content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Linq; using System.Runtime.InteropServices; namespace AzureTableFramework.Core { public static partial class Utils { public static string CharactersOnly(this string val) { return val.ToCharArray().Where(Char.IsLetterOrDigit).Aggregate("", (current, c) => current + c); } public static UInt32 Hash(Byte[] data) { return Hash(data, 0xc58f1a7b); } private const UInt32 m = 0x5bd1e995; private const Int32 r = 24; [StructLayout(LayoutKind.Explicit)] private struct BytetoUInt32Converter { [FieldOffset(0)] public Byte[] Bytes; [FieldOffset(0)] public UInt32[] UInts; } public static UInt32 Hash(Byte[] data, UInt32 seed) { Int32 length = data.Length; if (length == 0) return 0; UInt32 h = seed ^ (UInt32)length; Int32 currentIndex = 0; // array will be length of Bytes but contains Uints // therefore the currentIndex will jump with +1 while length will jump with +4 UInt32[] hackArray = new BytetoUInt32Converter { Bytes = data }.UInts; while (length >= 4) { UInt32 k = hackArray[currentIndex++]; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; length -= 4; } currentIndex *= 4; // fix the length switch (length) { case 3: h ^= (UInt16)(data[currentIndex++] | data[currentIndex++] << 8); h ^= (UInt32)data[currentIndex] << 16; h *= m; break; case 2: h ^= (UInt16)(data[currentIndex++] | data[currentIndex] << 8); h *= m; break; case 1: h ^= data[currentIndex]; h *= m; break; default: break; } // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } } }
29.209302
109
0.42914
[ "MIT" ]
JeffHughes/AzureTableFramework
src/Utils/Strings.cs
2,514
C#
namespace Caf.Projects.CafModelingRegionalSoilConditioningIndex.Csip.Common.Models.Json { /// <summary> /// Represents important values obtained from results of a WEPS simulation /// </summary> public class WepsResponseV5_2 : IErosionModelResponse { public string Suid { get; set; } public string Status { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } // Name of rotation treatment public string RotationName { get; set; } // wind_eros: Wind erosion (computed by WEPS) (ton/acre/year) public double WindErosion { get; set; } // sci_er_factor: SCI Erosion Rate subfactor (unitless) public double ER { get; set; } // sci_om_factor: SCI Organic Matter subfactor (unitless) public double OM { get; set; } // sci_fo_factor: SCI Field Operations subfactor (unitless) public double FO { get; set; } // avg_all_stir: Average STIR (unitless) public double Stir { get; set; } // average_biomass: Average biomass (ton/acre/year) public double AverageBiomass { get; set; } } }
31.184211
88
0.634599
[ "CC0-1.0" ]
cafltar/CafModelingRegionalSoilConditioningIndex_Csip
src/dotnet/Csip.Common/Models/Json/WepsResponseV5_2.cs
1,187
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IntelliMood.Data.Models; using IntelliMood.Web.Infrastructure.Mapper; namespace IntelliMood.Web.Models.UserViewModels { public class UserListViewModel : IMapFrom<User> { public string Id { get; set; } public string UserName { get; set; } } }
22.117647
51
0.728723
[ "MIT" ]
GenchoBG/SmartDiary
IntelliMood.Web/Models/UserViewModels/UserListViewModel.cs
378
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace Microsoft.Data.Entity.Design.Model.Commands { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Data.Entity.Design.Model.Entity; using Microsoft.Data.Entity.Design.Model.Mapping; /// <summary> /// Use this command to change the the FunctionScalarProperty. /// </summary> internal class ChangeFunctionScalarPropertyCommand : Command { private readonly FunctionScalarProperty _existingFunctionScalarProperty; private readonly List<Property> _propChain; private readonly NavigationProperty _pointingNavProp; private readonly Parameter _param; private readonly string _version; private FunctionScalarProperty _updatedFunctionScalarProperty; /// <summary> /// Change the property pointed to by the FunctionScalarProperty. This may involve /// change of property chain, change to/from a NavProp property or change of parameter. /// </summary> /// <param name="fspToChange">FunctionScalarProperty to be changed</param> /// <param name="newPropertiesChain">property chain for new Property</param> /// <param name="newPointingNavProp">NavProp for new Property (null indicates new Property not reached via NavProp)</param> /// <param name="newParameter">Parameter to which new Property should be mapped (null indicates use existing Parameter)</param> /// <param name="newVersion">Version attribute for new Property (null indicates use existing value). Only appropriate for Update Functions</param> internal ChangeFunctionScalarPropertyCommand( FunctionScalarProperty fspToChange, List<Property> newPropertiesChain, NavigationProperty newPointingNavProp, Parameter newParameter, string newVersion) { Debug.Assert( !(newPropertiesChain == null && newPointingNavProp == null && newParameter == null), "Not all of newPropertiesChain, newPointingNavProp, newParameter can be null"); if (newPropertiesChain == null && newPointingNavProp == null && newParameter == null) { return; } Debug.Assert( string.IsNullOrEmpty(newVersion) || ModelConstants.FunctionScalarPropertyVersionOriginal.Equals(newVersion, StringComparison.Ordinal) || ModelConstants.FunctionScalarPropertyVersionCurrent.Equals(newVersion, StringComparison.Ordinal), "newVersion must be empty or " + ModelConstants.FunctionScalarPropertyVersionOriginal + " or " + ModelConstants.FunctionScalarPropertyVersionCurrent + ". Actual value: " + newVersion); CommandValidation.ValidateFunctionScalarProperty(fspToChange); if (newPointingNavProp != null) { CommandValidation.ValidateNavigationProperty(newPointingNavProp); } if (newParameter != null) { CommandValidation.ValidateParameter(newParameter); } _existingFunctionScalarProperty = fspToChange; _propChain = newPropertiesChain; _pointingNavProp = newPointingNavProp; _param = newParameter; _version = newVersion; } /// <summary> /// This method lets you change just the version of a FunctionScalarProperty. /// </summary> /// <param name="fspToChange">FunctionScalarProperty to be changed</param> /// <param name="version">New version value</param> internal ChangeFunctionScalarPropertyCommand(FunctionScalarProperty fspToChange, string version) { Debug.Assert(version != null, "Version can't be null"); Debug.Assert( ModelConstants.FunctionScalarPropertyVersionOriginal.Equals(version, StringComparison.Ordinal) || ModelConstants.FunctionScalarPropertyVersionCurrent.Equals(version, StringComparison.Ordinal), "Version must be " + ModelConstants.FunctionScalarPropertyVersionOriginal + " or " + ModelConstants.FunctionScalarPropertyVersionCurrent + ". Actual value: " + version); CommandValidation.ValidateFunctionScalarProperty(fspToChange); _existingFunctionScalarProperty = fspToChange; _version = version; } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ExitingFunctionScalarProperty")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "InvokeInternal")] protected override void InvokeInternal(CommandProcessorContext cpc) { Debug.Assert(cpc != null, "InvokeInternal is called when ExitingFunctionScalarProperty is null."); // safety check, this should never be hit if (_existingFunctionScalarProperty == null) { throw new InvalidOperationException("InvokeInternal is called when ExitingFunctionScalarProperty is null."); } if (_propChain == null && _pointingNavProp == null && _param == null && _version != null) { // setting new version only if (string.Compare(_existingFunctionScalarProperty.Version.Value, _version, StringComparison.CurrentCulture) != 0) { var mfAncestor = _existingFunctionScalarProperty.GetParentOfType(typeof(ModificationFunction)) as ModificationFunction; Debug.Assert( mfAncestor != null, "Bad attempt to set version on FunctionScalarProperty which does not have a ModificationFunction ancestor"); if (mfAncestor != null) { Debug.Assert( mfAncestor.FunctionType == ModificationFunctionType.Update, "Bad attempt to set version on FunctionScalarProperty which has a ModificationFunction ancestor whose FunctionType is " + mfAncestor.FunctionType.ToString() + ". Should be " + ModificationFunctionType.Update.ToString()); if (mfAncestor.FunctionType == ModificationFunctionType.Update) { _existingFunctionScalarProperty.Version.Value = _version; } } } _updatedFunctionScalarProperty = _existingFunctionScalarProperty; return; } // if not just setting version then need to delete and re-create FunctionScalarProperty // to allow for changes in properties chain // where nulls have been passed in, use existing values (except for _pointingNavProp where null // indicates "use no NavProp for the new property") var mf = _existingFunctionScalarProperty.GetParentOfType(typeof(ModificationFunction)) as ModificationFunction; Debug.Assert(mf != null, "Bad attempt to change FunctionScalarProperty which does not have a ModificationFunction ancestor"); if (mf == null) { return; } var propChain = (_propChain != null ? _propChain : _existingFunctionScalarProperty.GetMappedPropertiesList()); var parameter = (_param != null ? _param : _existingFunctionScalarProperty.ParameterName.Target); var version = (_version != null ? _version : _existingFunctionScalarProperty.Version.Value); // now construct delete command for existing FunctionScalarProperty followed by create with new properties var cmd1 = _existingFunctionScalarProperty.GetDeleteCommand(); var cmd2 = new CreateFunctionScalarPropertyTreeCommand(mf, propChain, _pointingNavProp, parameter, version); cmd2.PostInvokeEvent += (o, eventsArgs) => { _updatedFunctionScalarProperty = cmd2.FunctionScalarProperty; Debug.Assert( _updatedFunctionScalarProperty != null, "CreateFunctionScalarPropertyTreeCommand should not result in null FunctionScalarProperty"); }; var cp = new CommandProcessor(cpc, cmd1, cmd2); try { cp.Invoke(); } finally { _updatedFunctionScalarProperty = null; } } internal FunctionScalarProperty FunctionScalarProperty { get { return _updatedFunctionScalarProperty; } } } }
51.418079
154
0.632897
[ "Apache-2.0" ]
Cireson/EntityFramework6
src/EFTools/EntityDesignModel/Commands/ChangeFunctionScalarPropertyCommand.cs
9,103
C#
using FluentValidation; namespace Gear.ProjectManagement.Manager.Domain.Activities.Commands.BulkActions.MoveActivitiesToList { public class MoveActivitiesToListCommandValidator : AbstractValidator<MoveActivitiesToListCommand> { public MoveActivitiesToListCommandValidator() { RuleFor(a => a.ActivityListId).NotEmpty(); RuleFor(a => a.ActivityListId).NotNull().NotEmpty(); } } }
29.4
102
0.714286
[ "MIT" ]
indrivo/bizon360_pm
IndrivoPM/Gear.ProjectManagement.Application/Domain/Activities/Commands/BulkActions/MoveActivitiesToList/MoveActivitiesToListCommandValidator.cs
443
C#
using System; namespace it.unifi.dsi.stlab.math.algebra { public abstract class AlgebraConstraint { public abstract void check (); } }
12.909091
41
0.739437
[ "MIT" ]
massimo-nocentini/network-reasoner
it.unifi.dsi.stlab.math.algebra/constaints/AlgebraConstraint.cs
142
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Orders.Serialization; using QuantConnect.Securities; namespace QuantConnect.Tests.Common.Orders { [TestFixture] public class OrderEventTests { [Test] public void JsonIgnores() { var order = new MarketOrder(Symbols.BTCUSD, 0.123m, DateTime.UtcNow); var json = JsonConvert.SerializeObject(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero), new OrderEventJsonConverter("id")); Assert.IsFalse(json.Contains("Message")); Assert.IsFalse(json.Contains("Message")); Assert.IsFalse(json.Contains("LimitPrice")); Assert.IsFalse(json.Contains("StopPrice")); json = JsonConvert.SerializeObject(new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero, "This is a message") { LimitPrice = 1, StopPrice = 2 }); Assert.IsTrue(json.Contains("Message")); Assert.IsTrue(json.Contains("This is a message")); Assert.IsTrue(json.Contains("LimitPrice")); Assert.IsTrue(json.Contains("StopPrice")); } [Test] public void RoundTripSerialization() { var order = new MarketOrder(Symbols.BTCUSD, 0.123m, DateTime.UtcNow); var orderEvent = new OrderEvent(order, DateTime.UtcNow, OrderFee.Zero) { Message = "Pepe", Status = OrderStatus.PartiallyFilled, StopPrice = 1, LimitPrice = 2, FillPrice = 11, FillQuantity = 12, FillPriceCurrency = "USD", Id = 55, Quantity = 16 }; var converter = new OrderEventJsonConverter("id"); var serializeObject = JsonConvert.SerializeObject(orderEvent, converter); // OrderFee zero uses null currency and should be ignored when serializing Assert.IsFalse(serializeObject.Contains(Currencies.NullCurrency)); Assert.IsFalse(serializeObject.Contains("order-fee-amount")); Assert.IsFalse(serializeObject.Contains("order-fee-currency")); var deserializeObject = JsonConvert.DeserializeObject<OrderEvent>(serializeObject, converter); Assert.AreEqual(orderEvent.Symbol, deserializeObject.Symbol); Assert.AreEqual(orderEvent.StopPrice, deserializeObject.StopPrice); // there is a small loss of precision because we use double Assert.AreEqual(orderEvent.UtcTime.Ticks, deserializeObject.UtcTime.Ticks, 5); Assert.AreEqual(orderEvent.OrderId, deserializeObject.OrderId); Assert.AreEqual(orderEvent.AbsoluteFillQuantity, deserializeObject.AbsoluteFillQuantity); Assert.AreEqual(orderEvent.Direction, deserializeObject.Direction); Assert.AreEqual(orderEvent.FillPrice, deserializeObject.FillPrice); Assert.AreEqual(orderEvent.FillPriceCurrency, deserializeObject.FillPriceCurrency); Assert.AreEqual(orderEvent.FillQuantity, deserializeObject.FillQuantity); Assert.AreEqual(orderEvent.Id, deserializeObject.Id); Assert.AreEqual(orderEvent.IsAssignment, deserializeObject.IsAssignment); Assert.AreEqual(orderEvent.LimitPrice, deserializeObject.LimitPrice); Assert.AreEqual(orderEvent.Message, deserializeObject.Message); Assert.AreEqual(orderEvent.Quantity, deserializeObject.Quantity); Assert.AreEqual(orderEvent.Status, deserializeObject.Status); Assert.AreEqual(orderEvent.OrderFee.Value.Amount, deserializeObject.OrderFee.Value.Amount); Assert.AreEqual(orderEvent.OrderFee.Value.Currency, deserializeObject.OrderFee.Value.Currency); } [Test] public void NonNullOrderFee() { var order = new MarketOrder(Symbols.BTCUSD, 0.123m, DateTime.UtcNow); var orderEvent = new OrderEvent(order, DateTime.UtcNow, new OrderFee(new CashAmount(88, Currencies.USD))); var converter = new OrderEventJsonConverter("id"); var serializeObject = JsonConvert.SerializeObject(orderEvent, converter); var deserializeObject = JsonConvert.DeserializeObject<OrderEvent>(serializeObject, converter); Assert.IsTrue(serializeObject.Contains("order-fee-amount")); Assert.IsTrue(serializeObject.Contains("order-fee-currency")); Assert.AreEqual(orderEvent.OrderFee.Value.Amount, deserializeObject.OrderFee.Value.Amount); Assert.AreEqual(orderEvent.OrderFee.Value.Currency, deserializeObject.OrderFee.Value.Currency); } } }
47.076271
121
0.673987
[ "Apache-2.0" ]
michael-sena/Lean
Tests/Common/Orders/OrderEventTests.cs
5,557
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("WpfApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WpfApplication1")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
41.339286
94
0.72959
[ "BSD-3-Clause" ]
chliebel/dotnetpro-flexbox-xaml
xaml/WpfApplication1/Properties/AssemblyInfo.cs
2,318
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. using System; namespace Mosa.UnitTest.Collection { public static class BoxingTests { public static byte BoxU1(byte value) { object o = value; return (byte)o; } public static bool EqualsU1(byte value) { object o = value; return o.Equals(value); } public static ushort BoxU2(ushort value) { object o = value; return (ushort)o; } public static bool EqualsU2(ushort value) { object o = value; return o.Equals(value); } public static uint BoxU4(uint value) { object o = value; return (uint)o; } public static bool EqualsU4(uint value) { object o = value; return o.Equals(value); } public static ulong BoxU8(ulong value) { object o = value; return (ulong)o; } public static bool EqualsU8(ulong value) { object o = value; return o.Equals(value); } public static sbyte BoxI1(sbyte value) { object o = value; return (sbyte)o; } public static bool EqualsI1(sbyte value) { object o = value; return o.Equals(value); } public static short BoxI2(short value) { object o = value; return (short)o; } public static bool EqualsI2(short value) { object o = value; return o.Equals(value); } public static int BoxI4(int value) { object o = value; return (int)o; } public static bool EqualsI4(int value) { object o = value; return o.Equals(value); } public static long BoxI8(long value) { object o = value; return (long)o; } public static bool EqualsI8(long value) { object o = value; return o.Equals(value); } public static float BoxR4(float value) { object o = value; return (float)o; } public static bool EqualsR4(float value) { object o = value; return o.Equals(value); } public static double BoxR8(double value) { object o = value; return (double)o; } public static bool EqualsR8(double value) { object o = value; return o.Equals(value); } public static char BoxC(char value) { object o = value; return (char)o; } public static bool EqualsC(char value) { object o = value; return o.Equals(value); } } }
15.847222
67
0.623138
[ "BSD-3-Clause" ]
carverh/ShiftOS
Source/Mosa.UnitTest.Collection/BoxingTests.cs
2,284
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class UnityFx_Async_CompilerServices_AsyncAwaiter_1_Knight_Core_WaitAsync_Binding_WaitForSecondsRequest_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>); args = new Type[]{}; method = type.GetMethod("get_IsCompleted", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_IsCompleted_0); args = new Type[]{}; method = type.GetMethod("GetResult", flag, null, args, null); app.RegisterCLRMethodRedirection(method, GetResult_1); app.RegisterCLRCreateDefaultInstance(type, () => new UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>()); } static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest> instance_of_this_method) { ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.Object: { __mStack[ptr_of_this_method->Value] = instance_of_this_method; } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { var t = __domain.GetType(___obj.GetType()) as CLRType; t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method); } } break; case ObjectTypes.StaticFieldReference: { var t = __domain.GetType(ptr_of_this_method->Value); if(t is ILType) { ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method; } break; } } static StackObject* get_IsCompleted_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest> instance_of_this_method = (UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>)typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.IsCompleted; ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* GetResult_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest> instance_of_this_method = (UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>)typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.GetResult(); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
50.606299
390
0.650226
[ "MIT" ]
JansonC/knight
knight-client/Assets/Game/Script/Generate/ILRuntime/UnityFx_Async_CompilerServices_AsyncAwaiter_1_Knight_Core_Wait_t.cs
6,427
C#
using Microsoft.AspNetCore.Mvc.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DevIO.UI.Site.Models { public class Aluno { public Aluno() { Id = Guid.NewGuid(); } public Guid Id { get; set; } public string Nome { get; set; } public string Email { get; set; } public DateTime DataNascimento { get; set; } } }
21.181818
52
0.609442
[ "MIT" ]
philipeformagio/sandbox-studies
AppModelo/src/DevIO.UI.Site/Models/Aluno.cs
468
C#
// Copyright (C) 2015 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alexey Kulakov // Created: 2015.05.21 using System; using System.Linq; using NUnit.Framework; using Xtensive.Core; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Issues.IssueJira0584_IncorrectMappingOfColumnInQueryModel; using Xtensive.Sql; using Xtensive.Sql.Dml; namespace Xtensive.Orm.Tests.Issues.IssueJira0584_IncorrectMappingOfColumnInQueryModel { public enum PacioliAccountType { Passive, Active, ActivePassive } public enum DealType { RoundsPlannedDeal, LeftOffPlannedDeal, RealDeal, } public enum DebitCredit { Debit, Credit, } [KeyGenerator(KeyGeneratorKind.None)] public abstract class EntityBase : Entity { [Field, Key] public Guid Id { get; private set; } protected EntityBase(Guid id) : base(id) { } } public abstract class TablePartBase : EntityBase { [Field] public FinToolKind Owner { get; private set; } protected TablePartBase(Guid id, FinToolKind owner) : base(id) { Owner = owner; } [HierarchyRoot] public class FinToolKind : EntityBase { [Field(Nullable = false, Length = 100)] public string Name { get; set; } [Field(Nullable = false, Length = 100)] public string FullName { get; set; } [Field] public FinToolKind Parent { get; set; } [Field] public string Entity { get; set; } [Field] public bool Quantitative { get; set; } [Field] [Association(PairTo = "Owner", OnTargetRemove = OnRemoveAction.Clear, OnOwnerRemove = OnRemoveAction.Cascade)] public EntitySet<TpPriceCalc> PriceCalc { get; private set; } public FinToolKind(Guid id) : base(id) { } [HierarchyRoot] public class TpPriceCalc : TablePartBase { [Field(Nullable = false)] public PacioliAccount Account { get; set; } [Field] public bool OnlyCurrentType { get; set; } public TpPriceCalc(Guid id, FinToolKind owner) : base(id, owner) { } } } } [HierarchyRoot] public abstract class FinToolBase : EntityBase { [Field(Length = 300, Nullable = false)] public virtual string Name { get; set; } [Field(Length = 50, Nullable = false)] public string DocumentIdentifier { get; set; } [Field(Nullable = false)] public TablePartBase.FinToolKind FinToolKind { get; set; } [Field(Nullable = false)] public virtual Currency Cur { get; set; } public FinToolBase(Guid id) : base(id) { } } public class OtherFinTools : FinToolBase { public OtherFinTools(Guid id) : base(id) { } } [HierarchyRoot] public class Status : EntityBase { [Field] public string Description { get; set; } [Field] public string Name { get; set; } public Status(Guid id) : base(id) { } } [HierarchyRoot] public class Currency : EntityBase { [Field(Length = 20)] public string CurCode { get; set; } [Field(Length = 3)] public string DigitCode { get; set; } [Field] public int? MinorUnits { get; set; } [Field(Length = 400, Nullable = false)] public string Name { get; set; } [Field(Length = 400)] public string Description { get; set; } [Field(Length = 20)] public string Sign { get; set; } [Field(Length = 400)] public string EngName { get; set; } public Currency(Guid id) : base(id) { } } [HierarchyRoot] public abstract class Subject : EntityBase { [Field(Length = 8)] public int? Code { get; set; } [Field(Nullable = false, Length = 255)] public string Name { get; set; } [Field(Nullable = false, Length = 400)] public string FullName { get; set; } [Field(Nullable = false, Length = 20)] public virtual string Identifier { get; set; } public Subject(Guid id) : base(id) { } } public abstract class Portfolio : Subject { [Field(Length = 400)] public string LegalName { get; set; } [Field] public DateTime? DateOnService { get; set; } [Field] public DateTime? DateRemovalFromService { get; set; } [Field] public DateTime? EisTransitionDate { get; set; } [Field] public DateTime? ImportedToDate { get; set; } protected Portfolio(Guid id) : base(id) { } } public class RealPortfolio : Portfolio { public RealPortfolio(Guid id) :base(id) {} } public abstract class DocumentBase : EntityBase { [Field] public Status Status { get; set; } public DocumentBase(Guid id) : base(id) { } } [HierarchyRoot] public abstract class OperationBase : DocumentBase { [Field(Length = 50)] public string Number { get; set; } [Field] public DateTime? InputDate { get; set; } [Field] public DateTime? AuthorizationDate { get; set; } [Field] public OperationType OperationType { get; set; } [Field] public Portfolio Portfolio { get; set; } [Field(Length = 1024)] public string Comment { get; set; } protected OperationBase(Guid id) : base(id) { } } public class TechOperation : OperationBase { [Field] public string ForeignId { get; set; } public TechOperation(Guid id) : base(id) { } } [HierarchyRoot] public class OperationType : EntityBase { [Field(Length = 255, Nullable = false)] public string Name { get; set; } [Field(Length = 255)] public string Description { get; set; } [Field] public PacioliAccount Account { get; set; } public OperationType(Guid id) : base(id) { } } [HierarchyRoot] public class PacioliAccount : EntityBase { [Field, Key] public Guid Id { get; set; } [Field] public PacioliAccount Parent { get; set; } [Field(Length = 128, Nullable = false)] public string Name { get; set; } [Field(Length = 4000)] public string Description { get; set; } [Field(Length = 32, Nullable = false)] public string Code { get; set; } [Field(Length = 32, Nullable = false)] public string FastAccess { get; set; } [Field] public PacioliAccountType AccountType { get; set; } public PacioliAccount(Guid id) : base(id) { } } [HierarchyRoot] public class PacioliPosting : DocumentBase { [Field] public FinToolBase FinDebit { get; set; } [Field] public FinToolBase FinCredit { get; set; } [Field(Nullable = false)] public Portfolio BalanceHolder { get; set; } [Field] public string Name { get; set; } [Field(Nullable = false)] public OperationBase Operation { get; set; } [Field] public string ForeignId { get; set; } [Field(Length = 12)] public string ForeignIdHash { get; set; } [Field] public PacioliAccount DebitAccount { get; set; } [Field] public PacioliAccount CreditAccount { get; set; } [Field] public DateTime CreationDate { get; set; } [Field] public DateTime? ExecutionDate { get; set; } [Field] public decimal Sum { get; set; } [Field] public Currency Currency { get; set; } [Field(Indexed = false)] public FinToolBase DebitFinTool { get; set; } [Field(Indexed = false)] public FinToolBase CreditFinTool { get; set; } [Field] public DealType Deal { get; set; } public PacioliPosting(Guid id) : base(id) { } } [HierarchyRoot] public class RegTransaction : Entity { [Field, Key] public Guid Id { get; set; } [Field] public DateTime? AuthorizeDate { get; set; } [Field] public DateTime? OperDate { get; set; } [Field] public Portfolio Portfolio { get; set; } [Field] public TablePartBase.FinToolKind FinTool { get; set; } [Field] public TransactionMethod Method { get; set; } [Field] public decimal Qty { get; set; } [Field] public decimal Price { get; set; } } public enum TransactionMethod { Debit } public class CustomPosting { public Guid Id { get; set; } public DateTime CreationDate { get; set; } public DateTime? ExecutionDate { get; set; } public Portfolio BalanceHolder { get; set; } public OperationBase Operation { get; set; } public OperationType OperationType { get; set; } public decimal Sum { get; set; } public Currency Currency { get; set; } public Status Status { get; set; } public PacioliAccount MasterAccount { get; set; } public PacioliAccount SlaveAccount { get; set; } public FinToolBase MasterFinToolBase { get; set; } public FinToolBase SlaveFinToolBase { get; set; } public TablePartBase.FinToolKind MasterFinToolKind { get; set; } public TablePartBase.FinToolKind SlaveFinToolKind { get; set; } } public static class GuidModifier { public static Guid ReplaceOne(Guid source, string replacement) { return Guid.Parse(source.ToString().Substring(0, 35) + replacement); } } [CompilerContainer(typeof(SqlExpression))] public class GuidCompilers { [Compiler(typeof(GuidModifier), "ReplaceOne", TargetKind.Method | TargetKind.Static)] public static SqlExpression CompileReplaceOne(SqlExpression sourceSqlExpression, SqlExpression replacement) { var stringId = SqlDml.Cast(sourceSqlExpression, SqlType.VarCharMax); var substringId = SqlDml.Substring(stringId, 0, 35); return SqlDml.Cast(SqlDml.Concat(substringId, replacement), SqlType.Guid); } } } namespace Xtensive.Orm.Tests.Issues { public class IssueJira0584_IncorrectMappingOfColumnInQuery : AutoBuildTest { private ProviderKind? previousProviderKind; [Test(Description = "Case when calculated column in the midle of selected columns averege")] public void IncludeProviderOptimizationTest01() { EnsureRightDateIsInStorage(ProviderKind.IncludeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var priceCalculation = from tablePart in Query.All<TablePartBase.FinToolKind.TpPriceCalc>() where !tablePart.OnlyCurrentType select tablePart; var masterDebit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, Sum = (posting.DebitAccount.AccountType==PacioliAccountType.Passive) ? -posting.Sum : posting.Sum, MasterAccount = posting.DebitAccount, MasterFinToolBase = posting.FinDebit, SlaveAccount = posting.CreditAccount, SlaveFinToolBase = posting.FinCredit }; var masterCredit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, Sum = posting.CreditAccount.AccountType==PacioliAccountType.Active || posting.CreditAccount.AccountType==PacioliAccountType.ActivePassive ? -posting.Sum : posting.Sum, MasterAccount = posting.CreditAccount, MasterFinToolBase = posting.FinCredit, SlaveAccount = posting.DebitAccount, SlaveFinToolBase = posting.FinDebit }; var usefulColumns = masterCredit.Union(masterDebit); var readyForFilterQuery = from joinResult in usefulColumns .LeftJoin(priceCalculation, a => a.SlaveAccount, a => a.Account, (pp, ps) => new {pp, ps}) .LeftJoin(priceCalculation, a => a.pp.MasterAccount, a => a.Account, (a, pm) => new {a.pp, a.ps, pm}) let item = joinResult.pp select new CustomPosting() { Id = item.Id, Status = item.Status, BalanceHolder = item.BalanceHolder, CreationDate = item.CreationDate, Currency = item.Currency, ExecutionDate = item.ExecutionDate, Operation = item.Operation, OperationType = item.Operation.OperationType, Sum = item.Sum, MasterAccount = item.MasterAccount, MasterFinToolBase = item.MasterFinToolBase, SlaveAccount = item.SlaveAccount, SlaveFinToolBase = item.SlaveFinToolBase, MasterFinToolKind = joinResult.pm!=null ? joinResult.pm.Owner : item.MasterFinToolBase.FinToolKind, SlaveFinToolKind = joinResult.pm!=null ? joinResult.ps.Owner : item.SlaveFinToolBase.FinToolKind, }; var id = session.Query.All<PacioliAccount>().First().Id; Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id == id).LongCount()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Code == "123").LongCount()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Code.In("123")).LongCount()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).ToArray()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).LongCount()); } } [Test(Description = "Case when calculated column is first columns of selection")] public void IncludeProviderOptimizationTest02() { EnsureRightDateIsInStorage(ProviderKind.IncludeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var priceCalculation = from tablePart in Query.All<TablePartBase.FinToolKind.TpPriceCalc>() where !tablePart.OnlyCurrentType select tablePart; var masterDebit = from posting in Query.All<PacioliPosting>() select new { Sum = (posting.DebitAccount.AccountType==PacioliAccountType.Passive) ? -posting.Sum : posting.Sum, Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.DebitAccount, MasterFinToolBase = posting.FinDebit, SlaveAccount = posting.CreditAccount, SlaveFinToolBase = posting.FinCredit }; var masterCredit = from posting in Query.All<PacioliPosting>() select new { Sum = posting.CreditAccount.AccountType==PacioliAccountType.Active || posting.CreditAccount.AccountType==PacioliAccountType.ActivePassive ? -posting.Sum : posting.Sum, Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.CreditAccount, MasterFinToolBase = posting.FinCredit, SlaveAccount = posting.DebitAccount, SlaveFinToolBase = posting.FinDebit }; var usefulColumns = masterCredit.Union(masterDebit); var readyForFilterQuery = from joinResult in usefulColumns .LeftJoin(priceCalculation, a => a.SlaveAccount, a => a.Account, (pp, ps) => new {pp, ps}) .LeftJoin(priceCalculation, a => a.pp.MasterAccount, a => a.Account, (a, pm) => new {a.pp, a.ps, pm}) let item = joinResult.pp select new CustomPosting { Id = item.Id, Status = item.Status, BalanceHolder = item.BalanceHolder, CreationDate = item.CreationDate, Currency = item.Currency, ExecutionDate = item.ExecutionDate, Operation = item.Operation, OperationType = item.Operation.OperationType, Sum = item.Sum, MasterAccount = item.MasterAccount, MasterFinToolBase = item.MasterFinToolBase, SlaveAccount = item.SlaveAccount, SlaveFinToolBase = item.SlaveFinToolBase, MasterFinToolKind = joinResult.pm!=null ? joinResult.pm.Owner : item.MasterFinToolBase.FinToolKind, SlaveFinToolKind = joinResult.pm!=null ? joinResult.ps.Owner : item.SlaveFinToolBase.FinToolKind, }; var id = session.Query.All<PacioliAccount>().First().Id; Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id == id).LongCount()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Code == "123").LongCount()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Code.In("123")).LongCount()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).ToArray()); Assert.DoesNotThrow(()=>readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).LongCount()); } } [Test(Description = "Case when calculated column is the second column in selection")] public void IncludeProviderOptimizationTest03() { EnsureRightDateIsInStorage(ProviderKind.IncludeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var priceCalculation = from tablePart in Query.All<TablePartBase.FinToolKind.TpPriceCalc>() where !tablePart.OnlyCurrentType select tablePart; var masterDebit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Sum = (posting.DebitAccount.AccountType==PacioliAccountType.Passive) ? -posting.Sum : posting.Sum, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.DebitAccount, MasterFinToolBase = posting.FinDebit, SlaveAccount = posting.CreditAccount, SlaveFinToolBase = posting.FinCredit }; var masterCredit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Sum = posting.CreditAccount.AccountType==PacioliAccountType.Active || posting.CreditAccount.AccountType==PacioliAccountType.ActivePassive ? -posting.Sum : posting.Sum, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.CreditAccount, MasterFinToolBase = posting.FinCredit, SlaveAccount = posting.DebitAccount, SlaveFinToolBase = posting.FinDebit }; var usefulColumns = masterCredit.Union(masterDebit); var readyForFilterQuery = from joinResult in usefulColumns .LeftJoin(priceCalculation, a => a.SlaveAccount, a => a.Account, (pp, ps) => new {pp, ps}) .LeftJoin(priceCalculation, a => a.pp.MasterAccount, a => a.Account, (a, pm) => new {a.pp, a.ps, pm}) let item = joinResult.pp select new CustomPosting { Id = item.Id, Status = item.Status, BalanceHolder = item.BalanceHolder, CreationDate = item.CreationDate, Currency = item.Currency, ExecutionDate = item.ExecutionDate, Operation = item.Operation, OperationType = item.Operation.OperationType, Sum = item.Sum, MasterAccount = item.MasterAccount, MasterFinToolBase = item.MasterFinToolBase, SlaveAccount = item.SlaveAccount, SlaveFinToolBase = item.SlaveFinToolBase, MasterFinToolKind = joinResult.pm!=null ? joinResult.pm.Owner : item.MasterFinToolBase.FinToolKind, SlaveFinToolKind = joinResult.pm!=null ? joinResult.ps.Owner : item.SlaveFinToolBase.FinToolKind, }; var id = session.Query.All<PacioliAccount>().First().Id; Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id == id).LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Code == "123").LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Code.In("123")).LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).ToArray()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).LongCount()); } } [Test(Description = "Case when calculated columns is right before the last columns in selection")] public void IncludeProviderOptimizationTest04() { EnsureRightDateIsInStorage(ProviderKind.IncludeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var priceCalculation = from tablePart in Query.All<TablePartBase.FinToolKind.TpPriceCalc>() where !tablePart.OnlyCurrentType select tablePart; var masterDebit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.DebitAccount, MasterFinToolBase = posting.FinDebit, SlaveAccount = posting.CreditAccount, Sum = (posting.DebitAccount.AccountType==PacioliAccountType.Passive) ? -posting.Sum : posting.Sum, SlaveFinToolBase = posting.FinCredit }; var masterCredit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.CreditAccount, MasterFinToolBase = posting.FinCredit, SlaveAccount = posting.DebitAccount, Sum = posting.CreditAccount.AccountType==PacioliAccountType.Active || posting.CreditAccount.AccountType==PacioliAccountType.ActivePassive ? -posting.Sum : posting.Sum, SlaveFinToolBase = posting.FinDebit }; var usefulColumns = masterCredit.Union(masterDebit); var readyForFilterQuery = from joinResult in usefulColumns .LeftJoin(priceCalculation, a => a.SlaveAccount, a => a.Account, (pp, ps) => new {pp, ps}) .LeftJoin(priceCalculation, a => a.pp.MasterAccount, a => a.Account, (a, pm) => new {a.pp, a.ps, pm}) let item = joinResult.pp select new CustomPosting { Id = item.Id, Status = item.Status, BalanceHolder = item.BalanceHolder, CreationDate = item.CreationDate, Currency = item.Currency, ExecutionDate = item.ExecutionDate, Operation = item.Operation, OperationType = item.Operation.OperationType, Sum = item.Sum, MasterAccount = item.MasterAccount, MasterFinToolBase = item.MasterFinToolBase, SlaveAccount = item.SlaveAccount, SlaveFinToolBase = item.SlaveFinToolBase, MasterFinToolKind = joinResult.pm!=null ? joinResult.pm.Owner : item.MasterFinToolBase.FinToolKind, SlaveFinToolKind = joinResult.pm!=null ? joinResult.ps.Owner : item.SlaveFinToolBase.FinToolKind, }; var id = session.Query.All<PacioliAccount>().First().Id; Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id == id).LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Code == "123").LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Code.In("123")).LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).ToArray()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).LongCount()); } } [Test (Description = "Case when calculated column is the last column in selection")] public void IncludeProviderOptimizationTest05() { EnsureRightDateIsInStorage(ProviderKind.IncludeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var priceCalculation = from tablePart in Query.All<TablePartBase.FinToolKind.TpPriceCalc>() where !tablePart.OnlyCurrentType select tablePart; var masterDebit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.DebitAccount, MasterFinToolBase = posting.FinDebit, SlaveAccount = posting.CreditAccount, SlaveFinToolBase = posting.FinCredit, Sum = (posting.DebitAccount.AccountType==PacioliAccountType.Passive) ? -posting.Sum : posting.Sum }; var masterCredit = from posting in Query.All<PacioliPosting>() select new { Id = posting.Id, Status = posting.Status, BalanceHolder = posting.BalanceHolder, CreationDate = posting.CreationDate, Currency = posting.Currency, ExecutionDate = posting.ExecutionDate, Operation = posting.Operation, OperationType = posting.Operation.OperationType, MasterAccount = posting.CreditAccount, MasterFinToolBase = posting.FinCredit, SlaveAccount = posting.DebitAccount, SlaveFinToolBase = posting.FinDebit, Sum = posting.CreditAccount.AccountType==PacioliAccountType.Active || posting.CreditAccount.AccountType==PacioliAccountType.ActivePassive ? -posting.Sum : posting.Sum, }; var usefulColumns = masterCredit.Union(masterDebit); var readyForFilterQuery = from joinResult in usefulColumns .LeftJoin(priceCalculation, a => a.SlaveAccount, a => a.Account, (pp, ps) => new {pp, ps}) .LeftJoin(priceCalculation, a => a.pp.MasterAccount, a => a.Account, (a, pm) => new {a.pp, a.ps, pm}) let item = joinResult.pp select new CustomPosting { Id = item.Id, Status = item.Status, BalanceHolder = item.BalanceHolder, CreationDate = item.CreationDate, Currency = item.Currency, ExecutionDate = item.ExecutionDate, Operation = item.Operation, OperationType = item.Operation.OperationType, Sum = item.Sum, MasterAccount = item.MasterAccount, MasterFinToolBase = item.MasterFinToolBase, SlaveAccount = item.SlaveAccount, SlaveFinToolBase = item.SlaveFinToolBase, MasterFinToolKind = joinResult.pm!=null ? joinResult.pm.Owner : item.MasterFinToolBase.FinToolKind, SlaveFinToolKind = joinResult.pm!=null ? joinResult.ps.Owner : item.SlaveFinToolBase.FinToolKind, }; var id = session.Query.All<PacioliAccount>().First().Id; Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id == id).LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Code == "123").LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Code.In("123")).LongCount()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).ToArray()); Assert.DoesNotThrow(() => readyForFilterQuery.Where(a => a.MasterAccount.Id.In(new[] { id })).LongCount()); } } [Test] public void AdditionalTest01() { EnsureRightDateIsInStorage(ProviderKind.IncludeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var portfolioId = session.Query.All<Portfolio>().Select(el=>el.Id).First(); var assistant = new {PortfolioId = portfolioId, PriceOnDate = DateTime.Now, DateOfFormation = DateTime.Now,}; var transactions = Session.Current.Query.All<RegTransaction>() .Where(a => a.AuthorizeDate!=null && a.OperDate!=null && a.Portfolio.Id==assistant.PortfolioId) .Where(a => a.AuthorizeDate.Value.Date <= assistant.DateOfFormation && a.OperDate.Value.Date <= assistant.PriceOnDate); var balanceFinTools = transactions.Select( z => new { z.FinTool, Sum = z.Method==TransactionMethod.Debit ? z.Qty : -z.Qty, SumPrice = z.Method==TransactionMethod.Debit ? z.Price : -z.Price }).GroupBy(r => r.FinTool) .Select(f => new {FinTool = f.Key, Summ = f.Sum(s => s.Sum), SummPrice = f.Sum(s => s.SumPrice)}) .Where(a => a.Summ!=0); Assert.DoesNotThrow(() => { balanceFinTools.Select(a => a.FinTool.Id).Distinct().ToArray(); }); } } [Test] public void TakeProviderOptimizationTest01() { EnsureRightDateIsInStorage(ProviderKind.TakeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var allPostings = Query.All<PacioliPosting>(); var masterDebit = allPostings.Select( posting => new { Id = GuidModifier.ReplaceOne(posting.Id, "1"), Posting = posting, Sum = posting.DebitAccount.AccountType==PacioliAccountType.Passive ? -posting.Sum : posting.Sum, MasterFinToolBase = posting.DebitFinTool }); var masterCredit = allPostings.Select( posting => new { Id = GuidModifier.ReplaceOne(posting.Id, "9"), Posting = posting, Sum = posting.CreditAccount.AccountType==PacioliAccountType.Active || posting.CreditAccount.AccountType==PacioliAccountType.ActivePassive ? -posting.Sum : posting.Sum, MasterFinToolBase = posting.CreditFinTool }); var concatination = masterCredit.Concat(masterDebit); var usefulColumnsSelection = from raw in concatination select new { Id = raw.Id, Posting = raw.Posting, Sum = raw.Sum, MasterFinToolBase = raw.MasterFinToolBase, }; var finalQuery = from raw in usefulColumnsSelection.Select( selectionItem => new { MasterFinToolBase = selectionItem.MasterFinToolBase, Sum = selectionItem.Sum, Id = selectionItem.Posting.Id }) where raw.MasterFinToolBase!=null group raw by new { MasterFinToolBase = raw.MasterFinToolBase } into grouping select new { MasterFinToolBase = grouping.Key.MasterFinToolBase, Sum = grouping.Sum(s => s.Sum), Id = grouping.Select(x => x.Id).First() }; Assert.DoesNotThrow(() => { finalQuery.ToArray(); }); transaction.Complete(); } } [Test] public void JoinAsSourceOfSetOperation() { EnsureRightDateIsInStorage(ProviderKind.TakeProvider); using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var tp = from q in Query.All<TablePartBase.FinToolKind.TpPriceCalc>() select new { q.Account, OnlyCurrentType = !q.OnlyCurrentType, FinToolKind = q.OnlyCurrentType ? Guid.Empty : q.Owner.Id }; var masterDebit = from q in Query.All<PacioliPosting>() select new { Id = q.Id, Posting = q, DebitCredit = DebitCredit.Debit, Status = q.Status, BalanceHolder = q.BalanceHolder, CreationDate = q.CreationDate, Currency = q.Currency, Deal = q.Deal, ExecutionDate = q.ExecutionDate, Sum = q.Sum, MasterAccount = q.DebitAccount, MasterFinToolBase = q.DebitFinTool, }; var masterCredit = from q in Query.All<PacioliPosting>() select new { Id = q.Id, Posting = q, DebitCredit = DebitCredit.Credit, Status = q.Status, BalanceHolder = q.BalanceHolder, CreationDate = q.CreationDate, Currency = q.Currency, Deal = q.Deal, ExecutionDate = q.ExecutionDate, Sum = q.Sum, MasterAccount = q.CreditAccount, MasterFinToolBase = q.CreditFinTool, }; var preResult = masterCredit.Concat(masterDebit); var result = from r in preResult.Join(tp.Distinct(), a => a.MasterAccount, a => a.Account, (a, pm) => new {pp = a, pm}) .LeftJoin(Query.All<TablePartBase.FinToolKind>(), a => a.pm.FinToolKind, a => a.Id, (a, b) => new {pp = a.pp, pm = a.pm, fk = b}) let q = r.pp select new { Id = q.Id, Posting = q.Posting, Status = q.Status, BalanceHolder = q.BalanceHolder, CreationDate = q.CreationDate, Currency = q.Currency, Deal = q.Deal, ExecutionDate = q.ExecutionDate, Sum = q.Sum, MasterAccount = q.MasterAccount, MasterFinToolBase = q.MasterFinToolBase, MasterFinToolKind = r.pm.OnlyCurrentType ? r.fk : q.MasterFinToolBase.FinToolKind, AccountType = q.MasterAccount.AccountType }; var xx = from a in result .Select( a => new { MasterFinToolBase = a.MasterFinToolBase, MasterFinToolKind = a.MasterFinToolKind, Currency = a.Currency, BalanceHolder = a.BalanceHolder, CreationDate = a.CreationDate, ExecutionDate = a.ExecutionDate, Deal = a.Deal, MasterAccount = a.MasterAccount, Sum = a.Sum, Posting = a.Posting }) where a.MasterFinToolBase!=null && a.MasterFinToolKind!=null group a by new { Currency = a.Currency, BalanceHolder = a.BalanceHolder, CreationDate = a.CreationDate, Deal = a.Deal, ExecutionDate = a.ExecutionDate, MasterAccount = a.MasterAccount, MasterFinToolBase = a.MasterFinToolBase } into gr select new { ExecutionDate = gr.Key.ExecutionDate, BalanceHolder = gr.Key.BalanceHolder, MasterFinToolBase = gr.Key.MasterFinToolBase, Currency = gr.Key.Currency, CreationDate = gr.Key.CreationDate, Deal = gr.Key.Deal, MasterAccount = gr.Key.MasterAccount, Sum = gr.Sum(s => s.Sum), Id = gr.Select(a => a.Posting).First().Id }; Assert.DoesNotThrow(() => result.Run()); } } private void PopulateDataForIncludeProvider() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var currency = new Currency(Guid.NewGuid()) { CurCode = "RU", Name = "Ruble" }; var debitPassiveAccount = new PacioliAccount(Guid.NewGuid()); debitPassiveAccount.AccountType = PacioliAccountType.Passive; debitPassiveAccount.Code = "12345"; debitPassiveAccount.Description = "debitPassiveAccount"; debitPassiveAccount.FastAccess = "debitPassiveAccount"; debitPassiveAccount.Name = "debitPassiveAccount"; var debitActiveAccount = new PacioliAccount(Guid.NewGuid()); debitActiveAccount.AccountType = PacioliAccountType.Active; debitActiveAccount.Code = "23456"; debitActiveAccount.Description = "debitActiveAccount"; debitActiveAccount.FastAccess = "debitActiveAccount"; debitActiveAccount.Name = "debitActiveAccount"; var debitActivePassiveAccount = new PacioliAccount(Guid.NewGuid()); debitActivePassiveAccount.AccountType = PacioliAccountType.ActivePassive; debitActivePassiveAccount.Code = "34567"; debitActivePassiveAccount.Description = "debitActivePassiveAccount"; debitActivePassiveAccount.FastAccess = "debitActivePassiveAccount"; debitActivePassiveAccount.Name = "debitActivePassiveAccount"; var creditPassiveAccount = new PacioliAccount(Guid.NewGuid()); creditPassiveAccount.AccountType = PacioliAccountType.Passive; creditPassiveAccount.Code = "45678"; creditPassiveAccount.Description = "creditPassiveAccount"; creditPassiveAccount.FastAccess = "creditPassiveAccount"; creditPassiveAccount.Name = "creditPassiveAccount"; var creditActiveAccount = new PacioliAccount(Guid.NewGuid()); creditActiveAccount.AccountType = PacioliAccountType.Active; creditActiveAccount.Code = "56789"; creditActiveAccount.Description = "creditActiveAccount"; creditActiveAccount.FastAccess = "creditActiveAccount"; creditActiveAccount.Name = "creditActiveAccount"; var creditActivePassiveAccount = new PacioliAccount(Guid.NewGuid()); creditActivePassiveAccount.AccountType = PacioliAccountType.ActivePassive; creditActivePassiveAccount.Code = "67890"; creditActivePassiveAccount.Description = "creditActivePassiveAccount"; creditActivePassiveAccount.FastAccess = "creditActivePassiveAccount"; creditActivePassiveAccount.Name = "creditActivePassiveAccount"; var fintoolkindOwner = new TablePartBase.FinToolKind(Guid.NewGuid()) { Name = "fgjlhjfglkhjfg", FullName = "jfhjhgfkdhkgjhfkgjh" }; var priceCalc1 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc1.OnlyCurrentType = true; priceCalc1.Account = debitActiveAccount; var priceCalc2 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc2.OnlyCurrentType = true; priceCalc2.Account = debitPassiveAccount; var priceCalc3 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc3.OnlyCurrentType = true; priceCalc3.Account = debitActivePassiveAccount; var priceCalc4 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc4.OnlyCurrentType = true; priceCalc4.Account = creditActiveAccount; var priceCalc5 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc5.OnlyCurrentType = true; priceCalc5.Account = creditPassiveAccount; var priceCalc6 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc6.OnlyCurrentType = true; priceCalc6.Account = creditActivePassiveAccount; var priceCalc7 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc7.OnlyCurrentType = false; priceCalc7.Account = debitActiveAccount; var priceCalc8 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc8.OnlyCurrentType = false; priceCalc8.Account = debitPassiveAccount; var priceCalc9 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc9.OnlyCurrentType = false; priceCalc9.Account = debitActivePassiveAccount; var priceCalc10 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc10.OnlyCurrentType = false; priceCalc10.Account = creditActiveAccount; var priceCalc11 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc11.OnlyCurrentType = false; priceCalc11.Account = creditPassiveAccount; var priceCalc12 = new TablePartBase.FinToolKind.TpPriceCalc(Guid.NewGuid(), fintoolkindOwner); priceCalc12.OnlyCurrentType = false; priceCalc12.Account = creditActivePassiveAccount; var posting1 = new PacioliPosting(Guid.NewGuid()); posting1.Sum = new decimal(11); posting1.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "dfhgkjhdfgkjhdfj", FullName = "dhsfhkjh khgkjdfhgkj", Identifier = "uyiyriet"}; posting1.CreationDate = DateTime.Now; posting1.CreditAccount = creditPassiveAccount; posting1.DebitAccount = debitPassiveAccount; posting1.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "aaaa", Name = "aaaa"}; posting1.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "bbbb", Name = "bbbb"}; posting1.Operation = new TechOperation(Guid.NewGuid()); var posting2 = new PacioliPosting(Guid.NewGuid()); posting2.Sum = new decimal(12); posting2.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "dfhgkjhdfg", FullName = "dhsfhkjh khgkj", Identifier = "udfjgkjhfdk"}; posting2.CreationDate = DateTime.Now; posting2.CreditAccount = creditPassiveAccount; posting2.DebitAccount = debitActiveAccount; posting2.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "cccc", Name = "cccc"}; posting2.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "dddd", Name = "dddd"}; posting2.Operation = new TechOperation(Guid.NewGuid()); var posting3 = new PacioliPosting(Guid.NewGuid()); posting3.Sum = new decimal(13); posting3.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "dfhgkjhdfj", FullName = "dhsfhkjh", Identifier = "utrtoiore"}; posting3.CreationDate = DateTime.Now; posting3.CreditAccount = creditPassiveAccount; posting3.DebitAccount = debitActivePassiveAccount; posting3.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "eeee", Name = "eeee"}; posting3.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "ffff", Name = "ffff"}; posting3.Operation = new TechOperation(Guid.NewGuid()); var posting4 = new PacioliPosting(Guid.NewGuid()); posting4.Sum = new decimal(14); posting4.BalanceHolder = new RealPortfolio(Guid.NewGuid()) { Name = "kjhdfgkjhdfj", FullName = "kjh khgkjdfhgkj", Identifier = "dfkgkfdj" }; posting4.CreationDate = DateTime.Now; posting4.CreditAccount = creditActiveAccount; posting4.DebitAccount = debitPassiveAccount; posting4.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "gggg", Name = "gggg"}; posting4.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "hhh", Name = "hhh"}; posting4.Operation = new TechOperation(Guid.NewGuid()); var posting5 = new PacioliPosting(Guid.NewGuid()); posting5.Sum = new decimal(-15); posting5.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "reotoihre", FullName = "fghdg hdufgihiu", Identifier = "ghdfgjhf"}; posting5.CreationDate = DateTime.Now; posting5.CreditAccount = creditActiveAccount; posting5.DebitAccount = debitActiveAccount; posting5.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "iii", Name = "iiii"}; posting5.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "jjj", Name = "jjj"}; posting5.Operation = new TechOperation(Guid.NewGuid()); var posting6 = new PacioliPosting(Guid.NewGuid()); posting6.Sum = new decimal(-14); posting6.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "hfgdhdfhjghhkj", FullName = "kjh jdfhghjdgh", Identifier = "jdhfkgjhfkjgh"}; posting6.CreationDate = DateTime.Now; posting6.CreditAccount = creditActiveAccount; posting6.DebitAccount = debitActivePassiveAccount; posting6.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "kkkk", Name = "kkkk"}; posting6.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "llll", Name = "llll"}; posting6.Operation = new TechOperation(Guid.NewGuid()); var posting7 = new PacioliPosting(Guid.NewGuid()); posting7.Sum = new decimal(-13); posting7.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "hjdjhfghjdfhg", FullName = "dfgjdfhkgkj khgkjdfhgkj", Identifier = "dfbghkjdfhgkj"}; posting7.CreationDate = DateTime.Now; posting7.CreditAccount = creditActivePassiveAccount; posting7.DebitAccount = debitPassiveAccount; posting7.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "mmmm", Name = "mmm"}; posting7.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "nnn", Name = "nnn"}; posting7.Operation = new TechOperation(Guid.NewGuid()); var posting8 = new PacioliPosting(Guid.NewGuid()); posting8.Sum = new decimal(130); posting8.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "yrietyiury", FullName = "dhkgkj khgkjdfhgkj", Identifier = "dfbghj"}; posting8.CreationDate = DateTime.Now; posting8.CreditAccount = creditActivePassiveAccount; posting8.DebitAccount = debitActiveAccount; posting8.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "oooo", Name = "ooo"}; posting8.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "ppp", Name = "ppp"}; posting8.Operation = new TechOperation(Guid.NewGuid()); var posting9 = new PacioliPosting(Guid.NewGuid()); posting9.Sum = new decimal(-113); posting9.BalanceHolder = new RealPortfolio(Guid.NewGuid()) {Name = "biibibibob", FullName = "nbknf riewuruiet", Identifier = "ncvbmnvbcm"}; posting9.CreationDate = DateTime.Now; posting9.CreditAccount = creditActivePassiveAccount; posting9.DebitAccount = debitActivePassiveAccount; posting9.FinDebit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "qqqq", Name = "qqq"}; posting9.FinCredit = new OtherFinTools(Guid.NewGuid()) {Cur = currency, FinToolKind = fintoolkindOwner, DocumentIdentifier = "rrr", Name = "rrr"}; posting9.Operation = new TechOperation(Guid.NewGuid()); transaction.Complete(); } } public void PopulateDataForTakeProvider() { using (var session = Domain.OpenSession()) using (var transaction = session.OpenTransaction()) { var status = new Status(Guid.NewGuid()) { Name = "aa" }; var currency = new Currency(Guid.NewGuid()) { Name = "aa", CurCode = "qwe", DigitCode = "123", EngName = "re" }; session.SaveChanges(); var port = new RealPortfolio(Guid.NewGuid()) { Name = "ww", FullName = "ee", Identifier = "w" }; var operation = new TechOperation(Guid.NewGuid()); operation.Status = status; session.SaveChanges(); var finToolKind = new TablePartBase.FinToolKind(Guid.NewGuid()) { Name = "aa", FullName = "qq" }; var finTool1 = new OtherFinTools(Guid.NewGuid()) { Name = "aa", DocumentIdentifier = "wewe", Cur = currency, FinToolKind = finToolKind }; var finTool2 = new OtherFinTools(Guid.NewGuid()) { Name = "aaw", DocumentIdentifier = "wewee", Cur = currency, FinToolKind = finToolKind, }; session.SaveChanges(); var pp = new PacioliAccount(Guid.NewGuid()) { AccountType = PacioliAccountType.Active, Name = "aa", FastAccess = "w", Code = "x" }; new PacioliPosting(Guid.NewGuid()) { Name = "a", Status = status, DebitAccount = pp, CreditAccount = pp, CreditFinTool = finTool1, DebitFinTool = finTool2, Sum = 1, Currency = currency, BalanceHolder = port, Operation = operation }; transaction.Complete(); } } public void EnsureRightDateIsInStorage(ProviderKind providerKind) { if (previousProviderKind.HasValue && previousProviderKind!=providerKind) { RebuildDomain(); previousProviderKind = providerKind; } switch (providerKind) { case ProviderKind.IncludeProvider: { PopulateDataForTakeProvider(); return; } case ProviderKind.TakeProvider: { PopulateDataForIncludeProvider(); return; } } } protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(CustomPosting).Assembly, typeof(CustomPosting).Namespace); configuration.UpgradeMode = DomainUpgradeMode.Recreate; return configuration; } } public enum ProviderKind { IncludeProvider, TakeProvider } }
40.050661
161
0.613027
[ "MIT" ]
SergeiPavlov/dataobjects-net
Orm/Xtensive.Orm.Tests/Issues/IssueJira0584_IncorrectMappingOfColumnInQuery.cs
54,551
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using MVCBlog.Data; namespace MVCBlog.Web.Areas.Identity.Pages.Account.Manage { public class Disable2faModel : PageModel { private readonly UserManager<User> _userManager; private readonly ILogger<Disable2faModel> _logger; public Disable2faModel( UserManager<User> userManager, ILogger<Disable2faModel> logger) { _userManager = userManager; _logger = logger; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGet() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!await _userManager.GetTwoFactorEnabledAsync(user)) { throw new InvalidOperationException($"Cannot disable 2FA for user with ID '{_userManager.GetUserId(User)}' as it's not currently enabled."); } return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false); if (!disable2faResult.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred disabling 2FA for user with ID '{_userManager.GetUserId(User)}'."); } _logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User)); StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app"; return RedirectToPage("./TwoFactorAuthentication"); } } }
35.15625
156
0.624444
[ "Apache-2.0" ]
3xp3rT/MyBlog
src/MVCBlog.Web/Areas/Identity/Pages/Account/Manage/Disable2fa.cshtml.cs
2,252
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; //GameService UI helper information //GameService Editor inspector foldout namespace GameplayFramework { internal enum ActionOnService { DoNothing = 0, Stop = 1, Restart = 2 } public abstract class GameService : MonoBehaviour { [SerializeField, HideInInspector, Multiline] string serviceAbout = "", serviceDescription = ""; [SerializeField, HideInInspector] bool waitForThisInitialization = false, useDelay = false; [SerializeField, HideInInspector] float delayAmount = 2f; [SerializeField, HideInInspector] ActionOnService whenError = ActionOnService.DoNothing, whenException = ActionOnService.DoNothing, whenCodeFailure = ActionOnService.DoNothing; protected internal abstract void OnTick(); protected internal virtual void OnInit() { } protected internal virtual IEnumerator OnInitAsync() { if (useDelay) { yield return new WaitForSeconds(delayAmount); } else { yield return null; } } protected virtual void OnRestart() { } protected virtual void OnStop() { } protected virtual void OnStartManual() { } bool isRunning = true; public bool IsRunning { get { return isRunning; } internal set { isRunning = value; } } internal bool WaitForThisInitialization { get { return waitForThisInitialization; } } public string AboutService { get { return serviceAbout; } } public string ServiceDescription { get { return serviceDescription; } } #region Logging protected void Check(System.Action Code) { #if KLOG_SUPPORT if (GameLevel.Instance == null) { try { Code?.Invoke(); } catch (System.Exception ex) { Debug.Log("Code execution failure in service. Error Messag: " + ex.Message); DoAction(whenCodeFailure); } } else { KLog.Check(Code); } #else Code?.Invoke(); #endif } protected void PrintLog(string message, Color color = default) { #if KLOG_SUPPORT if (GameLevel.Instance == null) { string ltxt = message; if (color != default) { ltxt = string.Format("<color=#{0:X2}{1:X2}{2:X2}>{3}</color> Service log: ", (byte)(color.r * 255f), (byte)(color.g * 255f), (byte)(color.b * 255f), message); Debug.Log(ltxt); } else { Debug.Log("Service log: " + ltxt); } } else { KLog.Print("Service log: " + message, color); } #endif } protected void PrintError(string message) { #if KLOG_SUPPORT if (GameLevel.Instance == null) { Debug.LogError("Service Error: " + message); } else { KLog.PrintError("Service Error: " + message); } DoAction(whenError); #endif } protected void PrintWarning(string message) { #if KLOG_SUPPORT if (GameLevel.Instance == null) { Debug.LogWarning("Service warning: " + message); } else { KLog.PrintWarning("Service warning: " + message); } #endif } protected void PrintException(Exception exception) { #if KLOG_SUPPORT exception.Source += Environment.NewLine + " At Service"; if (GameLevel.Instance == null) { Debug.LogException(exception); } else { KLog.PrintException(exception); } DoAction(whenException); #endif } protected void PrintException(Exception exception, UnityEngine.Object context) { #if KLOG_SUPPORT exception.Source += Environment.NewLine + " At Service"; if (GameLevel.Instance == null) { Debug.LogException(exception, context); } else { KLog.PrintException(exception, context); } DoAction(whenException); #endif } #endregion void DoAction(ActionOnService action) { if (action == ActionOnService.DoNothing) { return; } if (action == ActionOnService.Restart) { RestartService(); } else if (action == ActionOnService.Stop) { StopService(); } } public void StopService() { isRunning = false; StopAllCoroutines(); OnStop(); } public void StartServiceIfStopped() { if (isRunning) { return; } isRunning = true; OnInit(); StartCoroutine(OnInitAsync()); OnStartManual(); } public void RestartService() { isRunning = true; StopAllCoroutines(); OnInit(); StartCoroutine(OnInitAsync()); OnRestart(); } public void RemoveService() { GameServiceManager.RemoveService(this.GetType()); } } }
29.635417
120
0.513357
[ "MIT" ]
kaiyumcg/KAction
KAction/Code/GameService/GameService.cs
5,690
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Hotcakes.Modules.SearchInput { public partial class Settings { /// <summary> /// ViewLabel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.UserControl ViewLabel; /// <summary> /// ViewContentLabel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label ViewContentLabel; /// <summary> /// ViewSelectionLabel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.UserControl ViewSelectionLabel; /// <summary> /// ViewComboBox control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Telerik.Web.UI.RadComboBox ViewComboBox; } }
33.615385
84
0.518879
[ "MIT" ]
aburias/hotcakes-commerce-core
Website/DesktopModules/Hotcakes/SearchInput/Settings.ascx.designer.cs
1,750
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace estate_app { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.62963
70
0.644509
[ "MIT" ]
anegerega/Estate_App
src/estate_app/Program.cs
692
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using System.Windows.Forms; namespace ClearCanvas.Desktop.View.WinForms { /// <summary> /// WinForms implementation of <see cref="IWorkspaceView"/>. /// </summary> /// <remarks> /// <para> /// This class may subclassed if customization is desired. In this case, the <see cref="DesktopWindowView"/> /// class must also be subclassed in order to instantiate the subclass from /// its <see cref="DesktopWindowView.CreateWorkspaceView"/> method. /// </para> /// <para> /// Reasons for subclassing may include: overriding <see cref="SetTitle"/> to customize the display of the workspace title. /// </para> /// </remarks> public class WorkspaceView : DesktopObjectView, IWorkspaceView { private Crownwood.DotNetMagic.Controls.TabPage _tabPage; private DesktopWindowView _desktopView; private Control _control; /// <summary> /// Constructor. /// </summary> /// <param name="workspace"></param> /// <param name="desktopView"></param> protected internal WorkspaceView(Workspace workspace, DesktopWindowView desktopView) { IApplicationComponentView componentView = (IApplicationComponentView)ViewFactory.CreateAssociatedView(workspace.Component.GetType()); componentView.SetComponent((IApplicationComponent)workspace.Component); _tabPage = new Crownwood.DotNetMagic.Controls.TabPage(); _tabPage.Control = _control = componentView.GuiElement as Control; _tabPage.Tag = this; _desktopView = desktopView; } /// <summary> /// Gets the tab page that hosts this workspace view. /// </summary> protected internal Crownwood.DotNetMagic.Controls.TabPage TabPage { get { return _tabPage; } } #region DesktopObjectView overrides /// <summary> /// Sets the title of the workspace. /// </summary> /// <param name="title"></param> public override void SetTitle(string title) { _tabPage.Title = title; _tabPage.ToolTip = title; } /// <summary> /// Opens the workspace, adding the tab to the tab group. /// </summary> public override void Open() { _desktopView.AddWorkspaceView(this); } /// <summary> /// Activates the workspace, making the tab the selected tab. /// </summary> public override void Activate() { _tabPage.Selected = true; } /// <summary> /// Not implemented. /// </summary> public override void Show() { } /// <summary> /// Not implemented. /// </summary> public override void Hide() { } /// <summary> /// Disposes of this object. /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing) { if (_tabPage != null) { // Remove the tab _desktopView.RemoveWorkspaceView(this); _control.Dispose(); _control = null; _tabPage.Dispose(); _tabPage = null; } } base.Dispose(disposing); } #endregion } }
35.864865
146
0.5974
[ "Apache-2.0" ]
econmed/ImageServer20
Desktop/View/WinForms/WorkspaceView.cs
5,310
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager { /// <summary> /// Extension class for resource manager. /// </summary> internal static class ResourceManagerExtensions { /// <summary> /// Gets the correlation id from x-ms-correlation-id. /// </summary> public static string GetCorrelationId(this Response response) { string correlationId = null; response.Headers.TryGetValue("x-ms-correlation-request-id", out correlationId); return correlationId; } internal static ResourceIdentifier GetSubscriptionResourceIdentifier(this ResourceIdentifier id) { if (id.ResourceType == Subscription.ResourceType) return id; ResourceIdentifier parent = id.Parent; while (parent != null && parent.ResourceType != Subscription.ResourceType) { parent = parent.Parent; } return parent?.ResourceType == Subscription.ResourceType ? parent : null; } } }
31.076923
104
0.624587
[ "MIT" ]
nitsi/azure-sdk-for-net
sdk/resourcemanager/Azure.ResourceManager/src/ResourceManagerExtensions.cs
1,214
C#
using System; using System.Collections.Generic; using System.Linq; using UniRx; using System.Text; using System.Threading.Tasks; using GTA; using GTA.Math; using GTA.Native; namespace Inferno.InfernoScripts.Player { class PlayerGripVehicle : InfernoScript { private bool _isGriped = false; private Vehicle _vehicle; private Vector3 _ofsetPosition; protected override void Setup() { //0.3秒間押しっぱなしなら発動 OnThinnedTickAsObservable .Select(_ => !this.GetPlayerVehicle().IsSafeExist() && !_isGriped && this.IsGamePadPressed(GameKey.Reload) ).Buffer(3, 1) .Where(x => x.All(v => v)) .Subscribe(_ => GripAction()); OnThinnedTickAsObservable .Where(_ => _isGriped) .Subscribe(_ => { Grip(PlayerPed, _vehicle, _ofsetPosition); }); OnThinnedTickAsObservable .Where(_ => _isGriped && (!this.IsGamePadPressed(GameKey.Reload) || PlayerPed.IsDead)) .Subscribe(_ => GripRemove()); this.OnAbortAsync.Subscribe(_ => { SetPlayerProof(false); }); } /// <summary> /// 車両から手を離す /// </summary> private void GripRemove() { SetPlayerProof(false); _isGriped = false; Function.Call(Hash.DETACH_ENTITY, PlayerPed, false, false); PlayerPed.Task.ClearAllImmediately(); PlayerPed.SetToRagdoll(); } private void SetPlayerProof(bool hasCollisionProof) { PlayerPed.SetProofs( PlayerPed.IsBulletProof, PlayerPed.IsFireProof, PlayerPed.IsExplosionProof, hasCollisionProof, PlayerPed.IsMeleeProof, false, false, false); } /// <summary> /// 掴む車両の選別 /// </summary> private void GripAction() { var gripAvailableVeles = CachedVehicles .Where(x => x.IsSafeExist() && x.IsInRangeOf(PlayerPed.Position, 10.0f)) .OrderBy(x => x.Position.DistanceTo(PlayerPed.Position)) .FirstOrDefault(); if (gripAvailableVeles == null || !gripAvailableVeles.IsTouching(PlayerPed)) return; _isGriped = true; var playerRHandCoords = PlayerPed.GetBoneCoord(Bone.SKEL_R_Hand); var offsetPosition = Function.Call<Vector3>(Hash.GET_OFFSET_FROM_ENTITY_GIVEN_WORLD_COORDS, gripAvailableVeles, playerRHandCoords.X, playerRHandCoords.Y, playerRHandCoords.Z); Grip(PlayerPed, gripAvailableVeles, offsetPosition); } /// <summary> /// 車両を掴む処理 /// </summary> /// <param name="player"></param> /// <param name="vehicle"></param> /// <param name="ofsetPosition"></param> private void Grip(Ped player, Vehicle vehicle, Vector3 ofsetPosition) { player.SetToRagdoll(0, 1); SetPlayerProof(true); _vehicle = vehicle; _ofsetPosition = ofsetPosition; var forceToBreak = 99999.0f; var rotation = new Vector3(0.0f, 0.0f, 0.0f); var isCollision = true; Function.Call(Hash.ATTACH_ENTITY_TO_ENTITY_PHYSICALLY, player, vehicle, player.GetBoneIndex(Bone.SKEL_R_Hand), vehicle.GetBoneIndex("SKEL_ROOT"), ofsetPosition.X, ofsetPosition.Y, ofsetPosition.Z, 0.0f, 0.0f, 0.0f, rotation.X, rotation.Y, rotation.Z, forceToBreak, false, //? false, //? isCollision, false, //? 2); //? } } }
32.676923
104
0.500706
[ "MIT" ]
Hackbesh/GTAV_InfernoScripts
Inferno/InfernoScripts/Player/PlayerGripVehicle.cs
4,318
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; internal partial class Interop { internal partial class BCrypt { internal enum NTSTATUS : uint { STATUS_SUCCESS = 0x0, STATUS_NOT_FOUND = 0xc0000225, STATUS_INVALID_PARAMETER = 0xc000000d, STATUS_NO_MEMORY = 0xc0000017, } } }
26.45
71
0.655955
[ "MIT" ]
Acidburn0zzz/corefx
src/Common/src/Interop/Windows/BCrypt/Interop.NTSTATUS.cs
529
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NUnit.Framework; namespace ProteinReader_UnitTests { internal static class FileRefs { public const string SHARE_PATH = @"\\proto-2\unitTest_Files\Protein_File_Reader\"; public static FileInfo GetTestFile(string relativeFilePath) { var dataFile = new FileInfo(relativeFilePath); if (dataFile.Exists) { #if DEBUG Console.WriteLine("Found file " + dataFile.FullName); Console.WriteLine(); #endif return dataFile; } #if DEBUG Console.WriteLine("Could not find " + relativeFilePath); Console.WriteLine("Checking alternative locations"); #endif var relativePathsToCheck = new List<string> { dataFile.Name }; if (!Path.IsPathRooted(relativeFilePath) && (relativeFilePath.Contains(Path.DirectorySeparatorChar) || relativeFilePath.Contains(Path.AltDirectorySeparatorChar))) { relativePathsToCheck.Add(relativeFilePath); } if (dataFile.Directory != null) { var parentToCheck = dataFile.Directory.Parent; while (parentToCheck != null) { foreach (var relativePath in relativePathsToCheck) { var alternateFile = new FileInfo(Path.Combine(parentToCheck.FullName, relativePath)); if (alternateFile.Exists) { #if DEBUG Console.WriteLine("... found at " + alternateFile.FullName); Console.WriteLine(); #endif return alternateFile; } } parentToCheck = parentToCheck.Parent; } } foreach (var relativePath in relativePathsToCheck) { var serverPathFile = new FileInfo(Path.Combine(SHARE_PATH, relativePath)); if (serverPathFile.Exists) { #if DEBUG Console.WriteLine("... found at " + serverPathFile); Console.WriteLine(); #endif return serverPathFile; } } var currentDirectory = new DirectoryInfo("."); Assert.Fail("Could not find " + relativeFilePath + "; current working directory: " + currentDirectory.FullName); return null; } } }
32.975904
135
0.515528
[ "Apache-2.0" ]
PNNL-Comp-Mass-Spec/Protein-File-Reader
UnitTests/FileRefs.cs
2,739
C#
using System; namespace AV.Middle.Common.Model { public class DataModel { private string message; public string Message { get { return message; } set { message = value; } } private DateTime receivedTime; public DateTime ReceivedTime { get { return receivedTime; } set { receivedTime = value; } } } }
14.521739
32
0.667665
[ "MIT" ]
iAvinashVarma/RunnerCore
Middle/Common/AV.Middle.Common.Model/DataModel.cs
334
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using IdentityServer4.Stores; using Iris.IdentityServer4.MongoDB.Stores; using Iris.IdentityServer4.MongoDB.Services; using System; using Iris.IdentityServer4.MongoDB.Options; using Iris.IdentityServer4.MongoDB.Contexts; namespace Iris.IdentityServer4.MongoDB { public static class IdentityServerMongoDbBuilderExtensions { public static IIdentityServerBuilder AddMongoDbStores( this IIdentityServerBuilder builder, Action<MongoDbStoreOptions> storeActionOptions) { builder.Services.Configure<MongoDbStoreOptions>(storeActionOptions); builder.Services.TryAddSingleton<MongoDbConfigurationContext>(); builder.Services.TryAddSingleton<MongoDbPersistedGrantContext>(); // Add configuration stores builder.AddClientStore<MongoDbClientStore>() .AddCorsPolicyService<MongoDbCorsPolicyService>() .AddResourceStore<MongoDbResourceStore>() .AddInMemoryCaching() .AddClientStoreCache<MongoDbClientStore>() .AddCorsPolicyCache<MongoDbCorsPolicyService>() .AddResourceStoreCache<MongoDbResourceStore>(); // Add operational stores builder.Services.AddTransient<IPersistedGrantStore, MongoDbPersistedGrantStore>(); builder.Services.AddTransient<IDeviceFlowStore, MongoDbDeviceFlowStore>(); builder.Services.AddSingleton<TokenCleanupService>(); builder.Services.AddHostedService<TokenCleanupWorker>(); return builder; } } }
41
94
0.714691
[ "Apache-2.0" ]
stewartm83/Iris.IdentityServer4.MongoDB
src/Iris.IdentityServer4.MongoDB/IdentityServerMongoDbBuilderExtensions.cs
1,765
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("TabelaFipe.BLL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TabelaFipe.BLL")] [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("8b68aaee-d171-4e78-867c-ba8328437825")] // 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.864865
84
0.744468
[ "MIT" ]
leonardoacoelho/TabelaFipe
TabelaFipe/TabelaFipe.BLL/Properties/AssemblyInfo.cs
1,404
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the alexaforbusiness-2017-11-09.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.AlexaForBusiness.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AlexaForBusiness.Model.Internal.MarshallTransformations { /// <summary> /// Ssml Marshaller /// </summary> public class SsmlMarshaller : IRequestMarshaller<Ssml, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(Ssml requestObject, JsonMarshallerContext context) { if(requestObject.IsSetLocale()) { context.Writer.WritePropertyName("Locale"); context.Writer.Write(requestObject.Locale); } if(requestObject.IsSetValue()) { context.Writer.WritePropertyName("Value"); context.Writer.Write(requestObject.Value); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static SsmlMarshaller Instance = new SsmlMarshaller(); } }
33.014706
115
0.642316
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/AlexaForBusiness/Generated/Model/Internal/MarshallTransformations/SsmlMarshaller.cs
2,245
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NewGUID { class Program { static void Main(string[] args) { string g = Guid.NewGuid().ToString(); Console.WriteLine("==============================================================================="); Console.WriteLine("GUID: "); Console.WriteLine("==============================================================================="); Console.WriteLine(""); Console.WriteLine(g); Console.WriteLine(""); Console.WriteLine("Press Any Key To Continue"); Console.ReadKey(); } } }
25.44
104
0.511006
[ "MIT" ]
jamiefutch/NewGUID
Program.cs
638
C#
using System; using System.Collections.Generic; namespace Models.DB { public partial class EreservationInfo { public EreservationInfo() { EformationTt = new HashSet<EformationTt>(); } public long EreservationInfoId { get; set; } public long Booking { get; set; } public virtual Tbooking BookingNavigation { get; set; } public virtual ICollection<EformationTt> EformationTt { get; set; } } }
23.75
75
0.635789
[ "Apache-2.0" ]
LightosLimited/RailML
v2.4/Models/DB/EreservationInfo.cs
477
C#
using System; using System.Collections.Generic; using System.Text; using static System.String; public class Robot { private static readonly HashSet<string> Registry = new HashSet<string>(); private static readonly Random Generator = new Random(); private string _name = Empty; public string Name { get { if (this._name.Length != 0) { return this._name; } Name = generateId(); // we need to make sure that the name is unique using the registry while (Registry.Contains(this._name)) { Name = generateId(); } Registry.Add(this._name); return this._name; } private set => this._name = value; } public void Reset() { Registry.Remove(Name); Name = Empty; } private string generateId() { const int offset = 26; // 1st uppercase letter char c1 = (char)Robot.Generator.Next('A', 'A' + offset); // 2nd uppercase letter char c2 = (char)Robot.Generator.Next('A', 'A' + offset); // 3 random digits int digits3 = Robot.Generator.Next(100, 999); var id = new StringBuilder(); return id.Append(c1).Append(c2).Append(digits3).ToString(); } }
25.490566
78
0.549223
[ "MIT" ]
stanciua/exercism
csharp/robot-name/RobotName.cs
1,351
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference.Tests { using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using Xunit; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.DocAsCode.DataContracts.ManagedReference; using static Microsoft.DocAsCode.Metadata.ManagedReference.RoslynIntermediateMetadataExtractor; [Trait("Owner", "vwxyzh")] [Trait("Language", "CSharp")] [Trait("EntityType", "Model")] [Collection("docfx STA")] public class GenerateMetadataFromCSUnitTest { private static readonly MSBuildWorkspace Workspace = MSBuildWorkspace.Create(); [Fact] [Trait("Related", "Attribute")] public void TestGenerateMetadataAsyncWithFuncVoidReturn() { string code = @" using System; namespace Test1 { /// <summary> /// This is a test /// </summary> /// <seealso cref=""Func1(int)""/> [Serializable] public class Class1 { /// <summary> /// This is a function /// </summary> /// <param name=""i"">This is a param as <see cref=""int""/></param> /// <seealso cref=""int""/> public void Func1(int i) { return; } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); var @class = output.Items[0].Items[0]; Assert.NotNull(@class); Assert.Equal("Class1", @class.DisplayNames.First().Value); Assert.Equal("Class1", @class.DisplayNamesWithType.First().Value); Assert.Equal("Test1.Class1", @class.DisplayQualifiedNames.First().Value); Assert.Equal(@" This is a test ".Replace("\r\n", "\n"), @class.Summary); Assert.Equal("Test1.Class1.Func1(System.Int32)", @class.SeeAlsos[0].LinkId); Assert.Equal(@"[Serializable] public class Class1", @class.Syntax.Content[SyntaxLanguage.CSharp]); var function = output.Items[0].Items[0].Items[0]; Assert.NotNull(function); Assert.Equal("Func1(Int32)", function.DisplayNames.First().Value); Assert.Equal("Class1.Func1(Int32)", function.DisplayNamesWithType.First().Value); Assert.Equal("Test1.Class1.Func1(System.Int32)", function.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.Class1.Func1(System.Int32)", function.Name); Assert.Equal(@" This is a function ".Replace("\r\n", "\n"), function.Summary); Assert.Equal("System.Int32", function.SeeAlsos[0].LinkId); Assert.Equal("This is a param as <xref href=\"System.Int32\" data-throw-if-not-resolved=\"false\"></xref>", function.Syntax.Parameters[0].Description); Assert.Single(output.Items); var parameter = function.Syntax.Parameters[0]; Assert.Equal("i", parameter.Name); Assert.Equal("System.Int32", parameter.Type); var returnValue = function.Syntax.Return; Assert.Null(returnValue); } [Fact] public void TestGenerateMetadataAsyncWithNamespace() { string code = @" namespace Test1.Test2 { /// <seealso cref=""Class1""/> public class Class1 { } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); Assert.Equal("Test1.Test2", ns.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Test2", ns.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Test2", ns.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Empty(ns.Modifiers); } [Trait("Related", "Generic")] [Trait("Related", "Reference")] [Trait("Related", "TripleSlashComments")] [Fact] public void TestGenerateMetadataWithGenericClass() { string code = @" using System.Collections.Generic namespace Test1 { /// <summary> /// class1 <see cref=""Dictionary{TKey,TValue}""/> /// </summary> /// <typeparam name=""T"">The type</typeparam> public sealed class Class1<T> where T : struct, IEnumerable<T> { public TResult? Func1<TResult>(T? x, IEnumerable<T> y) where TResult : struct { return null; } public IEnumerable<T> Items { get; set; } public event EventHandler Event1; public static bool operator ==(Class1<T> x, Class1<T> y) { return false; } public IEnumerable<T> Items2 { get; private set; } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); MetadataItem output_preserveRaw = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code), null, options: new ExtractMetadataOptions { PreserveRawInlineComments = true }); Assert.Single(output.Items); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Class1<T>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Class1<T>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Class1<T>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Class1`1", type.Name); Assert.Equal(@"public sealed class Class1<T> where T : struct, IEnumerable<T>", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.NotNull(type.Syntax.TypeParameters); Assert.Single(type.Syntax.TypeParameters); Assert.Equal("T", type.Syntax.TypeParameters[0].Name); Assert.Null(type.Syntax.TypeParameters[0].Type); Assert.Equal("The type", type.Syntax.TypeParameters[0].Description); Assert.Equal(new[] { "public", "sealed", "class" }, type.Modifiers[SyntaxLanguage.CSharp]); } { var function = output.Items[0].Items[0].Items[0]; Assert.NotNull(function); Assert.Equal("Func1<TResult>(Nullable<T>, IEnumerable<T>)", function.DisplayNames.First().Value); Assert.Equal("Class1<T>.Func1<TResult>(Nullable<T>, IEnumerable<T>)", function.DisplayNamesWithType.First().Value); Assert.Equal("Test1.Class1<T>.Func1<TResult>(System.Nullable<T>, System.Collections.Generic.IEnumerable<T>)", function.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.Class1`1.Func1``1(System.Nullable{`0},System.Collections.Generic.IEnumerable{`0})", function.Name); var parameterX = function.Syntax.Parameters[0]; Assert.Equal("x", parameterX.Name); Assert.Equal("System.Nullable{{T}}", parameterX.Type); var parameterY = function.Syntax.Parameters[1]; Assert.Equal("y", parameterY.Name); Assert.Equal("System.Collections.Generic.IEnumerable{{T}}", parameterY.Type); var returnValue = function.Syntax.Return; Assert.NotNull(returnValue); Assert.NotNull(returnValue.Type); Assert.Equal("System.Nullable{{TResult}}", returnValue.Type); Assert.Equal("public TResult? Func1<TResult>(T? x, IEnumerable<T> y)\r\n where TResult : struct", function.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, function.Modifiers[SyntaxLanguage.CSharp]); } { var proptery = output.Items[0].Items[0].Items[1]; Assert.NotNull(proptery); Assert.Equal("Items", proptery.DisplayNames.First().Value); Assert.Equal("Class1<T>.Items", proptery.DisplayNamesWithType.First().Value); Assert.Equal("Test1.Class1<T>.Items", proptery.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.Class1`1.Items", proptery.Name); Assert.Empty(proptery.Syntax.Parameters); var returnValue = proptery.Syntax.Return; Assert.NotNull(returnValue.Type); Assert.Equal("System.Collections.Generic.IEnumerable{{T}}", returnValue.Type); Assert.Equal(@"public IEnumerable<T> Items { get; set; }", proptery.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "get", "set" }, proptery.Modifiers[SyntaxLanguage.CSharp]); } { var event1 = output.Items[0].Items[0].Items[2]; Assert.NotNull(event1); Assert.Equal("Event1", event1.DisplayNames.First().Value); Assert.Equal("Class1<T>.Event1", event1.DisplayNamesWithType.First().Value); Assert.Equal("Test1.Class1<T>.Event1", event1.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.Class1`1.Event1", event1.Name); Assert.Null(event1.Syntax.Parameters); Assert.Equal("EventHandler", event1.Syntax.Return.Type); Assert.Equal("public event EventHandler Event1", event1.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, event1.Modifiers[SyntaxLanguage.CSharp]); } { var operator1 = output.Items[0].Items[0].Items[3]; Assert.NotNull(operator1); Assert.Equal("Equality(Class1<T>, Class1<T>)", operator1.DisplayNames.First().Value); Assert.Equal("Class1<T>.Equality(Class1<T>, Class1<T>)", operator1.DisplayNamesWithType.First().Value); Assert.Equal("Test1.Class1<T>.Equality(Test1.Class1<T>, Test1.Class1<T>)", operator1.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.Class1`1.op_Equality(Test1.Class1{`0},Test1.Class1{`0})", operator1.Name); Assert.NotNull(operator1.Syntax.Parameters); var parameterX = operator1.Syntax.Parameters[0]; Assert.Equal("x", parameterX.Name); Assert.Equal("Test1.Class1`1", parameterX.Type); var parameterY = operator1.Syntax.Parameters[1]; Assert.Equal("y", parameterY.Name); Assert.Equal("Test1.Class1`1", parameterY.Type); Assert.NotNull(operator1.Syntax.Return); Assert.Equal("System.Boolean", operator1.Syntax.Return.Type); Assert.Equal("public static bool operator ==(Class1<T> x, Class1<T> y)", operator1.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, operator1.Modifiers[SyntaxLanguage.CSharp]); } { var proptery = output.Items[0].Items[0].Items[4]; Assert.NotNull(proptery); Assert.Equal("Items2", proptery.DisplayNames.First().Value); Assert.Equal("Class1<T>.Items2", proptery.DisplayNamesWithType.First().Value); Assert.Equal("Test1.Class1<T>.Items2", proptery.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.Class1`1.Items2", proptery.Name); Assert.Empty(proptery.Syntax.Parameters); var returnValue = proptery.Syntax.Return; Assert.NotNull(returnValue.Type); Assert.Equal("System.Collections.Generic.IEnumerable{{T}}", returnValue.Type); Assert.Equal(@"public IEnumerable<T> Items2 { get; }", proptery.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "get" }, proptery.Modifiers[SyntaxLanguage.CSharp]); } // check references { Assert.NotNull(output.References); Assert.True(output.References.Count > 0); Assert.True(output.References.ContainsKey("Test1.Class1`1")); var refenence = output.References["Test1.Class1`1"]; Assert.True(refenence.IsDefinition); Assert.Equal("Test1", refenence.Parent); Assert.True(output.References.ContainsKey("Test1")); refenence = output.References["Test1"]; Assert.True(refenence.IsDefinition); Assert.Null(refenence.Parent); Assert.True(output.References.ContainsKey("System.Collections.Generic.Dictionary`2")); Assert.NotNull(output.References["System.Collections.Generic.Dictionary`2"]); Assert.True(output.Items[0].Items[0].References.ContainsKey("System.Collections.Generic.Dictionary`2")); Assert.Null(output.Items[0].Items[0].References["System.Collections.Generic.Dictionary`2"]); } } [Fact] public void TestGenerateMetadataWithInterface() { string code = @" namespace Test1 { public interface IFoo { string Bar(int x); int Count { get; } event EventHandler FooBar; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("Bar(Int32)", method.DisplayNames.First().Value); Assert.Equal("IFoo.Bar(Int32)", method.DisplayNamesWithType.First().Value); Assert.Equal("Test1.IFoo.Bar(System.Int32)", method.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.IFoo.Bar(System.Int32)", method.Name); var parameter = method.Syntax.Parameters[0]; Assert.Equal("x", parameter.Name); Assert.Equal("System.Int32", parameter.Type); var returnValue = method.Syntax.Return; Assert.NotNull(returnValue); Assert.NotNull(returnValue.Type); Assert.Equal("System.String", returnValue.Type); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.CSharp]); } { var property = output.Items[0].Items[0].Items[1]; Assert.NotNull(property); Assert.Equal("Count", property.DisplayNames.First().Value); Assert.Equal("IFoo.Count", property.DisplayNamesWithType.First().Value); Assert.Equal("Test1.IFoo.Count", property.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.IFoo.Count", property.Name); Assert.Empty(property.Syntax.Parameters); var returnValue = property.Syntax.Return; Assert.NotNull(returnValue); Assert.NotNull(returnValue.Type); Assert.Equal("System.Int32", returnValue.Type); Assert.Equal(new[] { "get" }, property.Modifiers[SyntaxLanguage.CSharp]); } { var @event = output.Items[0].Items[0].Items[2]; Assert.NotNull(@event); Assert.Equal("FooBar", @event.DisplayNames.First().Value); Assert.Equal("IFoo.FooBar", @event.DisplayNamesWithType.First().Value); Assert.Equal("Test1.IFoo.FooBar", @event.DisplayQualifiedNames.First().Value); Assert.Equal("Test1.IFoo.FooBar", @event.Name); Assert.Equal("event EventHandler FooBar", @event.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Null(@event.Syntax.Parameters); Assert.Equal("EventHandler", @event.Syntax.Return.Type); Assert.Equal(new string[0], @event.Modifiers[SyntaxLanguage.CSharp]); } } [Fact] public void TestGenerateMetadataWithInterfaceAndInherits() { string code = @" namespace Test1 { public interface IFoo { } public interface IBar : IFoo { } public interface IFooBar : IBar { } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ifoo = output.Items[0].Items[0]; Assert.NotNull(ifoo); Assert.Equal("IFoo", ifoo.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFoo", ifoo.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo", ifoo.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("public interface IFoo", ifoo.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "interface" }, ifoo.Modifiers[SyntaxLanguage.CSharp]); var ibar = output.Items[0].Items[1]; Assert.NotNull(ibar); Assert.Equal("IBar", ibar.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IBar", ibar.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IBar", ibar.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("public interface IBar : IFoo", ibar.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "interface" }, ibar.Modifiers[SyntaxLanguage.CSharp]); var ifoobar = output.Items[0].Items[2]; Assert.NotNull(ifoobar); Assert.Equal("IFooBar", ifoobar.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar", ifoobar.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar", ifoobar.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("public interface IFooBar : IBar, IFoo", ifoobar.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "interface" }, ifoobar.Modifiers[SyntaxLanguage.CSharp]); } [Trait("Related", "Generic")] [Trait("Related", "Inheritance")] [Trait("Related", "Reference")] [Fact] public void TestGenerateMetadataWithClassAndInherits() { string code = @" namespace Test1 { public class Foo<T> : IFoo { } public class Bar<T> : Foo<T[]>, IBar { } public class FooBar : Bar<string>, IFooBar { } public interface IFoo { } public interface IBar { } public interface IFooBar : IFoo, IBar { } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var foo = output.Items[0].Items[0]; Assert.NotNull(foo); Assert.Equal("Foo<T>", foo.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>", foo.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>", foo.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("public class Foo<T> : IFoo", foo.Syntax.Content[SyntaxLanguage.CSharp]); Assert.NotNull(foo.Implements); Assert.Single(foo.Implements); Assert.Equal(new[] { "Test1.IFoo" }, foo.Implements); Assert.Equal(new[] { "public", "class" }, foo.Modifiers[SyntaxLanguage.CSharp]); var bar = output.Items[0].Items[1]; Assert.NotNull(bar); Assert.Equal("Bar<T>", bar.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar<T>", bar.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar<T>", bar.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("public class Bar<T> : Foo<T[]>, IFoo, IBar", bar.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "System.Object", "Test1.Foo{{T}[]}" }, bar.Inheritance); Assert.Equal(new[] { "Test1.IFoo", "Test1.IBar" }, bar.Implements); Assert.Equal(new[] { "public", "class" }, bar.Modifiers[SyntaxLanguage.CSharp]); var foobar = output.Items[0].Items[2]; Assert.NotNull(foobar); Assert.Equal("FooBar", foobar.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("FooBar", foobar.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.FooBar", foobar.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("public class FooBar : Bar<string>, IFooBar, IFoo, IBar", foobar.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "System.Object", "Test1.Foo{System.String[]}", "Test1.Bar{System.String}" }, foobar.Inheritance); Assert.Equal(new[] { "Test1.IFoo", "Test1.IBar", "Test1.IFooBar" }.OrderBy(s => s), foobar.Implements.OrderBy(s => s)); Assert.Equal(new[] { "public", "class" }, foobar.Modifiers[SyntaxLanguage.CSharp]); Assert.NotNull(output.References); Assert.Equal(19, output.References.Count); { var item = output.References["System.Object"]; Assert.Equal("System", item.Parent); Assert.NotNull(item); Assert.Single(item.Parts[SyntaxLanguage.CSharp]); Assert.Equal("System.Object", item.Parts[SyntaxLanguage.CSharp][0].Name); Assert.Equal("Object", item.Parts[SyntaxLanguage.CSharp][0].DisplayName); Assert.Equal("Object", item.Parts[SyntaxLanguage.CSharp][0].DisplayNamesWithType); Assert.Equal("System.Object", item.Parts[SyntaxLanguage.CSharp][0].DisplayQualifiedNames); } { var item = output.References["Test1.Bar{System.String}"]; Assert.NotNull(item); Assert.Equal("Test1.Bar`1", item.Definition); Assert.Equal("Test1", item.Parent); Assert.Equal(4, item.Parts[SyntaxLanguage.CSharp].Count); Assert.Equal("Test1.Bar`1", item.Parts[SyntaxLanguage.CSharp][0].Name); Assert.Equal("Bar", item.Parts[SyntaxLanguage.CSharp][0].DisplayName); Assert.Equal("Bar", item.Parts[SyntaxLanguage.CSharp][0].DisplayNamesWithType); Assert.Equal("Test1.Bar", item.Parts[SyntaxLanguage.CSharp][0].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][1].Name); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayName); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayNamesWithType); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayQualifiedNames); Assert.Equal("System.String", item.Parts[SyntaxLanguage.CSharp][2].Name); Assert.Equal("String", item.Parts[SyntaxLanguage.CSharp][2].DisplayNamesWithType); Assert.Equal("String", item.Parts[SyntaxLanguage.CSharp][2].DisplayName); Assert.Equal("System.String", item.Parts[SyntaxLanguage.CSharp][2].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][3].Name); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][3].DisplayName); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][3].DisplayNamesWithType); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][3].DisplayQualifiedNames); } { var item = output.References["Test1.Foo{{T}[]}"]; Assert.NotNull(item); Assert.Equal("Test1.Foo`1", item.Definition); Assert.Equal("Test1", item.Parent); Assert.Equal(5, item.Parts[SyntaxLanguage.CSharp].Count); Assert.Equal("Test1.Foo`1", item.Parts[SyntaxLanguage.CSharp][0].Name); Assert.Equal("Foo", item.Parts[SyntaxLanguage.CSharp][0].DisplayName); Assert.Equal("Foo", item.Parts[SyntaxLanguage.CSharp][0].DisplayNamesWithType); Assert.Equal("Test1.Foo", item.Parts[SyntaxLanguage.CSharp][0].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][1].Name); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayName); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayNamesWithType); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][2].Name); Assert.Equal("T", item.Parts[SyntaxLanguage.CSharp][2].DisplayName); Assert.Equal("T", item.Parts[SyntaxLanguage.CSharp][2].DisplayNamesWithType); Assert.Equal("T", item.Parts[SyntaxLanguage.CSharp][2].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][3].Name); Assert.Equal("[]", item.Parts[SyntaxLanguage.CSharp][3].DisplayName); Assert.Equal("[]", item.Parts[SyntaxLanguage.CSharp][3].DisplayNamesWithType); Assert.Equal("[]", item.Parts[SyntaxLanguage.CSharp][3].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][4].Name); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][4].DisplayName); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][4].DisplayNamesWithType); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][4].DisplayQualifiedNames); } { var item = output.References["Test1.Foo{System.String[]}"]; Assert.NotNull(item); Assert.Equal("Test1.Foo`1", item.Definition); Assert.Equal("Test1", item.Parent); Assert.Equal(5, item.Parts[SyntaxLanguage.CSharp].Count); Assert.Equal("Test1.Foo`1", item.Parts[SyntaxLanguage.CSharp][0].Name); Assert.Equal("Foo", item.Parts[SyntaxLanguage.CSharp][0].DisplayNamesWithType); Assert.Equal("Foo", item.Parts[SyntaxLanguage.CSharp][0].DisplayName); Assert.Equal("Test1.Foo", item.Parts[SyntaxLanguage.CSharp][0].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][1].Name); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayName); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayNamesWithType); Assert.Equal("<", item.Parts[SyntaxLanguage.CSharp][1].DisplayQualifiedNames); Assert.Equal("System.String", item.Parts[SyntaxLanguage.CSharp][2].Name); Assert.Equal("String", item.Parts[SyntaxLanguage.CSharp][2].DisplayName); Assert.Equal("String", item.Parts[SyntaxLanguage.CSharp][2].DisplayNamesWithType); Assert.Equal("System.String", item.Parts[SyntaxLanguage.CSharp][2].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][3].Name); Assert.Equal("[]", item.Parts[SyntaxLanguage.CSharp][3].DisplayName); Assert.Equal("[]", item.Parts[SyntaxLanguage.CSharp][3].DisplayNamesWithType); Assert.Equal("[]", item.Parts[SyntaxLanguage.CSharp][3].DisplayQualifiedNames); Assert.Null(item.Parts[SyntaxLanguage.CSharp][4].Name); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][4].DisplayName); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][4].DisplayNamesWithType); Assert.Equal(">", item.Parts[SyntaxLanguage.CSharp][4].DisplayQualifiedNames); } } [Fact] public void TestGenerateMetadataWithEnum() { string code = @" namespace Test1 { public enum ABC{A,B,C} public enum YN : byte {Y=1, N=0} public enum XYZ:int{X,Y,Z} } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("ABC", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("ABC", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.ABC", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.ABC", type.Name); Assert.Equal("public enum ABC", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "enum" }, type.Modifiers[SyntaxLanguage.CSharp]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("YN", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("YN", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.YN", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.YN", type.Name); Assert.Equal("public enum YN : byte", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "enum" }, type.Modifiers[SyntaxLanguage.CSharp]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("XYZ", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("XYZ", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.XYZ", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.XYZ", type.Name); Assert.Equal("public enum XYZ", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "enum" }, type.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Inheritance")] [Fact] public void TestGenerateMetadataWithStruct() { string code = @" using System.Collections using System.Collections.Generic namespace Test1 { public struct Foo{} public struct Bar<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() => null; IEnumerator IEnumerable.GetEnumerator() => null; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo", type.Name); Assert.Equal("public struct Foo", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Null(type.Implements); Assert.Equal(new[] { "public", "struct" }, type.Modifiers[SyntaxLanguage.CSharp]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("Bar<T>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar<T>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar<T>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar`1", type.Name); Assert.Equal("public struct Bar<T> : IEnumerable<T>, IEnumerable", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "System.Collections.Generic.IEnumerable{{T}}", "System.Collections.IEnumerable" }, type.Implements); Assert.Equal(new[] { "public", "struct" }, type.Modifiers[SyntaxLanguage.CSharp]); } // inheritance of Foo { var inheritedMembers = output.Items[0].Items[0].InheritedMembers; Assert.NotNull(inheritedMembers); Assert.Equal( new string[] { "System.ValueType.ToString", "System.ValueType.Equals(System.Object)", "System.ValueType.GetHashCode", "System.Object.Equals(System.Object,System.Object)", "System.Object.ReferenceEquals(System.Object,System.Object)", "System.Object.GetType", }.OrderBy(s => s), inheritedMembers.OrderBy(s => s)); } } [Trait("Related", "Generic")] [Fact] public void TestGenerateMetadataWithDelegate() { string code = @" using System.Collections.Generic namespace Test1 { public delegate void Foo(); public delegate T Bar<T>(IEnumerable<T> x = null) where T : class; public delegate void FooBar(ref int x, out string y, params byte[] z); } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo", type.Name); Assert.Equal("public delegate void Foo();", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Null(type.Syntax.Parameters); Assert.Null(type.Syntax.Return); Assert.Equal(new[] { "public", "delegate" }, type.Modifiers[SyntaxLanguage.CSharp]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("Bar<T>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar<T>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar<T>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar`1", type.Name); Assert.Equal("public delegate T Bar<T>(IEnumerable<T> x = null)\r\n where T : class;", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "delegate" }, type.Modifiers[SyntaxLanguage.CSharp]); Assert.NotNull(type.Syntax.Parameters); Assert.Single(type.Syntax.Parameters); Assert.Equal("x", type.Syntax.Parameters[0].Name); Assert.Equal("System.Collections.Generic.IEnumerable{{T}}", type.Syntax.Parameters[0].Type); Assert.NotNull(type.Syntax.Return); Assert.Equal("{T}", type.Syntax.Return.Type); Assert.Equal(new[] { "public", "delegate" }, type.Modifiers[SyntaxLanguage.CSharp]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("FooBar", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("FooBar", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.FooBar", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.FooBar", type.Name); Assert.Equal(@"public delegate void FooBar(ref int x, out string y, params byte[] z);", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.NotNull(type.Syntax.Parameters); Assert.Equal(3, type.Syntax.Parameters.Count); Assert.Equal("x", type.Syntax.Parameters[0].Name); Assert.Equal("System.Int32", type.Syntax.Parameters[0].Type); Assert.Equal("y", type.Syntax.Parameters[1].Name); Assert.Equal("System.String", type.Syntax.Parameters[1].Type); Assert.Equal("z", type.Syntax.Parameters[2].Name); Assert.Equal("System.Byte[]", type.Syntax.Parameters[2].Type); Assert.Null(type.Syntax.Return); Assert.Equal(new[] { "public", "delegate" }, type.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Generic")] [Fact] public void TestGenerateMetadataWithMethod() { string code = @" using System.Threading.Tasks namespace Test1 { public abstract class Foo<T> { public abstract void M1(); protected virtual Foo<T> M2<TArg>(TArg arg) where TArg : Foo<T> => this; public static TResult M3<TResult>(string x) where TResult : class => null; public void M4(int x){} } public class Bar : Foo<string>, IFooBar { public override void M1(){} protected override sealed Foo<T> M2<TArg>(TArg arg) where TArg : Foo<string> => this; public int M5<TArg>(TArg arg) where TArg : struct, new() => 2; } public interface IFooBar { void M1(); Foo<T> M2<TArg>(TArg arg) where TArg : Foo<string>; int M5<TArg>(TArg arg) where TArg : struct, new(); } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); // Foo<T> { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("M1()", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.M1()", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.M1()", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.M1", method.Name); Assert.Equal("public abstract void M1()", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "abstract" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[1]; Assert.NotNull(method); Assert.Equal("M2<TArg>(TArg)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.M2<TArg>(TArg)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.M2<TArg>(TArg)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.M2``1(``0)", method.Name); Assert.Equal("protected virtual Foo<T> M2<TArg>(TArg arg)\r\n where TArg : Foo<T>", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "virtual" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[2]; Assert.NotNull(method); Assert.Equal("M3<TResult>(String)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.M3<TResult>(String)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.M3<TResult>(System.String)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.M3``1(System.String)", method.Name); Assert.Equal("public static TResult M3<TResult>(string x)\r\n where TResult : class", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[3]; Assert.NotNull(method); Assert.Equal("M4(Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.M4(Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.M4(System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.M4(System.Int32)", method.Name); Assert.Equal("public void M4(int x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, method.Modifiers[SyntaxLanguage.CSharp]); } // Bar { var method = output.Items[0].Items[1].Items[0]; Assert.NotNull(method); Assert.Equal("M1()", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.M1()", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.M1()", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.M1", method.Name); Assert.Equal("public override void M1()", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{System.String}.M1", method.Overridden); Assert.Equal(new[] { "public", "override" }, method.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M1", method.Implements[0]); } { var method = output.Items[0].Items[1].Items[1]; Assert.NotNull(method); Assert.Equal("M2<TArg>(TArg)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.M2<TArg>(TArg)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.M2<TArg>(TArg)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.M2``1(``0)", method.Name); Assert.Equal("protected override sealed Foo<T> M2<TArg>(TArg arg)\r\n where TArg : Foo<string>", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{System.String}.M2``1({TArg})", method.Overridden); } { var method = output.Items[0].Items[1].Items[2]; Assert.NotNull(method); Assert.Equal("M5<TArg>(TArg)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.M5<TArg>(TArg)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.M5<TArg>(TArg)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.M5``1(``0)", method.Name); Assert.Equal("public int M5<TArg>(TArg arg)\r\n where TArg : struct, new()", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, method.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M5``1({TArg})", method.Implements[0]); } // IFooBar { var method = output.Items[0].Items[2].Items[0]; Assert.NotNull(method); Assert.Equal("M1()", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.M1()", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M1()", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M1", method.Name); Assert.Equal("void M1()", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[2].Items[1]; Assert.NotNull(method); Assert.Equal("M2<TArg>(TArg)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.M2<TArg>(TArg)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M2<TArg>(TArg)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M2``1(``0)", method.Name); Assert.Equal("Foo<T> M2<TArg>(TArg arg)\r\n where TArg : Foo<string>", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[2].Items[2]; Assert.NotNull(method); Assert.Equal("M5<TArg>(TArg)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.M5<TArg>(TArg)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M5<TArg>(TArg)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.M5``1(``0)", method.Name); Assert.Equal("int M5<TArg>(TArg arg)\r\n where TArg : struct, new()", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Generic")] [Trait("Related", "EII")] [Fact] public void TestGenerateMetadataWithEii() { string code = @" using System.Collections.Generic namespace Test1 { public class Foo<T> : IFoo, IFoo<string>, IFoo<T> where T : class { object IFoo.Bar(ref int x) => null; string IFoo<string>.Bar<TArg>(TArg[] x) => ""; T IFoo<T>.Bar<TArg>(TArg[] x) => null; string IFoo<string>.P { get; set; } T IFoo<T>.P { get; set; } int IFoo<string>.this[string x] { get { return 1; } } int IFoo<T>.this[T x] { get { return 1; } } event EventHandler IFoo.E { add { } remove { } } public bool IFoo.Global { get; set; } } public interface IFoo { object Bar(ref int x); event EventHandler E; bool Global { get; set;} } public interface IFoo<out T> { T Bar<TArg>(TArg[] x) T P { get; set; } int this[T x] { get; } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo<T>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1", type.Name); Assert.Equal(@"public class Foo<T> : IFoo, IFoo<string>, IFoo<T> where T : class", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "class" }, type.Modifiers[SyntaxLanguage.CSharp]); Assert.Contains("Test1.IFoo", type.Implements); Assert.Contains("Test1.IFoo{System.String}", type.Implements); Assert.Contains("Test1.IFoo{{T}}", type.Implements); } { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.True(method.IsExplicitInterfaceImplementation); Assert.Equal("IFoo.Bar(ref Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo.Bar(ref Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo.Bar(ref System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo#Bar(System.Int32@)", method.Name); Assert.Equal(@"object IFoo.Bar(ref int x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo.Bar(System.Int32@)", method.Implements[0]); } { var method = output.Items[0].Items[0].Items[1]; Assert.NotNull(method); Assert.True(method.IsExplicitInterfaceImplementation); Assert.Equal("IFoo<String>.Bar<TArg>(TArg[])", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo<String>.Bar<TArg>(TArg[])", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo<System.String>.Bar<TArg>(TArg[])", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo{System#String}#Bar``1(``0[])", method.Name); Assert.Equal(@"string IFoo<string>.Bar<TArg>(TArg[] x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo{System.String}.Bar``1({TArg}[])", method.Implements[0]); } { var method = output.Items[0].Items[0].Items[2]; Assert.NotNull(method); Assert.True(method.IsExplicitInterfaceImplementation); Assert.Equal("IFoo<T>.Bar<TArg>(TArg[])", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo<T>.Bar<TArg>(TArg[])", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo<T>.Bar<TArg>(TArg[])", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo{T}#Bar``1(``0[])", method.Name); Assert.Equal(@"T IFoo<T>.Bar<TArg>(TArg[] x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo{{T}}.Bar``1({TArg}[])", method.Implements[0]); } { var p = output.Items[0].Items[0].Items[3]; Assert.NotNull(p); Assert.True(p.IsExplicitInterfaceImplementation); Assert.Equal("IFoo<String>.P", p.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo<String>.P", p.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo<System.String>.P", p.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo{System#String}#P", p.Name); Assert.Equal(@"string IFoo<string>.P { get; set; }", p.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get", "set" }, p.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo{System.String}.P", p.Implements[0]); } { var p = output.Items[0].Items[0].Items[4]; Assert.NotNull(p); Assert.True(p.IsExplicitInterfaceImplementation); Assert.Equal("IFoo<T>.P", p.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo<T>.P", p.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo<T>.P", p.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo{T}#P", p.Name); Assert.Equal(@"T IFoo<T>.P { get; set; }", p.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get", "set" }, p.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo{{T}}.P", p.Implements[0]); } { var p = output.Items[0].Items[0].Items[5]; Assert.NotNull(p); Assert.True(p.IsExplicitInterfaceImplementation); Assert.Equal("IFoo<String>.Item[String]", p.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo<String>.Item[String]", p.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo<System.String>.Item[System.String]", p.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo{System#String}#Item(System.String)", p.Name); Assert.Equal(@"int IFoo<string>.this[string x] { get; }", p.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get", }, p.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo{System.String}.Item(System.String)", p.Implements[0]); } { var p = output.Items[0].Items[0].Items[6]; Assert.NotNull(p); Assert.True(p.IsExplicitInterfaceImplementation); Assert.Equal("IFoo<T>.Item[T]", p.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo<T>.Item[T]", p.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo<T>.Item[T]", p.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo{T}#Item(`0)", p.Name); Assert.Equal(@"int IFoo<T>.this[T x] { get; }", p.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get", }, p.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo{{T}}.Item({T})", p.Implements[0]); } { var e = output.Items[0].Items[0].Items[7]; Assert.NotNull(e); Assert.True(e.IsExplicitInterfaceImplementation); Assert.Equal("IFoo.E", e.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.IFoo.E", e.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Test1.IFoo.E", e.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Test1#IFoo#E", e.Name); Assert.Equal(@"event EventHandler IFoo.E", e.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], e.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFoo.E", e.Implements[0]); } } [Trait("Related", "Generic")] [Trait("Related", "EII")] [Fact] public void TestGenerateMetadataWithEditorBrowsableNeverEii() { string code = @" namespace Test { using System.ComponentModel; public interface IInterface { [EditorBrowsable(EditorBrowsableState.Never)] bool Method(); [EditorBrowsable(EditorBrowsableState.Never)] bool Property { get; } [EditorBrowsable(EditorBrowsableState.Never)] event EventHandler Event; } public class Class : IInterface { bool IInterface.Method() { return false; } bool IInterface.Property { get { return false; } } event EventHandler IInterface.Event { add {} remove {} } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.Equal(2, ns.Items.Count); { var type = ns.Items[0]; Assert.NotNull(type); Assert.Equal("IInterface", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Test.IInterface", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test.IInterface", type.Name); Assert.Equal("public interface IInterface", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "interface" }, type.Modifiers[SyntaxLanguage.CSharp]); Assert.Null(type.Implements); // Verify member with EditorBrowsable.Never should be filtered out Assert.Empty(type.Items); } { var type = ns.Items[1]; Assert.NotNull(type); Assert.Equal("Class", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Test.Class", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test.Class", type.Name); Assert.Equal("public class Class : IInterface", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "class" }, type.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test.IInterface", type.Implements[0]); // Verify EII member with EditorBrowsable.Never should be filtered out Assert.Empty(type.Items); } } [Trait("Related", "Generic")] [Trait("Related", "Extension Method")] [Fact] public void TestGenerateMetadataWithExtensionMethod() { string code = @" namespace Test1 { public abstract class Foo<T> { } public class FooImple<T> : Foo<T[]> { public void M1<U>(T a, U b) { } } public class FooImple2<T> : Foo<dynamic> { } public class FooImple3<T> : Foo<Foo<T[]>> { } public class Doll { } public static class Extension { public static void Eat<Tool>(this FooImple<Tool> impl) { } public static void Play<Tool, Way>(this Foo<Tool> foo, Tool t, Way w) { } public static void Rain(this Doll d) { } public static void Rain(this Doll d, Doll another) { } } } "; var compilation = CreateCompilationFromCSharpCode(code); MetadataItem output = GenerateYamlMetadata(compilation, options: new ExtractMetadataOptions { RoslynExtensionMethods = GetAllExtensionMethodsFromCompilation(new[] { compilation }) }); Assert.Single(output.Items); // FooImple<T> { var method = output.Items[0].Items[1].Items[0]; Assert.NotNull(method); Assert.Equal("M1<U>(T, U)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("FooImple<T>.M1<U>(T, U)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.FooImple<T>.M1<U>(T, U)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.FooImple`1.M1``1(`0,``0)", method.Name); Assert.Equal("public void M1<U>(T a, U b)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, method.Modifiers[SyntaxLanguage.CSharp]); } var extensionMethods = output.Items[0].Items[1].ExtensionMethods; Assert.Equal(2, extensionMethods.Count); { Assert.Equal("Test1.FooImple`1.Test1.Extension.Eat``1", extensionMethods[0]); var reference = output.References[extensionMethods[0]]; Assert.False(reference.IsDefinition); Assert.Equal("Test1.Extension.Eat``1(Test1.FooImple{``0})", reference.Definition); Assert.Equal("Eat<T>()", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayName))); Assert.Equal("Extension.Eat<T>()", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayNamesWithType))); } { Assert.Equal("Test1.Foo{`0[]}.Test1.Extension.Play``2({T}[],{Way})", extensionMethods[1]); var reference = output.References[extensionMethods[1]]; Assert.False(reference.IsDefinition); Assert.Equal("Test1.Extension.Play``2(Test1.Foo{``0},``0,``1)", reference.Definition); Assert.Equal("Play<T[], Way>(T[], Way)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayName))); Assert.Equal("Extension.Play<T[], Way>(T[], Way)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayNamesWithType))); } // FooImple2<T> extensionMethods = output.Items[0].Items[2].ExtensionMethods; Assert.Single(extensionMethods); { Assert.Equal("Test1.Foo{System.Object}.Test1.Extension.Play``2(System.Object,{Way})", extensionMethods[0]); var reference = output.References[extensionMethods[0]]; Assert.False(reference.IsDefinition); Assert.Equal("Test1.Extension.Play``2(Test1.Foo{``0},``0,``1)", reference.Definition); Assert.Equal("Play<Object, Way>(Object, Way)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayName))); Assert.Equal("Extension.Play<Object, Way>(Object, Way)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayNamesWithType))); } // FooImple3<T> extensionMethods = output.Items[0].Items[3].ExtensionMethods; Assert.Single(extensionMethods); { Assert.Equal("Test1.Foo{Test1.Foo{`0[]}}.Test1.Extension.Play``2(Test1.Foo{{T}[]},{Way})", extensionMethods[0]); var reference = output.References[extensionMethods[0]]; Assert.False(reference.IsDefinition); Assert.Equal("Test1.Extension.Play``2(Test1.Foo{``0},``0,``1)", reference.Definition); Assert.Equal("Play<Foo<T[]>, Way>(Foo<T[]>, Way)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayName))); Assert.Equal("Extension.Play<Foo<T[]>, Way>(Foo<T[]>, Way)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayNamesWithType))); } // Doll extensionMethods = output.Items[0].Items[4].ExtensionMethods; Assert.Equal(2, extensionMethods.Count); { Assert.Equal("Test1.Doll.Test1.Extension.Rain", extensionMethods[0]); var reference = output.References[extensionMethods[0]]; Assert.False(reference.IsDefinition); Assert.Equal("Test1.Extension.Rain(Test1.Doll)", reference.Definition); Assert.Equal("Rain()", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayName))); Assert.Equal("Extension.Rain()", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayNamesWithType))); } { Assert.Equal("Test1.Doll.Test1.Extension.Rain(Test1.Doll)", extensionMethods[1]); var reference = output.References[extensionMethods[1]]; Assert.False(reference.IsDefinition); Assert.Equal("Test1.Extension.Rain(Test1.Doll,Test1.Doll)", reference.Definition); Assert.Equal("Rain(Doll)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayName))); Assert.Equal("Extension.Rain(Doll)", string.Concat(reference.Parts[SyntaxLanguage.CSharp].Select(n => n.DisplayNamesWithType))); } } [Fact] public void TestGenerateMetadataWithOperator() { string code = @" using System.Collections.Generic namespace Test1 { public class Foo { // unary public static Foo operator +(Foo x) => x; public static Foo operator -(Foo x) => x; public static Foo operator !(Foo x) => x; public static Foo operator ~(Foo x) => x; public static Foo operator ++(Foo x) => x; public static Foo operator --(Foo x) => x; public static Foo operator true(Foo x) => x; public static Foo operator false(Foo x) => x; // binary public static Foo operator +(Foo x, int y) => x; public static Foo operator -(Foo x, int y) => x; public static Foo operator *(Foo x, int y) => x; public static Foo operator /(Foo x, int y) => x; public static Foo operator %(Foo x, int y) => x; public static Foo operator &(Foo x, int y) => x; public static Foo operator |(Foo x, int y) => x; public static Foo operator ^(Foo x, int y) => x; public static Foo operator >>(Foo x, int y) => x; public static Foo operator <<(Foo x, int y) => x; // comparison public static bool operator ==(Foo x, int y) => false; public static bool operator !=(Foo x, int y) => false; public static bool operator >(Foo x, int y) => false; public static bool operator <(Foo x, int y) => false; public static bool operator >=(Foo x, int y) => false; public static bool operator <=(Foo x, int y) => false; // convertion public static implicit operator Foo (int x) => null; public static explicit operator int (Foo x) => 0; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); // unary { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("UnaryPlus(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.UnaryPlus(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.UnaryPlus(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_UnaryPlus(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator +(Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[1]; Assert.NotNull(method); Assert.Equal("UnaryNegation(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.UnaryNegation(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.UnaryNegation(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_UnaryNegation(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator -(Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[2]; Assert.NotNull(method); Assert.Equal("LogicalNot(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.LogicalNot(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.LogicalNot(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_LogicalNot(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator !(Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[3]; Assert.NotNull(method); Assert.Equal("OnesComplement(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.OnesComplement(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.OnesComplement(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_OnesComplement(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator ~(Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[4]; Assert.NotNull(method); Assert.Equal("Increment(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Increment(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Increment(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Increment(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator ++(Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[5]; Assert.NotNull(method); Assert.Equal("Decrement(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Decrement(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Decrement(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Decrement(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator --(Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[6]; Assert.NotNull(method); Assert.Equal("True(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.True(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.True(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_True(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator true (Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[7]; Assert.NotNull(method); Assert.Equal("False(Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.False(Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.False(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_False(Test1.Foo)", method.Name); Assert.Equal(@"public static Foo operator false (Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } // binary { var method = output.Items[0].Items[0].Items[8]; Assert.NotNull(method); Assert.Equal("Addition(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Addition(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Addition(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Addition(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator +(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[9]; Assert.NotNull(method); Assert.Equal("Subtraction(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Subtraction(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Subtraction(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Subtraction(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator -(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[10]; Assert.NotNull(method); Assert.Equal("Multiply(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Multiply(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Multiply(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Multiply(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator *(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[11]; Assert.NotNull(method); Assert.Equal("Division(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Division(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Division(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Division(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator /(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[12]; Assert.NotNull(method); Assert.Equal("Modulus(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Modulus(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Modulus(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Modulus(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator %(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[13]; Assert.NotNull(method); Assert.Equal("BitwiseAnd(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.BitwiseAnd(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.BitwiseAnd(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_BitwiseAnd(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator &(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[14]; Assert.NotNull(method); Assert.Equal("BitwiseOr(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.BitwiseOr(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.BitwiseOr(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_BitwiseOr(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator |(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[15]; Assert.NotNull(method); Assert.Equal("ExclusiveOr(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.ExclusiveOr(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.ExclusiveOr(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_ExclusiveOr(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator ^(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[16]; Assert.NotNull(method); Assert.Equal("RightShift(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.RightShift(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.RightShift(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_RightShift(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator >>(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[17]; Assert.NotNull(method); Assert.Equal("LeftShift(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.LeftShift(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.LeftShift(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_LeftShift(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static Foo operator <<(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } // comparison { var method = output.Items[0].Items[0].Items[18]; Assert.NotNull(method); Assert.Equal("Equality(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Equality(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Equality(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Equality(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static bool operator ==(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[19]; Assert.NotNull(method); Assert.Equal("Inequality(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Inequality(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Inequality(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Inequality(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static bool operator !=(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[20]; Assert.NotNull(method); Assert.Equal("GreaterThan(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.GreaterThan(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.GreaterThan(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_GreaterThan(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static bool operator>(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[21]; Assert.NotNull(method); Assert.Equal("LessThan(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.LessThan(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.LessThan(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_LessThan(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static bool operator <(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[22]; Assert.NotNull(method); Assert.Equal("GreaterThanOrEqual(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.GreaterThanOrEqual(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.GreaterThanOrEqual(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_GreaterThanOrEqual(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static bool operator >=(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[23]; Assert.NotNull(method); Assert.Equal("LessThanOrEqual(Foo, Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.LessThanOrEqual(Foo, Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.LessThanOrEqual(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_LessThanOrEqual(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"public static bool operator <=(Foo x, int y)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } // conversion { var method = output.Items[0].Items[0].Items[24]; Assert.NotNull(method); Assert.Equal("Implicit(Int32 to Foo)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Implicit(Int32 to Foo)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Implicit(System.Int32 to Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Implicit(System.Int32)~Test1.Foo", method.Name); Assert.Equal(@"public static implicit operator Foo(int x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } { var method = output.Items[0].Items[0].Items[25]; Assert.NotNull(method); Assert.Equal("Explicit(Foo to Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Explicit(Foo to Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Explicit(Test1.Foo to System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.op_Explicit(Test1.Foo)~System.Int32", method.Name); Assert.Equal(@"public static explicit operator int (Foo x)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "static" }, method.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Generic")] [Fact] public void TestGenerateMetadataWithConstructor() { string code = @" namespace Test1 { public class Foo<T> { static Foo(){} public Foo(){} public Foo(int x) : base(x){} protected internal Foo(string x) : base(0){} } public class Bar { public Bar(){} protected Bar(int x){} } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var constructor = output.Items[0].Items[0].Items[0]; Assert.NotNull(constructor); Assert.Equal("Foo()", constructor.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Foo()", constructor.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Foo()", constructor.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.#ctor", constructor.Name); Assert.Equal("public Foo()", constructor.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, constructor.Modifiers[SyntaxLanguage.CSharp]); } { var constructor = output.Items[0].Items[0].Items[1]; Assert.NotNull(constructor); Assert.Equal("Foo(Int32)", constructor.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Foo(Int32)", constructor.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Foo(System.Int32)", constructor.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.#ctor(System.Int32)", constructor.Name); Assert.Equal("public Foo(int x)", constructor.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, constructor.Modifiers[SyntaxLanguage.CSharp]); } { var constructor = output.Items[0].Items[0].Items[2]; Assert.NotNull(constructor); Assert.Equal("Foo(String)", constructor.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Foo(String)", constructor.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Foo(System.String)", constructor.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.#ctor(System.String)", constructor.Name); Assert.Equal("protected Foo(string x)", constructor.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected" }, constructor.Modifiers[SyntaxLanguage.CSharp]); } { var constructor = output.Items[0].Items[1].Items[0]; Assert.NotNull(constructor); Assert.Equal("Bar()", constructor.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Bar()", constructor.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Bar()", constructor.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.#ctor", constructor.Name); Assert.Equal("public Bar()", constructor.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, constructor.Modifiers[SyntaxLanguage.CSharp]); } { var constructor = output.Items[0].Items[1].Items[1]; Assert.NotNull(constructor); Assert.Equal("Bar(Int32)", constructor.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Bar(Int32)", constructor.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Bar(System.Int32)", constructor.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.#ctor(System.Int32)", constructor.Name); Assert.Equal("protected Bar(int x)", constructor.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected" }, constructor.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Generic")] [Fact] public void TestGenerateMetadataWithField() { string code = @" namespace Test1 { public class Foo<T> { public volatile int X; protected static readonly Foo<T> Y = null; protected internal const string Z = """"; } public enum Bar { Black, Red, Blue = 2, Green = 4, White = Red | Blue | Green, } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var field = output.Items[0].Items[0].Items[0]; Assert.NotNull(field); Assert.Equal("X", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.X", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.X", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.X", field.Name); Assert.Equal("public volatile int X", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "volatile" }, field.Modifiers[SyntaxLanguage.CSharp]); } { var field = output.Items[0].Items[0].Items[1]; Assert.NotNull(field); Assert.Equal("Y", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Y", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Y", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Y", field.Name); Assert.Equal("protected static readonly Foo<T> Y", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "static", "readonly" }, field.Modifiers[SyntaxLanguage.CSharp]); } { var field = output.Items[0].Items[0].Items[2]; Assert.NotNull(field); Assert.Equal("Z", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Z", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Z", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Z", field.Name); Assert.Equal("protected const string Z = \"\"", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "const" }, field.Modifiers[SyntaxLanguage.CSharp]); } { var field = output.Items[0].Items[1].Items[0]; Assert.NotNull(field); Assert.Equal("Black", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Black", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Black", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Black", field.Name); Assert.Equal("Black = 0", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "const" }, field.Modifiers[SyntaxLanguage.CSharp]); } { var field = output.Items[0].Items[1].Items[1]; Assert.NotNull(field); Assert.Equal("Red", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Red", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Red", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Red", field.Name); Assert.Equal("Red = 1", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "const" }, field.Modifiers[SyntaxLanguage.CSharp]); } { var field = output.Items[0].Items[1].Items[2]; Assert.NotNull(field); Assert.Equal("Blue", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Blue", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Blue", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Blue", field.Name); Assert.Equal(@"Blue = 2", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "const" }, field.Modifiers[SyntaxLanguage.CSharp]); } { var field = output.Items[0].Items[1].Items[3]; Assert.NotNull(field); Assert.Equal("Green", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Green", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Green", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Green", field.Name); Assert.Equal("Green = 4", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "const" }, field.Modifiers[SyntaxLanguage.CSharp]); } { var field = output.Items[0].Items[1].Items[4]; Assert.NotNull(field); Assert.Equal("White", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.White", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.White", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.White", field.Name); Assert.Equal(@"White = 7", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "const" }, field.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Generic")] [Fact] public void TestGenerateMetadataWithCSharpCodeAndEvent() { string code = @" using System; namespace Test1 { public abstract class Foo<T> where T : EventArgs { public event EventHandler A; protected static event EventHandler B { add {} remove {}} protected internal abstract event EventHandler<T> C; public virtual event EventHandler<T> D { add {} remove {}} } public class Bar<T> : Foo<T> where T : EventArgs { public new event EventHandler A; protected internal override sealed event EventHandler<T> C; public override event EventHandler<T> D; } public interface IFooBar<T> where T : EventArgs { event EventHandler A; event EventHandler<T> D; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var a = output.Items[0].Items[0].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.A", a.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.A", a.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.A", a.Name); Assert.Equal("public event EventHandler A", a.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, a.Modifiers[SyntaxLanguage.CSharp]); } { var b = output.Items[0].Items[0].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.B", b.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.B", b.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.B", b.Name); Assert.Equal("protected static event EventHandler B", b.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "static" }, b.Modifiers[SyntaxLanguage.CSharp]); } { var c = output.Items[0].Items[0].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.C", c.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.C", c.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.C", c.Name); Assert.Equal("protected abstract event EventHandler<T> C", c.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "abstract" }, c.Modifiers[SyntaxLanguage.CSharp]); } { var d = output.Items[0].Items[0].Items[3]; Assert.NotNull(d); Assert.Equal("D", d.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.D", d.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.D", d.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.D", d.Name); Assert.Equal("public virtual event EventHandler<T> D", d.Syntax.Content[SyntaxLanguage.CSharp]); } { var a = output.Items[0].Items[1].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar<T>.A", a.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar<T>.A", a.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar`1.A", a.Name); Assert.Equal("public event EventHandler A", a.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public" }, a.Modifiers[SyntaxLanguage.CSharp]); } { var c = output.Items[0].Items[1].Items[1]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar<T>.C", c.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar<T>.C", c.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar`1.C", c.Name); Assert.Equal("protected override sealed event EventHandler<T> C", c.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{{T}}.C", c.Overridden); Assert.Equal(new[] { "protected", "override", "sealed" }, c.Modifiers[SyntaxLanguage.CSharp]); } { var d = output.Items[0].Items[1].Items[2]; Assert.NotNull(d); Assert.Equal("D", d.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar<T>.D", d.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar<T>.D", d.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar`1.D", d.Name); Assert.Equal("public override event EventHandler<T> D", d.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{{T}}.D", d.Overridden); Assert.Equal(new[] { "public", "override" }, d.Modifiers[SyntaxLanguage.CSharp]); } { var a = output.Items[0].Items[2].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar<T>.A", a.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar<T>.A", a.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar`1.A", a.Name); Assert.Equal("event EventHandler A", a.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], a.Modifiers[SyntaxLanguage.CSharp]); } { var d = output.Items[0].Items[2].Items[1]; Assert.NotNull(d); Assert.Equal("D", d.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar<T>.D", d.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar<T>.D", d.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar`1.D", d.Name); Assert.Equal("event EventHandler<T> D", d.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new string[0], d.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Generic")] [Fact] public void TestGenerateMetadataWithProperty() { string code = @" namespace Test1 { public abstract class Foo<T> where T : class { public int A { get; set; } public virtual int B { get { return 1; } } public abstract int C { set; } protected int D { get; private set; } public T E { get; protected set; } protected internal static int F { get; protected set; } } public class Bar : Foo<string>, IFooBar { public new virtual int A { get; set; } public override int B { get { return 2; } } public override sealed int C { set; } } public interface IFooBar { int A { get; set; } int B { get; } int C { set; } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var a = output.Items[0].Items[0].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.A", a.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.A", a.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.A", a.Name); Assert.Equal(@"public int A { get; set; }", a.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "get", "set" }, a.Modifiers[SyntaxLanguage.CSharp]); } { var b = output.Items[0].Items[0].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.B", b.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.B", b.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.B", b.Name); Assert.Equal(@"public virtual int B { get; }", b.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "virtual", "get" }, b.Modifiers[SyntaxLanguage.CSharp]); } { var c = output.Items[0].Items[0].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.C", c.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.C", c.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.C", c.Name); Assert.Equal(@"public abstract int C { set; }", c.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "abstract", "set" }, c.Modifiers[SyntaxLanguage.CSharp]); } { var d = output.Items[0].Items[0].Items[3]; Assert.NotNull(d); Assert.Equal("D", d.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.D", d.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.D", d.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.D", d.Name); Assert.Equal(@"protected int D { get; }", d.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "get" }, d.Modifiers[SyntaxLanguage.CSharp]); } { var e = output.Items[0].Items[0].Items[4]; Assert.NotNull(e); Assert.Equal("E", e.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.E", e.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.E", e.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.E", e.Name); Assert.Equal(@"public T E { get; protected set; }", e.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "get", "protected set" }, e.Modifiers[SyntaxLanguage.CSharp]); } { var f = output.Items[0].Items[0].Items[5]; Assert.NotNull(f); Assert.Equal("F", f.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.F", f.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.F", f.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.F", f.Name); Assert.Equal(@"protected static int F { get; set; }", f.Syntax.Content[SyntaxLanguage.CSharp]); } { var a = output.Items[0].Items[1].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.A", a.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.A", a.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.A", a.Name); Assert.Equal(@"public virtual int A { get; set; }", a.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "virtual", "get", "set" }, a.Modifiers[SyntaxLanguage.CSharp]); } { var b = output.Items[0].Items[1].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.B", b.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.B", b.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.B", b.Name); Assert.Equal(@"public override int B { get; }", b.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{System.String}.B", b.Overridden); Assert.Equal(new[] { "public", "override", "get" }, b.Modifiers[SyntaxLanguage.CSharp]); } { var c = output.Items[0].Items[1].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.C", c.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.C", c.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.C", c.Name); Assert.Equal(@"public override sealed int C { set; }", c.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{System.String}.C", c.Overridden); Assert.Equal(new[] { "public", "override", "sealed", "set" }, c.Modifiers[SyntaxLanguage.CSharp]); } { var a = output.Items[0].Items[2].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.A", a.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.A", a.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.A", a.Name); Assert.Equal(@"int A { get; set; }", a.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get", "set" }, a.Modifiers[SyntaxLanguage.CSharp]); } { var b = output.Items[0].Items[2].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.B", b.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.B", b.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.B", b.Name); Assert.Equal(@"int B { get; }", b.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get" }, b.Modifiers[SyntaxLanguage.CSharp]); } { var c = output.Items[0].Items[2].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.C", c.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.C", c.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.C", c.Name); Assert.Equal(@"int C { set; }", c.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "set" }, c.Modifiers[SyntaxLanguage.CSharp]); } } [Trait("Related", "Generic")] [Fact] public void TestGenerateMetadataWithIndexer() { string code = @" using System; namespace Test1 { public abstract class Foo<T> where T : class { public int this[int x] { get { return 0; } set { } } public virtual int this[string x] { get { return 1; } } public abstract int this[object x] { set; } protected int this[DateTime x] { get { return 0; } private set { } } public int this[T t] { get { return 0; } protected set { } } protected internal int this[int x, T t] { get; protected set; } } public class Bar : Foo<string>, IFooBar { public new virtual int this[int x] { get { return 0; } set { } } public override int this[string x] { get { return 2; } } public override sealed int this[object x] { set; } } public interface IFooBar { int this[int x] { get; set; } int this[string x] { get; } int this[object x] { set; } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); // Foo<T> { var indexer = output.Items[0].Items[0].Items[0]; Assert.NotNull(indexer); Assert.Equal("Item[Int32]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Item[Int32]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Item[System.Int32]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Item(System.Int32)", indexer.Name); Assert.Equal(@"public int this[int x] { get; set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "get", "set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } { var indexer = output.Items[0].Items[0].Items[1]; Assert.NotNull(indexer); Assert.Equal("Item[String]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Item[String]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Item[System.String]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Item(System.String)", indexer.Name); Assert.Equal(@"public virtual int this[string x] { get; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "virtual", "get" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } { var indexer = output.Items[0].Items[0].Items[2]; Assert.NotNull(indexer); Assert.Equal("Item[Object]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Item[Object]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Item[System.Object]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Item(System.Object)", indexer.Name); Assert.Equal(@"public abstract int this[object x] { set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "abstract", "set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } { var indexer = output.Items[0].Items[0].Items[3]; Assert.NotNull(indexer); Assert.Equal("Item[DateTime]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Item[DateTime]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Item[System.DateTime]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Item(System.DateTime)", indexer.Name); Assert.Equal(@"protected int this[DateTime x] { get; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "get" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } { var indexer = output.Items[0].Items[0].Items[4]; Assert.NotNull(indexer); Assert.Equal("Item[T]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Item[T]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Item[T]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Item(`0)", indexer.Name); Assert.Equal(@"public int this[T t] { get; protected set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "get", "protected set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } { var indexer = output.Items[0].Items[0].Items[5]; Assert.NotNull(indexer); Assert.Equal("Item[Int32, T]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo<T>.Item[Int32, T]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo<T>.Item[System.Int32, T]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo`1.Item(System.Int32,`0)", indexer.Name); Assert.Equal(@"protected int this[int x, T t] { get; set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "protected", "get", "set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } // Bar { var indexer = output.Items[0].Items[1].Items[0]; Assert.NotNull(indexer); Assert.Equal("Item[Int32]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Item[Int32]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Item[System.Int32]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Item(System.Int32)", indexer.Name); Assert.Equal(@"public virtual int this[int x] { get; set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "public", "virtual", "get", "set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item(System.Int32)", indexer.Implements[0]); } { var indexer = output.Items[0].Items[1].Items[1]; Assert.NotNull(indexer); Assert.Equal("Item[String]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Item[String]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Item[System.String]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Item(System.String)", indexer.Name); Assert.Equal(@"public override int this[string x] { get; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{System.String}.Item(System.String)", indexer.Overridden); Assert.Equal(new[] { "public", "override", "get" }, indexer.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item(System.String)", indexer.Implements[0]); } { var indexer = output.Items[0].Items[1].Items[2]; Assert.NotNull(indexer); Assert.Equal("Item[Object]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar.Item[Object]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Item[System.Object]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Bar.Item(System.Object)", indexer.Name); Assert.Equal(@"public override sealed int this[object x] { set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo{System.String}.Item(System.Object)", indexer.Overridden); Assert.Equal(new[] { "public", "override", "sealed", "set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item(System.Object)", indexer.Implements[0]); } // IFooBar { var indexer = output.Items[0].Items[2].Items[0]; Assert.NotNull(indexer); Assert.Equal("Item[Int32]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.Item[Int32]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item[System.Int32]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item(System.Int32)", indexer.Name); Assert.Equal(@"int this[int x] { get; set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get", "set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } { var indexer = output.Items[0].Items[2].Items[1]; Assert.NotNull(indexer); Assert.Equal("Item[String]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.Item[String]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item[System.String]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item(System.String)", indexer.Name); Assert.Equal(@"int this[string x] { get; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "get" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } { var indexer = output.Items[0].Items[2].Items[2]; Assert.NotNull(indexer); Assert.Equal("Item[Object]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("IFooBar.Item[Object]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item[System.Object]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.IFooBar.Item(System.Object)", indexer.Name); Assert.Equal(@"int this[object x] { set; }", indexer.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "set" }, indexer.Modifiers[SyntaxLanguage.CSharp]); } } [Fact] public void TestGenerateMetadataWithMethodUsingDefaultValue() { string code = @" namespace Test1 { public class Foo { public void Test( int a = 1, uint b = 1, short c = 1, ushort d = 1, long e = 1, ulong f= 1, byte g = 1, sbyte h = 1, char i = '1', string j = ""1"", bool k = true, object l = null) { } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal(@"public void Test(int a = 1, uint b = 1U, short c = 1, ushort d = 1, long e = 1L, ulong f = 1UL, byte g = 1, sbyte h = 1, char i = '1', string j = ""1"", bool k = true, object l = null)", method.Syntax.Content[SyntaxLanguage.CSharp]); } } [Fact] public void TestGenerateMetadataAsyncWithAssemblyInfoAndCrossReference() { string referenceCode = @" namespace Test1 { public class Class1 { public void Func1(int i) { return; } } } "; string code = @" namespace Test2 { public class Class2 : Test1.Class1 { public void Func1(Test1.Class1 i) { return; } } } namespace Test1 { public class Class2 : Test1.Class1 { public void Func1(Test1.Class1 i) { return; } } } "; var referencedAssembly = CreateAssemblyFromCSharpCode(referenceCode, "reference"); var compilation = CreateCompilationFromCSharpCode(code, MetadataReference.CreateFromFile(referencedAssembly.Location)); Assert.Equal("test.dll", compilation.AssemblyName); MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Null(output.AssemblyNameList); Assert.Null(output.NamespaceName); Assert.Equal("test.dll", output.Items[0].AssemblyNameList.First()); Assert.Null(output.Items[0].NamespaceName); Assert.Equal("test.dll", output.Items[0].Items[0].AssemblyNameList.First()); Assert.Equal("Test2", output.Items[0].Items[0].NamespaceName); } [Fact] [Trait("Related", "Multilanguage")] [Trait("Related", "Generic")] public void TestGenerateMetadataAsyncWithMultilanguage() { string code = @" namespace Test1 { public class Foo<T> { public void Bar<K>(int i) { } public int this[int index] { get { return index; } } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo<T>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T)", type.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1", type.Name); { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("Bar<K>(Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar(Of K)(Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T>.Bar<K>(Int32)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T).Bar(Of K)(Int32)", method.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T>.Bar<K>(System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T).Bar(Of K)(System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.Bar``1(System.Int32)", method.Name); Assert.Single(method.Syntax.Parameters); var parameter = method.Syntax.Parameters[0]; Assert.Equal("i", parameter.Name); Assert.Equal("System.Int32", parameter.Type); var returnValue = method.Syntax.Return; Assert.Null(returnValue); } { var indexer = output.Items[0].Items[0].Items[1]; Assert.NotNull(indexer); Assert.Equal("Item[Int32]", indexer.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Item(Int32)", indexer.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T>.Item[Int32]", indexer.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T).Item(Int32)", indexer.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T>.Item[System.Int32]", indexer.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T).Item(System.Int32)", indexer.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.Item(System.Int32)", indexer.Name); Assert.Single(indexer.Syntax.Parameters); var parameter = indexer.Syntax.Parameters[0]; Assert.Equal("index", parameter.Name); Assert.Equal("System.Int32", parameter.Type); var returnValue = indexer.Syntax.Return; Assert.NotNull(returnValue); Assert.Equal("System.Int32", returnValue.Type); } } [Fact] [Trait("Related", "Generic")] [Trait("Related", "Inheritance")] public void TestGenerateMetadataAsyncWithGenericInheritance() { string code = @" using System.Collections.Generic; namespace Test1 { public class Foo<T> : Dictionary<string, T> { } public class Foo<T1, T2, T3> : List<T3> { } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo<T>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T)", type.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1", type.Name); Assert.Equal(2, type.Inheritance.Count); Assert.Equal("System.Collections.Generic.Dictionary{System.String,{T}}", type.Inheritance[1]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("Foo<T1, T2, T3>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2, T3)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T1, T2, T3>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2, T3)", type.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T1, T2, T3>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T1, T2, T3)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`3", type.Name); Assert.Equal(2, type.Inheritance.Count); Assert.Equal("System.Collections.Generic.List{{T3}}", type.Inheritance[1]); } } [Trait("Related", "Dynamic")] [Trait("Related", "Multilanguage")] [Fact] public void TestGenerateMetadataWithDynamic() { string code = @" namespace Test1 { public abstract class Foo { public dynamic F = 1; public dynamic M(dynamic arg) => null; public dynamic P { get; protected set; } = ""; public dynamic this[dynamic index] { get; } => 1; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var field = output.Items[0].Items[0].Items[0]; Assert.NotNull(field); Assert.Equal("F", field.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("F", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo.F", field.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo.F", field.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.F", field.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.F", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.F", field.Name); Assert.Equal("public dynamic F", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Public F As Object", field.Syntax.Content[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[1]; Assert.NotNull(method); Assert.Equal("M(Object)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("M(Object)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo.M(Object)", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo.M(Object)", method.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.M(System.Object)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.M(System.Object)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.M(System.Object)", method.Name); Assert.Equal("public dynamic M(dynamic arg)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal("Public Function M(arg As Object) As Object", method.Syntax.Content[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[2]; Assert.NotNull(method); Assert.Equal("P", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("P", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo.P", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo.P", method.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.P", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.P", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.P", method.Name); Assert.Equal(@"public dynamic P { get; protected set; }", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(@"Public Property P As Object", method.Syntax.Content[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[3]; Assert.NotNull(method); Assert.Equal("Item[Object]", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Item(Object)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo.Item[Object]", method.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo.Item(Object)", method.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Item[System.Object]", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo.Item(System.Object)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Item(System.Object)", method.Name); Assert.Equal(@"public dynamic this[dynamic index] { get; }", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(@"Public ReadOnly Property Item(index As Object) As Object", method.Syntax.Content[SyntaxLanguage.VB]); } } [Fact] [Trait("Related", "Multilanguage")] public void TestGenerateMetadataWithStaticClass() { string code = @" using System.Collections.Generic; namespace Test1 { public static class Foo { } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo", type.Name); Assert.Single(type.Inheritance); Assert.Equal("System.Object", type.Inheritance[0]); Assert.Equal(@"public static class Foo", type.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(@"Public Module Foo", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "public", "static", "class" }, type.Modifiers[SyntaxLanguage.CSharp]); Assert.Equal(new[] { "Public", "Module" }, type.Modifiers[SyntaxLanguage.VB]); } } [Fact] [Trait("Related", "Generic")] public void TestGenerateMetadataAsyncWithNestedGeneric() { string code = @" using System.Collections.Generic; namespace Test1 { public class Foo<T1, T2> { public class Bar<T3> { } public class FooBar { } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo<T1, T2>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T1, T2>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2)", type.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T1, T2>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T1, T2)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`2", type.Name); Assert.Single(type.Inheritance); Assert.Equal("System.Object", type.Inheritance[0]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("Foo<T1, T2>.Bar<T3>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2).Bar(Of T3)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T1, T2>.Bar<T3>", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2).Bar(Of T3)", type.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T1, T2>.Bar<T3>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T1, T2).Bar(Of T3)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`2.Bar`1", type.Name); Assert.Single(type.Inheritance); Assert.Equal("System.Object", type.Inheritance[0]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("Foo<T1, T2>.FooBar", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2).FooBar", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Foo<T1, T2>.FooBar", type.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T1, T2).FooBar", type.DisplayNamesWithType[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T1, T2>.FooBar", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T1, T2).FooBar", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`2.FooBar", type.Name); Assert.Single(type.Inheritance); Assert.Equal("System.Object", type.Inheritance[0]); } } [Fact] [Trait("Related", "Attribute")] public void TestGenerateMetadataAsyncWithAttributes() { string code = @" using System; using System.ComponentModel; namespace Test1 { [Serializable] [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)] [TypeConverter(typeof(TestAttribute))] [TypeConverter(typeof(TestAttribute[]))] [Test(""test"")] [Test(new int[]{1,2,3})] [Test(new object[]{null, ""abc"", 'd', 1.1f, 1.2, (sbyte)2, (byte)3, (short)4, (ushort)5, 6, 7u, 8l, 9ul, new int[]{ 10, 11, 12 }})] [Test(new Type[]{ typeof(Func<>), typeof(Func<,>), typeof(Func<string, string>) })] public class TestAttribute : Attribute { [Test(1)] [Test(2)] public TestAttribute([Test(3), Test(4)] object obj){} [Test(5)] public object Property { [Test(6)] get; [Test(7), Test(8)] set; } } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code, MetadataReference.CreateFromFile(typeof(System.ComponentModel.TypeConverterAttribute).Assembly.Location))); var @class = output.Items[0].Items[0]; Assert.NotNull(@class); Assert.Equal("TestAttribute", @class.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("TestAttribute", @class.DisplayNamesWithType[SyntaxLanguage.CSharp]); Assert.Equal("Test1.TestAttribute", @class.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal(@"[Serializable] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter | AttributeTargets.All, Inherited = true, AllowMultiple = true)] [TypeConverter(typeof(TestAttribute))] [TypeConverter(typeof(TestAttribute[]))] [Test(""test"")] [Test(new int[]{1, 2, 3})] [Test(new object[]{null, ""abc"", 'd', 1.1F, 1.2, (sbyte)2, (byte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, new int[]{10, 11, 12}})] [Test(new Type[]{typeof(Func<>), typeof(Func<, >), typeof(Func<string, string>)})] public class TestAttribute : Attribute, _Attribute", @class.Syntax.Content[SyntaxLanguage.CSharp]); Assert.NotNull(@class.Attributes); Assert.Equal(5, @class.Attributes.Count); Assert.Equal("System.SerializableAttribute", @class.Attributes[0].Type); Assert.Equal("System.SerializableAttribute.#ctor", @class.Attributes[0].Constructor); Assert.NotNull(@class.Attributes[0].Arguments); Assert.Empty(@class.Attributes[0].Arguments); Assert.Null(@class.Attributes[0].NamedArguments); Assert.Equal("System.AttributeUsageAttribute", @class.Attributes[1].Type); Assert.Equal("System.AttributeUsageAttribute.#ctor(System.AttributeTargets)", @class.Attributes[1].Constructor); Assert.NotNull(@class.Attributes[1].Arguments); Assert.Single(@class.Attributes[1].Arguments); Assert.Equal("System.AttributeTargets", @class.Attributes[1].Arguments[0].Type); Assert.Equal(32767, @class.Attributes[1].Arguments[0].Value); Assert.NotNull(@class.Attributes[1].NamedArguments); Assert.Equal(2, @class.Attributes[1].NamedArguments.Count); Assert.Equal("Inherited", @class.Attributes[1].NamedArguments[0].Name); Assert.Equal("System.Boolean", @class.Attributes[1].NamedArguments[0].Type); Assert.Equal(true, @class.Attributes[1].NamedArguments[0].Value); Assert.Equal("AllowMultiple", @class.Attributes[1].NamedArguments[1].Name); Assert.Equal("System.Boolean", @class.Attributes[1].NamedArguments[1].Type); Assert.Equal(true, @class.Attributes[1].NamedArguments[1].Value); Assert.Equal("System.ComponentModel.TypeConverterAttribute", @class.Attributes[2].Type); Assert.Equal("System.ComponentModel.TypeConverterAttribute.#ctor(System.Type)", @class.Attributes[2].Constructor); Assert.NotNull(@class.Attributes[2].Arguments); Assert.Single(@class.Attributes[2].Arguments); Assert.Equal("System.Type", @class.Attributes[2].Arguments[0].Type); Assert.Equal("Test1.TestAttribute", @class.Attributes[2].Arguments[0].Value); Assert.Null(@class.Attributes[2].NamedArguments); Assert.Equal("System.ComponentModel.TypeConverterAttribute", @class.Attributes[3].Type); Assert.Equal("System.ComponentModel.TypeConverterAttribute.#ctor(System.Type)", @class.Attributes[3].Constructor); Assert.NotNull(@class.Attributes[3].Arguments); Assert.Single(@class.Attributes[3].Arguments); Assert.Equal("System.Type", @class.Attributes[3].Arguments[0].Type); Assert.Equal("Test1.TestAttribute[]", @class.Attributes[3].Arguments[0].Value); Assert.Null(@class.Attributes[3].NamedArguments); Assert.Equal("Test1.TestAttribute", @class.Attributes[4].Type); Assert.Equal("Test1.TestAttribute.#ctor(System.Object)", @class.Attributes[4].Constructor); Assert.NotNull(@class.Attributes[4].Arguments); Assert.Single(@class.Attributes[4].Arguments); Assert.Equal("System.String", @class.Attributes[4].Arguments[0].Type); Assert.Equal("test", @class.Attributes[4].Arguments[0].Value); Assert.Null(@class.Attributes[4].NamedArguments); var ctor = @class.Items[0]; Assert.NotNull(ctor); Assert.Equal(@"[Test(1)] [Test(2)] public TestAttribute([Test(3), Test(4)] object obj)", ctor.Syntax.Content[SyntaxLanguage.CSharp]); var property = @class.Items[1]; Assert.NotNull(property); Assert.Equal(@"[Test(5)] public object Property { [Test(6)] get; [Test(7)] [Test(8)] set; }", property.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] public void TestGenerateMetadataWithFieldHasDefaultValue() { string code = @" namespace Test1 { public class Foo { public const ushort Test = 123; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var field = output.Items[0].Items[0].Items[0]; Assert.NotNull(field); Assert.Equal(@"public const ushort Test = 123", field.Syntax.Content[SyntaxLanguage.CSharp]); } } [Fact] [Trait("Related", "Multilanguage")] public void TestGenerateMetadataWithFieldHasDefaultValue_SpecialCharacter() { string code = @" namespace Test1 { public class Foo { public const char Test = '\uDBFF'; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); { var field = output.Items[0].Items[0].Items[0]; Assert.NotNull(field); Assert.Equal(@"public const char Test = '\uDBFF'", field.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(@"Public Const Test As Char = ""\uDBFF""c", field.Syntax.Content[SyntaxLanguage.VB]); } } [Fact] [Trait("Related", "ExtensionMethod")] [Trait("Related", "Multilanguage")] public void TestGenerateMetadataAsyncWithExtensionMethods() { string code = @" namespace Test1 { public static class Class1 { public static void Method1(this object obj) {} } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var method = ns.Items[0].Items[0]; Assert.NotNull(method); Assert.True(method.IsExtensionMethod); Assert.Equal(@"public static void Method1(this object obj)", method.Syntax.Content[SyntaxLanguage.CSharp]); Assert.Equal(@"<ExtensionAttribute> Public Shared Sub Method1(obj As Object)", method.Syntax.Content[SyntaxLanguage.VB]); } [Fact] [Trait("Related", "Generic")] public void TestGenerateMetadataAsyncWithInheritedFromGenericClass() { string code = @" namespace Test1 { public interface I1<T> { public void M1(T obj) {} } public interface I2<T> : I1<string>, I1<T> {} } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var i1 = ns.Items[0]; Assert.NotNull(i1); Assert.Equal("Test1.I1`1", i1.Name); Assert.Single(i1.Items); Assert.Null(i1.InheritedMembers); var m1 = i1.Items[0]; Assert.Equal("Test1.I1`1.M1(`0)", m1.Name); var i2 = ns.Items[1]; Assert.NotNull(i2); Assert.Equal("Test1.I2`1", i2.Name); Assert.Empty(i2.Items); Assert.Equal(2, i2.InheritedMembers.Count); Assert.Equal(new[] { "Test1.I1{System.String}.M1(System.String)", "Test1.I1{{T}}.M1({T})" }, i2.InheritedMembers); var r1 = output.References["Test1.I1{System.String}.M1(System.String)"]; Assert.False(r1.IsDefinition); Assert.Equal("Test1.I1`1.M1(`0)", r1.Definition); var r2 = output.References["Test1.I1{{T}}.M1({T})"]; Assert.False(r1.IsDefinition); Assert.Equal("Test1.I1`1.M1(`0)", r1.Definition); } [Fact] [Trait("Related", "Generic")] public void TestCSharpFeature_Default_7_1Class() { string code = @" namespace Test1 { public class Foo { public int Bar(int x = default) => 1; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar(System.Int32)", bar.Name); Assert.Equal("public int Bar(int x = 0)", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithTupleParameter() { string code = @" namespace Test1 { public class Foo { public int Bar((string prefix, string uri) @namespace) => 1; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar(System.ValueTuple{System.String,System.String})", bar.Name); Assert.Equal("public int Bar((string prefix, string uri) namespace)", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithUnnamedTupleParameter() { string code = @" namespace Test1 { public class Foo { public int Bar((string, string) @namespace) => 1; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar(System.ValueTuple{System.String,System.String})", bar.Name); Assert.Equal("public int Bar((string, string) namespace)", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithPartiallyUnnamedTupleParameter() { string code = @" namespace Test1 { public class Foo { public int Bar((string, string uri) @namespace) => 1; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar(System.ValueTuple{System.String,System.String})", bar.Name); Assert.Equal("public int Bar((string, string uri) namespace)", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithTupleArrayParameter() { string code = @" namespace Test1 { public class Foo { public int Bar((string prefix, string uri)[] namespaces) => 1; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar(System.ValueTuple{System.String,System.String}[])", bar.Name); Assert.Equal("public int Bar((string prefix, string uri)[] namespaces)", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithTupleEnumerableParameter() { string code = @" using System.Collections.Generic; namespace Test1 { public class Foo { public int Bar(IEnumerable<(string prefix, string uri)> namespaces) => 1; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar(System.Collections.Generic.IEnumerable{System.ValueTuple{System.String,System.String}})", bar.Name); Assert.Equal("public int Bar(IEnumerable<(string prefix, string uri)> namespaces)", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithTupleResult() { string code = @" namespace Test1 { public class Foo { public (string prefix, string uri) Bar() => (string.Empty, string.Empty); } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar", bar.Name); Assert.Equal("public (string prefix, string uri) Bar()", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithUnnamedTupleResult() { string code = @" namespace Test1 { public class Foo { public (string, string) Bar() => (string.Empty, string.Empty); } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar", bar.Name); Assert.Equal("public (string, string) Bar()", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithPartiallyUnnamedTupleResult() { string code = @" namespace Test1 { public class Foo { public (string, string uri) Bar() => (string.Empty, string.Empty); } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar", bar.Name); Assert.Equal("public (string, string uri) Bar()", bar.Syntax.Content[SyntaxLanguage.CSharp]); } [Fact] [Trait("Related", "ValueTuple")] public void TestGenerateMetadataAsyncWithEnumerableTupleResult() { string code = @" using System.Collections.Generic; namespace Test1 { public class Foo { public IEnumerable<(string prefix, string uri)> Bar() => new (string.Empty, string.Empty)[0]; } } "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromCSharpCode(code)); Assert.Single(output.Items); var ns = output.Items[0]; Assert.NotNull(ns); var foo = ns.Items[0]; Assert.NotNull(foo); Assert.Equal("Test1.Foo", foo.Name); Assert.Single(foo.Items); var bar = foo.Items[0]; Assert.Equal("Test1.Foo.Bar", bar.Name); Assert.Equal("public IEnumerable<(string prefix, string uri)> Bar()", bar.Syntax.Content[SyntaxLanguage.CSharp]); } private static Compilation CreateCompilationFromCSharpCode(string code, params MetadataReference[] references) { return CreateCompilationFromCSharpCode(code, "test.dll", references); } private static Compilation CreateCompilationFromCSharpCode(string code, string assemblyName, params MetadataReference[] references) { var tree = SyntaxFactory.ParseSyntaxTree(code); var defaultReferences = new List<MetadataReference> { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(EditorBrowsableAttribute).Assembly.Location) }; if (references != null) { defaultReferences.AddRange(references); } var compilation = CSharpCompilation.Create( assemblyName, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: defaultReferences); return compilation; } private static Assembly CreateAssemblyFromCSharpCode(string code, string assemblyName) { // MemoryStream fails when MetadataReference.CreateFromAssembly with error: Empty path name is not legal var compilation = CreateCompilationFromCSharpCode(code); EmitResult result; using (FileStream stream = new FileStream(assemblyName, FileMode.Create)) { result = compilation.Emit(stream); } Assert.True(result.Success, string.Join(",", result.Diagnostics.Select(s => s.GetMessage()))); return Assembly.LoadFile(Path.GetFullPath(assemblyName)); } } }
54.932232
496
0.586802
[ "MIT" ]
AngryBerryMS/docfx
test/Microsoft.DocAsCode.Metadata.ManagedReference.Tests/GenerateMetadataFromCSUnitTest.cs
159,964
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace ModIO.UI { public enum PageTransitionDirection { FromLeft, FromRight, } public class ExplorerView : MonoBehaviour { // ---------[ NESTED DATA-TYPES ]--------- /// <summary>Event for notifying listeners of a change to displayed mods.</summary> [Serializable] public class ModPageChanged : UnityEngine.Events.UnityEvent<RequestPage<ModProfile>> {} /// <summary>Event for notifying listeners of a change to the request filter.</summary> [Serializable] public class RequestFilterChanged : UnityEngine.Events.UnityEvent<RequestFilter> {} /// <summary>Sort method data.</summary> [Serializable] public struct SortMethod { public bool ascending; public string fieldName; } // ---------[ FIELDS ]--------- [Header("UI Components")] /// <summary>Container used to display mods.</summary> public ModContainer pageTemplate = null; /// <summary>Button for transitioning to the previous page of results.</summary> public Button prevPageButton; /// <summary>Button for transitioning to the next page of results.</summary> public Button nextPageButton; /// <summary>Object to display when no results were found.</summary> [Tooltip("Object to display when no results were found.")] public GameObject noResultsDisplay; /// <summary>Object that should react to this view being enabled/disabled.</summary> public StateToggleDisplay isActiveIndicator; [Header("Settings")] /// <summary>Default sort method.</summary> public SortMethod defaultSortMethod = new SortMethod() { ascending = false, fieldName = API.GetAllModsFilterFields.dateLive, }; /// <summary>Number of seconds per page transition.</summary> public float pageTransitionTimeSeconds = 0.4f; [Header("Events")] /// <summary>Event for notifying listeners of a change to displayed mods.</summary> public ModPageChanged onModPageChanged = null; /// <summary>Event for notifying listeners of a change to the request filter.</summary> public RequestFilterChanged onRequestFilterChanged = null; // --- Run-time Data --- /// <summary>RequestPage being displayed.</summary> private RequestPage<ModProfile> m_modPage = null; /// <summary>RequestPage being transitioned to.</summary> private RequestPage<ModProfile> m_transitionPage = null; /// <summary>Currently applied RequestFilter.</summary> private RequestFilter m_requestFilter = new RequestFilter(); /// <summary>The mod container being used for the mod page display.</summary> private ModContainer m_modPageContainer = null; /// <summary>The mod container being used for the transition page display.</summary> private ModContainer m_transitionPageContainer = null; /// <summary>Whether the view is currently transitioning between pages.</summary> private bool m_isTransitioning = false; // --- Accessors --- /// <summary>RequestPage being displayed.</summary> public RequestPage<ModProfile> modPage { get { return this.m_modPage; } } /// <summary>RequestPage being transitioned to.</summary> public RequestPage<ModProfile> transitionPage { get { return this.m_transitionPage; } } /// <summary>Currently applied RequestFilter.</summary> public RequestFilter requestFilter { get { return this.m_requestFilter; } } /// <summary>Filter currently applied to the mod name.</summary> protected EqualToFilter<string> nameFieldFilter { get { List<IRequestFieldFilter> filterList = null; if(this.m_requestFilter.fieldFilterMap.TryGetValue(ModIO.API.GetAllModsFilterFields.fullTextSearch, out filterList) && filterList != null && filterList.Count > 0) { return filterList[0] as EqualToFilter<string>; } return null; } set { if(value == null) { this.m_requestFilter.fieldFilterMap.Remove(ModIO.API.GetAllModsFilterFields.fullTextSearch); } else { List<IRequestFieldFilter> filterList = null; if(this.m_requestFilter.fieldFilterMap.TryGetValue(ModIO.API.GetAllModsFilterFields.fullTextSearch, out filterList) && filterList != null && filterList.Count > 0) { filterList[0] = value; } else { this.m_requestFilter.AddFieldFilter(ModIO.API.GetAllModsFilterFields.fullTextSearch, value); } } } } /// <summary>Filter currently applied to the tags field.</summary> protected MatchesArrayFilter<string> tagMatchFieldFilter { get { List<IRequestFieldFilter> filterList = null; if(this.m_requestFilter.fieldFilterMap.TryGetValue(ModIO.API.GetAllModsFilterFields.tags, out filterList) && filterList != null && filterList.Count > 0) { return filterList[0] as MatchesArrayFilter<string>; } return null; } set { if(value == null) { this.m_requestFilter.fieldFilterMap.Remove(ModIO.API.GetAllModsFilterFields.tags); } else { List<IRequestFieldFilter> filterList = null; if(this.m_requestFilter.fieldFilterMap.TryGetValue(ModIO.API.GetAllModsFilterFields.tags, out filterList) && filterList != null && filterList.Count > 0) { filterList[0] = value; } else { this.m_requestFilter.AddFieldFilter(ModIO.API.GetAllModsFilterFields.tags, value); } } } } /// <summary>Accessor for the ModProfileRequestManager instance.</summary> private ModProfileRequestManager profileManager { get { return ModProfileRequestManager.instance; } } // ---------[ INITIALIZATION ]--------- /// <summary>Asserts values and initializes templates.</summary> protected virtual void Start() { Debug.Assert(this.gameObject != this.pageTemplate.gameObject, "[mod.io] The Explorer View and its Container Template cannot be the same" + " Game Object. Please create a separate Game Object for the container template."); #if UNITY_EDITOR ExplorerView[] nested = this.gameObject.GetComponentsInChildren<ExplorerView>(true); if(nested.Length > 1) { ExplorerView nestedView = nested[1]; if(nestedView == this) { nestedView = nested[0]; } Debug.LogError("[mod.io] Nesting ExplorerViews is currently not supported due to the" + " way IExplorerViewElement component parenting works." + "\nThe nested ExplorerViews must be removed to allow ExplorerView functionality." + "\nthis=" + this.gameObject.name + "\nnested=" + nestedView.gameObject.name, this); return; } #endif // -- initialize template --- this.pageTemplate.gameObject.SetActive(false); GameObject templateCopyGO; // current page templateCopyGO = GameObject.Instantiate(this.pageTemplate.gameObject, this.pageTemplate.transform.parent); templateCopyGO.name = "Mod Page A"; // TODO(@jackson): Change this... templateCopyGO.SetActive(true); templateCopyGO.transform.SetSiblingIndex(this.pageTemplate.transform.GetSiblingIndex() + 1); this.m_modPageContainer = templateCopyGO.GetComponent<ModContainer>(); this.m_modPageContainer.onItemLimitChanged += (i) => this.Refresh(); // transition page templateCopyGO = GameObject.Instantiate(this.pageTemplate.gameObject, this.pageTemplate.transform.parent); templateCopyGO.name = "Mod Page B"; templateCopyGO.SetActive(false); templateCopyGO.transform.SetSiblingIndex(this.pageTemplate.transform.GetSiblingIndex() + 2); this.m_transitionPageContainer = templateCopyGO.GetComponent<ModContainer>(); // assign view elements to this var viewElementChildren = this.gameObject.GetComponentsInChildren<IExplorerViewElement>(true); foreach(IExplorerViewElement viewElement in viewElementChildren) { viewElement.SetExplorerView(this); } // - create pages - this.UpdateModPageDisplay(); this.UpdatePageButtonInteractibility(); // - perform initial fetch - this.Refresh(); } private void OnEnable() { if(this.isActiveIndicator != null) { this.isActiveIndicator.isOn = true; } } private void OnDisable() { if(this.isActiveIndicator != null) { this.isActiveIndicator.isOn = false; } } public void Refresh() { int pageIndex = 0; int pageSize = this.m_modPageContainer.itemLimit; if(pageSize < 0) { pageSize = APIPaginationParameters.LIMIT_MAX; } int pageOffset = pageIndex * pageSize; bool wasDisplayUpdated = false; RequestPage<ModProfile> filteredPage = new RequestPage<ModProfile>() { size = pageSize, items = new ModProfile[pageSize], resultOffset = pageOffset, resultTotal = 0, }; this.m_modPage = filteredPage; ModProfileRequestManager.instance.FetchModProfilePage(this.m_requestFilter, pageOffset, pageSize, (page) => { if(this != null && this.m_modPage == filteredPage) { this.DisplayModPage(page); wasDisplayUpdated = true; } }, WebRequestError.LogAsWarning); if(!wasDisplayUpdated) { // force updates this.m_modPage = null; this.DisplayModPage(filteredPage); } } public void UpdatePageButtonInteractibility() { if(this.prevPageButton != null) { this.prevPageButton.interactable = (!this.m_isTransitioning && this.modPage != null && this.modPage.CalculatePageIndex() > 0); } if(this.nextPageButton != null) { this.nextPageButton.interactable = (!this.m_isTransitioning && this.modPage != null && this.modPage.CalculatePageIndex()+1 < this.modPage.CalculatePageCount()); } } public void ChangePage(int pageDifferential) { Debug.Assert(this.modPage != null); if(this.m_isTransitioning) { return; } int pageSize = this.m_modPageContainer.itemLimit; if(pageSize < 0) { pageSize = APIPaginationParameters.LIMIT_MAX; } int targetPageIndex = this.m_modPage.CalculatePageIndex() + pageDifferential; int targetPageProfileOffset = targetPageIndex * pageSize; Debug.Assert(targetPageIndex >= 0); Debug.Assert(targetPageIndex < this.m_modPage.CalculatePageCount()); int pageItemCount = (int)Mathf.Min(pageSize, this.m_modPage.resultTotal - targetPageProfileOffset); RequestPage<ModProfile> transitionPlaceholder = new RequestPage<ModProfile>() { size = pageSize, items = new ModProfile[pageItemCount], resultOffset = targetPageProfileOffset, resultTotal = this.m_modPage.resultTotal, }; this.m_transitionPage = transitionPlaceholder; this.UpdateTransitionPageDisplay(); ModProfileRequestManager.instance.FetchModProfilePage(this.m_requestFilter, targetPageProfileOffset, pageSize, (page) => { if(this.m_transitionPage == transitionPlaceholder) { this.m_transitionPage = page; this.UpdateTransitionPageDisplay(); } if(this.m_modPage == transitionPlaceholder) { this.DisplayModPage(page); } }, null); PageTransitionDirection transitionDirection = (pageDifferential < 0 ? PageTransitionDirection.FromLeft : PageTransitionDirection.FromRight); this.InitiateTargetPageTransition(transitionDirection, null); this.UpdatePageButtonInteractibility(); } // ---------[ FILTER CONTROL ]--------- /// <summary>Sets the title filter and refreshes the view.</summary> public void SetNameFieldFilter(string nameFilter) { EqualToFilter<string> oldFilter = this.nameFieldFilter; // null-checks if(nameFilter == null) { nameFilter = string.Empty; } string oldFilterValue = string.Empty; if(oldFilter != null && oldFilter.filterValue != null) { oldFilterValue = oldFilter.filterValue; } // apply filter if(oldFilterValue.ToUpper() != nameFilter.ToUpper()) { // set if(String.IsNullOrEmpty(nameFilter)) { this.nameFieldFilter = null; } else { EqualToFilter<string> newFieldFilter = new EqualToFilter<string>() { filterValue = nameFilter, }; this.nameFieldFilter = newFieldFilter; } // refresh if(this.isActiveAndEnabled) { this.Refresh(); } // notify if(this.onRequestFilterChanged != null) { this.onRequestFilterChanged.Invoke(this.m_requestFilter); } } } /// <summary>Gets the title filter string.</summary> public string GetTitleFilter() { EqualToFilter<string> filter = this.nameFieldFilter; if(filter == null) { return null; } else { return filter.filterValue; } } /// <summary>Sets the sort method and refreshes the view.</summary> public void SetSortMethod(SortMethod sortMethod) { // null-checks if(sortMethod.fieldName == null) { sortMethod.fieldName = string.Empty; } // apply filter if(this.m_requestFilter.sortFieldName.ToUpper() != sortMethod.fieldName.ToUpper() || this.m_requestFilter.isSortAscending != sortMethod.ascending) { this.m_requestFilter.sortFieldName = sortMethod.fieldName; this.m_requestFilter.isSortAscending = sortMethod.ascending; // refresh if(this.isActiveAndEnabled) { this.Refresh(); } // notify if(this.onRequestFilterChanged != null) { this.onRequestFilterChanged.Invoke(this.m_requestFilter); } } } /// <summary>Sets the sort method and refreshes the view.</summary> public void SetSortMethod(bool ascending, string fieldName) { // create struct SortMethod sortMethod = new SortMethod() { ascending = ascending, fieldName = fieldName, }; this.SetSortMethod(sortMethod); } /// <summary>Gets the sort method.</summary> public SortMethod GetSortMethod() { return new SortMethod() { ascending = this.m_requestFilter.isSortAscending, fieldName = this.m_requestFilter.sortFieldName, }; } /// <summary>Sets the tag filter and refreshes the results.</summary> public void SetTagFilter(IList<string> tagFilter) { MatchesArrayFilter<string> oldFilter = this.tagMatchFieldFilter; // null-checks if(tagFilter == null) { tagFilter = new string[0]; } string[] oldFilterValue = new string[0]; if(oldFilter != null) { oldFilterValue = oldFilter.filterArray; } // check if same and copy bool isSame = (oldFilterValue.Length == tagFilter.Count); string[] newFilterValue = new string[tagFilter.Count]; if(tagFilter != oldFilterValue) { for(int i = 0; i < newFilterValue.Length; ++i) { newFilterValue[i] = tagFilter[i]; isSame = isSame && (oldFilterValue[i] == newFilterValue[i]); } } // apply if(!isSame) { // set if(newFilterValue.Length == 0) { this.tagMatchFieldFilter = null; } else { MatchesArrayFilter<string> newFilter = new MatchesArrayFilter<string>() { filterArray = newFilterValue, }; this.tagMatchFieldFilter = newFilter; } // refresh if(this.isActiveAndEnabled) { this.Refresh(); } // notify if(this.onRequestFilterChanged != null) { this.onRequestFilterChanged.Invoke(this.m_requestFilter); } } } /// <summary>Gets the tag filter.</summary> public string[] GetTagFilter() { MatchesArrayFilter<string> filter = this.tagMatchFieldFilter; if(filter == null) { return null; } else { return filter.filterArray; } } /// <summary>Adds a tag to the tag filter and refreshes the results.</summary> public void AddTagToFilter(string tagName) { // get existing MatchesArrayFilter<string> tagFilter = this.tagMatchFieldFilter; if(tagFilter == null) { tagFilter = new MatchesArrayFilter<string>(); tagFilter.filterValue = new string[0]; } List<string> tagFilterValues = new List<string>(); tagFilterValues.AddRange(tagFilter.filterArray); // add if(!tagFilterValues.Contains(tagName)) { tagFilterValues.Add(tagName); tagFilter.filterArray = tagFilterValues.ToArray(); this.tagMatchFieldFilter = tagFilter; // refresh if(this.isActiveAndEnabled) { this.Refresh(); } // notify if(this.onRequestFilterChanged != null) { this.onRequestFilterChanged.Invoke(this.m_requestFilter); } } } /// <summary>Removes a tag from the tag filter and refreshes the results.</summary> public void RemoveTagFromFilter(string tagName) { MatchesArrayFilter<string> tagFilter = this.tagMatchFieldFilter; // early out if(tagFilter == null || tagFilter.filterArray == null || tagFilter.filterArray.Length == 0) { return; } // create list List<string> tagFilterValues = new List<string>(tagFilter.filterArray); if(tagFilterValues.Contains(tagName)) { tagFilterValues.Remove(tagName); if(tagFilterValues.Count == 0) { this.tagMatchFieldFilter = null; } else { tagFilter.filterArray = tagFilterValues.ToArray(); } // refresh if(this.isActiveAndEnabled) { this.Refresh(); } // notify if(this.onRequestFilterChanged != null) { this.onRequestFilterChanged.Invoke(this.m_requestFilter); } } } // ---------[ PAGE DISPLAY ]--------- public void UpdateModPageDisplay() { if(this.m_modPageContainer == null) { return; } #if DEBUG if(m_isTransitioning) { Debug.LogWarning("[mod.io] Explorer View is currently transitioning between pages. It" + " is recommended to not update page displays at this time."); } #endif if(noResultsDisplay != null) { noResultsDisplay.SetActive(this.m_modPage == null || this.m_modPage.items == null || this.m_modPage.items.Length == 0); } IList<ModProfile> profiles = null; if(this.m_modPage != null) { profiles = this.m_modPage.items; } this.DisplayProfiles(profiles, this.m_modPageContainer); } public void UpdateTransitionPageDisplay() { if(this.m_transitionPageContainer == null) { return; } #if DEBUG if(m_isTransitioning) { Debug.LogWarning("[mod.io] Explorer View is currently transitioning between pages. It" + " is recommended to not update page displays at this time."); } #endif this.DisplayProfiles(this.m_transitionPage.items, this.m_transitionPageContainer); } protected virtual void DisplayProfiles(IList<ModProfile> profileCollection, ModContainer modContainer) { Debug.Assert(modContainer != null); if(profileCollection == null) { profileCollection = new ModProfile[0]; } // init vars int displayCount = profileCollection.Count; ModProfile[] displayProfiles = new ModProfile[displayCount]; ModStatistics[] displayStats = new ModStatistics[displayCount]; List<int> missingStatsData = new List<int>(displayCount); // build arrays for(int i = 0; i < displayCount; ++i) { ModProfile profile = profileCollection[i]; ModStatistics stats = null; if(profile != null) { stats = ModStatisticsRequestManager.instance.TryGetValid(profile.id); if(stats == null) { missingStatsData.Add(profile.id); } } displayProfiles[i] = profile; displayStats[i] = stats; } // display modContainer.DisplayMods(displayProfiles, displayStats); // fetch missing stats if(missingStatsData.Count > 0) { ModStatisticsRequestManager.instance.RequestModStatistics(missingStatsData, (statsArray) => { if(this != null && modContainer != null) { // verify still valid bool doPushStats = (displayProfiles.Length == modContainer.modProfiles.Length); for(int i = 0; doPushStats && i < displayProfiles.Length; ++i) { // check profiles match ModProfile profile = displayProfiles[i]; doPushStats = (profile == modContainer.modProfiles[i]); if(doPushStats && profile != null && displayStats[i] == null) { // get missing stats foreach(ModStatistics stats in statsArray) { if(stats != null && stats.modId == profile.id) { displayStats[i] = stats; break; } } } } // push display data if(doPushStats) { modContainer.DisplayMods(displayProfiles, displayStats); } } }, WebRequestError.LogAsWarning); } } // ----------[ PAGE TRANSITIONS ]--------- public void InitiateTargetPageTransition(PageTransitionDirection direction, Action onTransitionCompleted) { if(!m_isTransitioning) { float containerWidth = ((RectTransform)this.m_modPageContainer.transform.parent).rect.width; float mainPaneTargetX = containerWidth * (direction == PageTransitionDirection.FromLeft ? 1f : -1f); float transPaneStartX = mainPaneTargetX * -1f; this.m_modPageContainer.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; this.m_transitionPageContainer.GetComponent<RectTransform>().anchoredPosition = new Vector2(transPaneStartX, 0f); StartCoroutine(TransitionPageCoroutine(mainPaneTargetX, transPaneStartX, this.pageTransitionTimeSeconds, onTransitionCompleted)); } #if DEBUG else { Debug.LogWarning("[mod.io] ModPages are already transitioning."); } #endif } private IEnumerator TransitionPageCoroutine(float mainPaneTargetX, float transitionPaneStartX, float transitionLength, Action onTransitionCompleted) { m_isTransitioning = true; this.m_transitionPageContainer.gameObject.SetActive(true); float transitionTime = 0f; // transition while(transitionTime < transitionLength) { float transPos = Mathf.Lerp(0f, mainPaneTargetX, transitionTime / transitionLength); this.m_modPageContainer.GetComponent<RectTransform>().anchoredPosition = new Vector2(transPos, 0f); this.m_transitionPageContainer.GetComponent<RectTransform>().anchoredPosition = new Vector2(transPos + transitionPaneStartX, 0f); transitionTime += Time.unscaledDeltaTime; yield return null; } // flip var tempContainer = this.m_modPageContainer; this.m_modPageContainer = this.m_transitionPageContainer; this.m_transitionPageContainer = tempContainer; var tempPage = modPage; this.m_modPage = this.m_transitionPage; this.m_transitionPage = tempPage; // finalize this.m_modPageContainer.GetComponent<RectTransform>().anchoredPosition = Vector2.zero; this.m_transitionPageContainer.gameObject.SetActive(false); m_isTransitioning = false; // notify, etc this.UpdatePageButtonInteractibility(); if(this.onModPageChanged != null) { this.onModPageChanged.Invoke(this.m_modPage); } if(onTransitionCompleted != null) { onTransitionCompleted(); } } // ---------[ UTILITY ]--------- public void ClearAllFilters() { // Check if already cleared if(this.nameFieldFilter == null && this.tagMatchFieldFilter == null && this.GetSortMethod().Equals(this.defaultSortMethod)) { return; } // Clear this.m_requestFilter = new RequestFilter() { sortFieldName = this.defaultSortMethod.fieldName, isSortAscending = this.defaultSortMethod.ascending, }; this.Refresh(); // notify if(this.onRequestFilterChanged != null) { this.onRequestFilterChanged.Invoke(this.m_requestFilter); } } /// <summary>Sets the mod page, updates displays, and notifies event listeners.</summary> protected void DisplayModPage(RequestPage<ModProfile> newModPage) { if(this.m_modPage != newModPage) { this.m_modPage = newModPage; this.UpdateModPageDisplay(); this.UpdatePageButtonInteractibility(); if(this.onModPageChanged != null) { this.onModPageChanged.Invoke(newModPage); } } } // ---------[ OBSOLETE ]--------- [Obsolete("Use ExplorerView.pageTemplate instead.")][HideInInspector] public GameObject itemPrefab = null; [Obsolete("Use ExplorerView.defaultSortMethod instead.")][HideInInspector] public string defaultSortString = string.Empty; [Obsolete("Use PageNumberDisplay component instead.")][HideInInspector] public Text pageNumberText; [Obsolete("Use PageCountDisplay component instead.")][HideInInspector] public Text pageCountText; [Obsolete("Use ResultCountDisplay component instead.")][HideInInspector] public Text resultCountText; [Obsolete("No longer supported.")][HideInInspector] public RectTransform currentPageContainer; [Obsolete("No longer supported.")][HideInInspector] public RectTransform transitionPageContainer; [Obsolete("No longer supported.")][HideInInspector] public GridLayoutGroup gridLayout; [Obsolete("Use ExplorerView.modPage instead.")] public RequestPage<ModProfile> currentPage { get { return this.modPage; } set {} } [Obsolete("Use ExplorerView.transitionPage instead.")] public RequestPage<ModProfile> targetPage { get { return this.transitionPage; } } [Obsolete("No longer necessary.")][HideInInspector] public RectTransform contentPane { get { if(this.m_modPageContainer != null) { return this.m_modPageContainer.transform.parent as RectTransform; } return null; } set {} } [Obsolete] public int itemsPerPage { get { return this.pageTemplate.itemLimit; } } [Obsolete("No longer supported.")] public IEnumerable<ModView> modViews { get { if(this.m_modPageContainer != null) { return this.m_modPageContainer.GetModViews(); } return null; } } [Obsolete("Use ExplorerView.modPage.CalculatePageIndex() instead.")] public int CurrentPageNumber { get { if(this.modPage != null) { return 1+this.modPage.CalculatePageIndex(); } return 0; } } [Obsolete("Use ExplorerView.modPage.CalculatePageCount() instead.")] public int CurrentPageCount { get { if(this.modPage != null) { return this.modPage.CalculatePageCount(); } return 0; } } #pragma warning disable 0067 [Obsolete("No longer supported. Use ExplorerView.onRequestFilterChanged instead.", true)] public event Action<string[]> onTagFilterUpdated; #pragma warning restore 0067 [Obsolete("No longer necessary. Initialization occurs in Start().")] public void Initialize() {} [Obsolete("Use ExplorerView.UpdateModPageDisplay() instead.")] public void UpdateCurrentPageDisplay() { this.UpdateModPageDisplay(); } [Obsolete("Use ExplorerView.UpdateTransitionPageDisplay() instead.")] public void UpdateTargetPageDisplay() { this.UpdateTransitionPageDisplay(); } [Obsolete("Use ExplorerView.ClearAllFilters() instead.")] public void ClearFilters() { ClearAllFilters(); } [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public event Action<ModView> inspectRequested; [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public void NotifyInspectRequested(ModView view) { if(inspectRequested != null) { inspectRequested(view); } } [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public event Action<ModView> subscribeRequested; [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public void NotifySubscribeRequested(ModView view) { if(subscribeRequested != null) { subscribeRequested(view); } } [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public event Action<ModView> unsubscribeRequested; [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public void NotifyUnsubscribeRequested(ModView view) { if(unsubscribeRequested != null) { unsubscribeRequested(view); } } [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public event Action<ModView> enableModRequested; [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public void NotifyEnableRequested(ModView view) { if(enableModRequested != null) { enableModRequested(view); } } [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public event Action<ModView> disableModRequested; [Obsolete("No longer necessary. Event is directly linked to ModBrowser.")] public void NotifyDisableRequested(ModView view) { if(disableModRequested != null) { disableModRequested(view); } } [Obsolete("Use ExplorerView.SetSortMethod() instead.")] public void SetSortString(string sortString) { if(sortString == null) { sortString = string.Empty; } // set vars string fieldName = sortString; bool ascending = true; // check for descending if(sortString.StartsWith("-")) { ascending = false; if(sortString.Length > 1) { fieldName = sortString.Substring(1); } else { fieldName = string.Empty; } } this.SetSortMethod(ascending, fieldName); } [Obsolete("Use ExplorerView.GetSortMethod() instead.")] public string GetSortString() { string sortString = (this.m_requestFilter.isSortAscending ? "" : "-") + this.m_requestFilter.sortFieldName; return sortString; } [Obsolete] public RequestFilter GenerateRequestFilter() { return this.m_requestFilter; } } }
36.38657
146
0.504913
[ "MIT" ]
TrutzX/9Nations
Assets/Plugins/mod.io/Scripts/UI/ExplorerView.cs
40,100
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v5/common/feed_common.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V5.Common { /// <summary>Holder for reflection information generated from google/ads/googleads/v5/common/feed_common.proto</summary> public static partial class FeedCommonReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v5/common/feed_common.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static FeedCommonReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjBnb29nbGUvYWRzL2dvb2dsZWFkcy92NS9jb21tb24vZmVlZF9jb21tb24u", "cHJvdG8SHmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY1LmNvbW1vbhoeZ29vZ2xl", "L3Byb3RvYnVmL3dyYXBwZXJzLnByb3RvGhxnb29nbGUvYXBpL2Fubm90YXRp", "b25zLnByb3RvInAKBU1vbmV5EjMKDWN1cnJlbmN5X2NvZGUYASABKAsyHC5n", "b29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUSMgoNYW1vdW50X21pY3JvcxgC", "IAEoCzIbLmdvb2dsZS5wcm90b2J1Zi5JbnQ2NFZhbHVlQuoBCiJjb20uZ29v", "Z2xlLmFkcy5nb29nbGVhZHMudjUuY29tbW9uQg9GZWVkQ29tbW9uUHJvdG9Q", "AVpEZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMv", "Z29vZ2xlYWRzL3Y1L2NvbW1vbjtjb21tb26iAgNHQUGqAh5Hb29nbGUuQWRz", "Lkdvb2dsZUFkcy5WNS5Db21tb27KAh5Hb29nbGVcQWRzXEdvb2dsZUFkc1xW", "NVxDb21tb27qAiJHb29nbGU6OkFkczo6R29vZ2xlQWRzOjpWNTo6Q29tbW9u", "YgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Common.Money), global::Google.Ads.GoogleAds.V5.Common.Money.Parser, new[]{ "CurrencyCode", "AmountMicros" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Represents a price in a particular currency. /// </summary> public sealed partial class Money : pb::IMessage<Money> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Money> _parser = new pb::MessageParser<Money>(() => new Money()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Money> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V5.Common.FeedCommonReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Money() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Money(Money other) : this() { CurrencyCode = other.CurrencyCode; AmountMicros = other.AmountMicros; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Money Clone() { return new Money(this); } /// <summary>Field number for the "currency_code" field.</summary> public const int CurrencyCodeFieldNumber = 1; private static readonly pb::FieldCodec<string> _single_currencyCode_codec = pb::FieldCodec.ForClassWrapper<string>(10); private string currencyCode_; /// <summary> /// Three-character ISO 4217 currency code. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CurrencyCode { get { return currencyCode_; } set { currencyCode_ = value; } } /// <summary>Field number for the "amount_micros" field.</summary> public const int AmountMicrosFieldNumber = 2; private static readonly pb::FieldCodec<long?> _single_amountMicros_codec = pb::FieldCodec.ForStructWrapper<long>(18); private long? amountMicros_; /// <summary> /// Amount in micros. One million is equivalent to one unit. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long? AmountMicros { get { return amountMicros_; } set { amountMicros_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Money); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Money other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (CurrencyCode != other.CurrencyCode) return false; if (AmountMicros != other.AmountMicros) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (currencyCode_ != null) hash ^= CurrencyCode.GetHashCode(); if (amountMicros_ != null) hash ^= AmountMicros.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (currencyCode_ != null) { _single_currencyCode_codec.WriteTagAndValue(output, CurrencyCode); } if (amountMicros_ != null) { _single_amountMicros_codec.WriteTagAndValue(output, AmountMicros); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (currencyCode_ != null) { _single_currencyCode_codec.WriteTagAndValue(ref output, CurrencyCode); } if (amountMicros_ != null) { _single_amountMicros_codec.WriteTagAndValue(ref output, AmountMicros); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (currencyCode_ != null) { size += _single_currencyCode_codec.CalculateSizeWithTag(CurrencyCode); } if (amountMicros_ != null) { size += _single_amountMicros_codec.CalculateSizeWithTag(AmountMicros); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Money other) { if (other == null) { return; } if (other.currencyCode_ != null) { if (currencyCode_ == null || other.CurrencyCode != "") { CurrencyCode = other.CurrencyCode; } } if (other.amountMicros_ != null) { if (amountMicros_ == null || other.AmountMicros != 0L) { AmountMicros = other.AmountMicros; } } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { string value = _single_currencyCode_codec.Read(input); if (currencyCode_ == null || value != "") { CurrencyCode = value; } break; } case 18: { long? value = _single_amountMicros_codec.Read(input); if (amountMicros_ == null || value != 0L) { AmountMicros = value; } break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { string value = _single_currencyCode_codec.Read(ref input); if (currencyCode_ == null || value != "") { CurrencyCode = value; } break; } case 18: { long? value = _single_amountMicros_codec.Read(ref input); if (amountMicros_ == null || value != 0L) { AmountMicros = value; } break; } } } } #endif } #endregion } #endregion Designer generated code
35.675958
213
0.667155
[ "Apache-2.0" ]
GraphikaPS/google-ads-dotnet
src/V5/Types/FeedCommon.cs
10,239
C#
// <auto-generated /> namespace BellumGens.Api.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class Subscribers : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(Subscribers)); string IMigrationMetadata.Id { get { return "201909112128222_Subscribers"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.3
94
0.620269
[ "MIT" ]
BellumGens/bellum-gens-api
BellumGens.Api/Migrations/201909112128222_Subscribers.Designer.cs
819
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Reflection; using System.Runtime.InteropServices; // Test assemblies should not use 'ConfigureAwait(false)' [assembly: DoNotUseConfigureAwait] [assembly: Guid("ee64e512-75d4-4415-a2a7-e93e4f49d602")]
29.9
58
0.765886
[ "MIT" ]
BearerPipelineTest/BuildXL
Public/Src/Cache/ContentStore/InterfacesTest/Properties/AssemblyInfo.cs
299
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using NUnit.Framework; using Omnifactotum.NUnit; namespace Omnifactotum.Tests { [TestFixture(TestOf = typeof(ReadOnlyItemCollection<>))] internal sealed class ReadOnlyItemCollectionTests { private const string Item1 = "11e2082d16b64d918dafd8e2e077ab4f"; private const string Item2 = "1ad469d8c40849bbbd4efca3fe28e3cb"; private const string Item3 = "b6acaaaae0fe4bf49414c27239e48ef8"; private const string AbsentItem = "de330e62b2d14bb284a6d8ebcbff4b4d"; [Test] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] public void TestInvalidConstruction() => Assert.That(() => new ReadOnlyItemCollection<int>(null), Throws.TypeOf<ArgumentNullException>()); [Test] public void TestConstruction() { var testeeContainer = CreateTesteeContainer(); testeeContainer.EnsureUnchanged(); } [Test] public void TestTrackingChanges() { const string ExtraItem = @"3e4097657a9a4f13a31ecae72ba495a4"; var testeeContainer = CreateTesteeContainer(); testeeContainer.EnsureUnchanged(); testeeContainer.ReferenceCollection.Add(ExtraItem); testeeContainer.EnsureMatchesWrappedCollection(); Assert.That(testeeContainer.ReferenceCollection.Count, Is.EqualTo(testeeContainer.OriginalCount + 1)); Assert.That(testeeContainer.Testee.Contains(ExtraItem), Is.True); Assert.That(testeeContainer.TesteeAsCollection.Contains(ExtraItem), Is.True); Assert.That(testeeContainer.TesteeAsReadOnlyCollection.Contains(ExtraItem), Is.True); testeeContainer.ReferenceCollection.Remove(Item2); testeeContainer.EnsureMatchesWrappedCollection(); Assert.That(testeeContainer.ReferenceCollection.Count, Is.EqualTo(testeeContainer.OriginalCount)); Assert.That(testeeContainer.Testee.Contains(Item2), Is.False); Assert.That(testeeContainer.TesteeAsCollection.Contains(Item2), Is.False); Assert.That(testeeContainer.TesteeAsReadOnlyCollection.Contains(Item2), Is.False); testeeContainer.ReferenceCollection.Clear(); testeeContainer.EnsureMatchesWrappedCollection(); Assert.That(testeeContainer.ReferenceCollection.Count, Is.Zero); Assert.That(testeeContainer.ReferenceCollection, Is.Empty); Assert.That(testeeContainer.Testee.Count, Is.Zero); Assert.That(testeeContainer.Testee, Is.Empty); Assert.That(testeeContainer.TesteeAsCollection.Count, Is.Zero); Assert.That(testeeContainer.TesteeAsCollection, Is.Empty); Assert.That(testeeContainer.TesteeAsReadOnlyCollection.Count, Is.Zero); Assert.That(testeeContainer.TesteeAsReadOnlyCollection, Is.Empty); } [Test] public void TestReadOnlyBehavior() { var testeeContainer = CreateTesteeContainer(); testeeContainer.EnsureUnchanged(); testeeContainer.AssertNotSupportedExceptionAndEnsureUnchanged(() => testeeContainer.TesteeAsCollection.Add(@"An item")); testeeContainer.AssertNotSupportedExceptionAndEnsureUnchanged(() => testeeContainer.TesteeAsCollection.Clear()); testeeContainer.AssertNotSupportedExceptionAndEnsureUnchanged(() => testeeContainer.TesteeAsCollection.Remove(Item1)); } private static TesteeContainer CreateTesteeContainer() => new(); private sealed class TesteeContainer { private readonly string[] _originalItems; internal TesteeContainer() { ReferenceCollection = new List<string> { Item1, Item2, Item3 }; _originalItems = ReferenceCollection.ToArray(); Testee = new ReadOnlyItemCollection<string>(ReferenceCollection); } public int OriginalCount => _originalItems.Length; public ICollection<string> ReferenceCollection { get; } public ReadOnlyItemCollection<string> Testee { get; } public ICollection<string> TesteeAsCollection => Testee; public IReadOnlyCollection<string> TesteeAsReadOnlyCollection => Testee; public void EnsureMatchesWrappedCollection() { Assert.That(Testee.Count, Is.EqualTo(ReferenceCollection.Count)); Assert.That(Testee, Is.EquivalentTo(ReferenceCollection)); Assert.That(Testee.AsEnumerable().ToArray(), Is.EquivalentTo(ReferenceCollection)); Assert.That(Testee.Contains(AbsentItem), Is.False); foreach (var item in ReferenceCollection) { Assert.That(Testee.Contains(item), Is.True); } var testeeItems = new string[Testee.Count]; Testee.CopyTo(testeeItems, 0); Assert.That(testeeItems, Is.EquivalentTo(ReferenceCollection)); Assert.That(TesteeAsCollection.IsReadOnly, Is.True); Assert.That(TesteeAsCollection.Count, Is.EqualTo(ReferenceCollection.Count)); Assert.That(TesteeAsCollection, Is.EquivalentTo(ReferenceCollection)); Assert.That(TesteeAsCollection.Contains(AbsentItem), Is.False); foreach (var item in ReferenceCollection) { Assert.That(TesteeAsCollection.Contains(item), Is.True); } var testeeAsCollectionItems = new string[TesteeAsCollection.Count]; TesteeAsCollection.CopyTo(testeeAsCollectionItems, 0); Assert.That(testeeAsCollectionItems, Is.EquivalentTo(ReferenceCollection)); Assert.That(TesteeAsReadOnlyCollection.Count, Is.EqualTo(ReferenceCollection.Count)); Assert.That(TesteeAsReadOnlyCollection, Is.EquivalentTo(ReferenceCollection)); Assert.That(TesteeAsReadOnlyCollection.Contains(AbsentItem), Is.False); foreach (var item in ReferenceCollection) { Assert.That(TesteeAsReadOnlyCollection.Contains(item), Is.True); } } public void EnsureUnchanged() { Assert.That(ReferenceCollection, Is.EquivalentTo(_originalItems)); EnsureMatchesWrappedCollection(); } public void AssertNotSupportedExceptionAndEnsureUnchanged(TestDelegate code) { Assert.That(code.AssertNotNull(), Throws.TypeOf<NotSupportedException>()); EnsureUnchanged(); } } } }
46.856164
132
0.65926
[ "MIT" ]
HarinezumiSama/omnifactotum
src/Omnifactotum.Tests/ReadOnlyItemCollectionTests.cs
6,843
C#
using System; using System.Collections.Generic; namespace Digitalisert.Dataplattform { public class ResourceModel { public class Resource { public string Context { get; set ; } public string ResourceId { get; set; } public IEnumerable<string> Type { get; set; } public IEnumerable<string> SubType { get; set; } public IEnumerable<string> Title { get; set; } public IEnumerable<string> SubTitle { get; set; } public IEnumerable<string> Code { get; set; } public IEnumerable<string> Body { get; set; } public IEnumerable<string> Status { get; set; } public IEnumerable<string> Tags { get; set; } public IEnumerable<Property> Properties { get; set; } public IEnumerable<string> Source { get; set; } public string Target { get; set; } public DateTime? Modified { get; set; } } public class Property { public string Name { get; set; } public IEnumerable<string> Value { get; set; } public IEnumerable<string> Tags { get; set; } public IEnumerable<ResourceModel.Resource> Resources { get; set; } public IEnumerable<Property> Properties { get; set; } public DateTime? From { get; set; } public DateTime? Thru { get; set; } public IEnumerable<string> Source { get; set; } } } }
38.358974
78
0.572861
[ "MIT" ]
askildolsen/dataplattform
etl/ResourceModel.cs
1,496
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// This is the response object from the DeleteCustomerGateway operation. /// </summary> public partial class DeleteCustomerGatewayResponse : AmazonWebServiceResponse { } }
30.368421
102
0.710572
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/DeleteCustomerGatewayResponse.cs
1,154
C#
//Author Maxim Kuzmin//makc// using System.Collections.Generic; namespace Vlad2020.Host.Base.Parts.Ldap.Config { /// <summary> /// Хост. Основа. Часть "LDAP". Конфигурация. Настройки. /// </summary> public class HostBasePartLdapConfigSettings : IHostBasePartLdapConfigSettings { #region Properties /// <inheritdoc/> public string Domain { get; set; } /// <inheritdoc/> public IEnumerable<string> Hosts { get; set; } /// <inheritdoc/> public bool IsSecureSocketLayerEnabled { get; set; } /// <inheritdoc/> public int Port { get; set; } #endregion Properties } }
24
81
0.610119
[ "MIT" ]
balkar20/Vlad
net-core/Vlad2020.Host.Base/Parts/Ldap/Config/HostBasePartLdapConfigSettings.cs
710
C#
// <auto-generated/> using System.Reflection; [assembly: AssemblyTitleAttribute("Plainion.Wiki.Xaml")] [assembly: AssemblyProductAttribute("Plainion.Notes")] [assembly: AssemblyDescriptionAttribute("Plainion.Notes")] [assembly: AssemblyCopyrightAttribute("Copyright @ 2017")] [assembly: AssemblyVersionAttribute("1.0")] [assembly: AssemblyFileVersionAttribute("1.0")] namespace System { internal static class AssemblyVersionInformation { internal const System.String AssemblyTitle = "Plainion.Wiki.Xaml"; internal const System.String AssemblyProduct = "Plainion.Notes"; internal const System.String AssemblyDescription = "Plainion.Notes"; internal const System.String AssemblyCopyright = "Copyright @ 2017"; internal const System.String AssemblyVersion = "1.0"; internal const System.String AssemblyFileVersion = "1.0"; } }
45.05
77
0.732519
[ "BSD-3-Clause" ]
plainionist/Plainion.Notes
src/Plainion.Wiki.Xaml/Properties/AssemblyInfo.cs
903
C#
using System.IO; using System.Windows.Forms; using System.Xml.Linq; using Utils.Helpers.Reflection; namespace ResourceTypes.M3.XBin { public class CarTuningModificatorsItem { public int ID { get; set; } public int CarId { get; set; } public int ItemId { get; set; } public int MemberId { get; set; } public int Value { get; set; } public override string ToString() { return string.Format("CarID = {0} ItemId = {1}", CarId, ItemId); } } public class CarTuningModificatorsTable : BaseTable { private uint unk0; private CarTuningModificatorsItem[] modificators; public CarTuningModificatorsItem[] TuningModificators { get { return modificators; } set { modificators = value; } } public CarTuningModificatorsTable() { modificators = new CarTuningModificatorsItem[0]; } public void ReadFromFile(BinaryReader reader) { unk0 = reader.ReadUInt32(); uint count0 = reader.ReadUInt32(); uint count1 = reader.ReadUInt32(); modificators = new CarTuningModificatorsItem[count0]; for (int i = 0; i < count1; i++) { CarTuningModificatorsItem item = new CarTuningModificatorsItem(); item.ID = reader.ReadInt32(); item.CarId = reader.ReadInt32(); item.ItemId = reader.ReadInt32(); item.MemberId = reader.ReadInt32(); item.Value = reader.ReadInt32(); modificators[i] = item; } } public void WriteToFile(XBinWriter writer) { writer.Write(unk0); writer.Write(modificators.Length); writer.Write(modificators.Length); foreach(var modificator in modificators) { writer.Write(modificator.ID); writer.Write(modificator.CarId); writer.Write(modificator.ItemId); writer.Write(modificator.MemberId); writer.Write(modificator.Value); } } public void ReadFromXML(string file) { XElement Root = XElement.Load(file); CarTuningModificatorsTable TableInformation = ReflectionHelpers.ConvertToPropertyFromXML<CarTuningModificatorsTable>(Root); this.modificators = TableInformation.modificators; } public void WriteToXML(string file) { XElement RootElement = ReflectionHelpers.ConvertPropertyToXML(this); RootElement.Save(file, SaveOptions.None); } public TreeNode GetAsTreeNodes() { TreeNode Root = new TreeNode(); Root.Text = "CarTuningModificatorsTable"; foreach(var Item in TuningModificators) { TreeNode ChildNode = new TreeNode(); ChildNode.Tag = Item; ChildNode.Text = Item.ToString(); Root.Nodes.Add(ChildNode); } return Root; } public void SetFromTreeNodes(TreeNode Root) { TuningModificators = new CarTuningModificatorsItem[Root.Nodes.Count]; for (int i = 0; i < TuningModificators.Length; i++) { TreeNode ChildNode = Root.Nodes[i]; CarTuningModificatorsItem Entry = (CarTuningModificatorsItem)ChildNode.Tag; TuningModificators[i] = Entry; } } } }
31.434783
135
0.565145
[ "MIT" ]
Greavesy1899/Mafia2Toolk
Mafia2Libs/ResourceTypes/FileTypes/M3/XBin/Types/CarTuningModificators.cs
3,617
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OfficeDevPnP.Core { /// <summary> /// A class that returns strings that represent identifiers (IDs) for built-in content types. /// </summary> public static class BuiltInContentTypeId { /// <summary> /// Contains the content identifier (ID) for the DocumentSet content type. To get content type from a list, use BestMatchContentTypeId(). /// </summary> public const string DocumentSet = "0x0120D520"; } }
29.45
145
0.685908
[ "Apache-2.0" ]
krishnapokhare/PnP
OfficeDevPnP.Core/OfficeDevPnP.Core/BuiltInContentTypeId.cs
591
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using SharpTestsEx; using Xunit; namespace MediatR.Tests.Publishing { public class MoreThanOneHandler { private class ServiceLocator { private readonly Dictionary<Type, List<object>> Services = new Dictionary<Type, List<object>>(); public void Register(Type type, params object[] implementations) => Services.Add(type, implementations.ToList()); public List<object> Get(Type type) { return Services[type]; } } public class TasksList { public List<string> Tasks { get; } public TasksList() { Tasks = new List<string>(); } } public class TaskWasAdded: INotification { public string TaskName { get; } public TaskWasAdded(string taskName) { TaskName = taskName; } } public class TaskWasAddedHandler: INotificationHandler<TaskWasAdded> { private readonly TasksList _taskList; public TaskWasAddedHandler(TasksList tasksList) { _taskList = tasksList; } public Task Handle(TaskWasAdded @event, CancellationToken cancellationToken = default(CancellationToken)) { _taskList.Tasks.Add(@event.TaskName); return Task.CompletedTask; } } private readonly IMediator mediator; private readonly TasksList _taskList = new TasksList(); public MoreThanOneHandler() { var eventHandler = new TaskWasAddedHandler(_taskList); var serviceLocator = new ServiceLocator(); serviceLocator.Register(typeof(IEnumerable<INotificationHandler<TaskWasAdded>>), new object[] { new List<INotificationHandler<TaskWasAdded>> { eventHandler, eventHandler } }); mediator = new Mediator(type => serviceLocator.Get(type).FirstOrDefault()); } [Fact] public async void GivenTwoHandlersForOneEvent_WhenPublishMethodIsBeingCalled_ThenTwoHandlersAreBeingCalled() { //Given var @event = new TaskWasAdded("cleaning"); //When await mediator.Publish(@event); //Then _taskList.Tasks.Count.Should().Be.EqualTo(2); _taskList.Tasks.Should().Have.SameValuesAs("cleaning", "cleaning"); } } }
29.131868
117
0.584685
[ "MIT" ]
NicoJuicy/EventSourcing.NetCore
MediatR.Tests/Publishing/MoreThanOneHandler.cs
2,651
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("PalindromeIntegers")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("PalindromeIntegers")] [assembly: System.Reflection.AssemblyTitleAttribute("PalindromeIntegers")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.833333
80
0.655378
[ "MIT" ]
BorislavDimitrov/C-Sharp-Fundamentals
MethodsExcercises/PalindromeIntegers/obj/Debug/netcoreapp3.1/PalindromeIntegers.AssemblyInfo.cs
1,004
C#
 using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; using Aspectize.Core; [assembly:AspectizeDALAssemblyAttribute] namespace LeanKanban { public static partial class SchemaNames { public static partial class Entities { public const string WorkItem = "WorkItem"; public const string State = "State"; public const string Board = "Board"; public const string User = "User"; public const string CurrentUser = "CurrentUser"; public const string Activity = "Activity"; public const string Attachment = "Attachment"; } public static partial class Relations { public const string WorkItemState = "WorkItemState"; public const string BoardState = "BoardState"; public const string BoardUser = "BoardUser"; public const string IsUser = "IsUser"; public const string ActivityWorkItem = "ActivityWorkItem"; public const string ActivityUser = "ActivityUser"; public const string WorkItemAttachment = "WorkItemAttachment"; public const string AttachmentUser = "AttachmentUser"; } } [SchemaNamespace] public class DomainProvider : INamespace { public string Name { get { return GetType().Namespace; } } public static string DomainName { get { return new DomainProvider().Name; } } } [DataDefinition(MustPersist = false)] public enum EnumUserStatus { [Description("Valid")] Valid, [Description("Blocked")] Blocked, [Description("Pending")] Pending } [DataDefinition] public class WorkItem : Entity, IDataWrapper { public static partial class Fields { public const string Id = "Id"; public const string DateCreation = "DateCreation"; public const string Title = "Title"; public const string Description = "Description"; public const string DueDate = "DueDate"; public const string Order = "Order"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [Data(IsPrimaryKey=true)] public Guid Id { get { return getValue<Guid>("Id"); } set { setValue<Guid>("Id", value); } } [Data] public DateTime DateCreation { get { return getValue<DateTime>("DateCreation"); } set { setValue<DateTime>("DateCreation", value); } } [Data(DefaultValue = "")] public string Title { get { return getValue<string>("Title"); } set { setValue<string>("Title", value); } } [Data(DefaultValue = "")] public string Description { get { return getValue<string>("Description"); } set { setValue<string>("Description", value); } } [Data(IsNullable = true)] public DateTime? DueDate { get { return getValue<DateTime?>("DueDate"); } set { setValue<DateTime?>("DueDate", value); } } [Data] public int Order { get { return getValue<int>("Order"); } set { setValue<int>("Order", value); } } } [DataDefinition] public class State : Entity, IDataWrapper { public static partial class Fields { public const string Id = "Id"; public const string Title = "Title"; public const string Order = "Order"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [Data(IsPrimaryKey=true)] public Guid Id { get { return getValue<Guid>("Id"); } set { setValue<Guid>("Id", value); } } [Data(DefaultValue = "")] public string Title { get { return getValue<string>("Title"); } set { setValue<string>("Title", value); } } [Data] public int Order { get { return getValue<int>("Order"); } set { setValue<int>("Order", value); } } } [DataDefinition] public class Board : Entity, IDataWrapper { public static partial class Fields { public const string Id = "Id"; public const string Name = "Name"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [Data(IsPrimaryKey=true)] public Guid Id { get { return getValue<Guid>("Id"); } set { setValue<Guid>("Id", value); } } [Data(DefaultValue = "", RegexPattern = @"(?#Name can not be empty)\S+")] public string Name { get { return getValue<string>("Name"); } set { setValue<string>("Name", value); } } } [DataDefinition] public class User : Entity, IDataWrapper { public static partial class Fields { public const string Id = "Id"; public const string FirstName = "FirstName"; public const string LastName = "LastName"; public const string Email = "Email"; public const string Password = "Password"; public const string VerificationCode = "VerificationCode"; public const string DateLastLogin = "DateLastLogin"; public const string Status = "Status"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [Data(IsPrimaryKey=true)] public Guid Id { get { return getValue<Guid>("Id"); } set { setValue<Guid>("Id", value); } } [Data(DefaultValue = "")] public string FirstName { get { return getValue<string>("FirstName"); } set { setValue<string>("FirstName", value); } } [Data(DefaultValue = "")] public string LastName { get { return getValue<string>("LastName"); } set { setValue<string>("LastName", value); } } [Data(DefaultValue = "")] public string Email { get { return getValue<string>("Email"); } set { setValue<string>("Email", value); } } [Data(DefaultValue = "", IsNullable = true, ServerOnly = true)] [System.Xml.Serialization.XmlIgnore] public string Password { get { return getValue<string>("Password"); } set { setValue<string>("Password", value); } } [Data(IsNullable = true, ServerOnly = true)] [System.Xml.Serialization.XmlIgnore] public Guid? VerificationCode { get { return getValue<Guid?>("VerificationCode"); } set { setValue<Guid?>("VerificationCode", value); } } [Data] public DateTime DateLastLogin { get { return getValue<DateTime>("DateLastLogin"); } set { setValue<DateTime>("DateLastLogin", value); } } [Data(DefaultValue = EnumUserStatus.Pending)] public EnumUserStatus Status { get { return getValue<EnumUserStatus>("Status"); } set { setValue<EnumUserStatus>("Status", value); } } } [DataDefinition(MustPersist = false)] public class CurrentUser : Entity, IDataWrapper { public static partial class Fields { public const string Id = "Id"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [Data(IsPrimaryKey=true)] public Guid Id { get { return getValue<Guid>("Id"); } set { setValue<Guid>("Id", value); } } } [DataDefinition] public class Activity : Entity, IDataWrapper { public static partial class Fields { public const string Id = "Id"; public const string DateCreation = "DateCreation"; public const string DateModification = "DateModification"; public const string Comment = "Comment"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [Data(IsPrimaryKey=true)] public Guid Id { get { return getValue<Guid>("Id"); } set { setValue<Guid>("Id", value); } } [Data] public DateTime DateCreation { get { return getValue<DateTime>("DateCreation"); } set { setValue<DateTime>("DateCreation", value); } } [Data] public DateTime DateModification { get { return getValue<DateTime>("DateModification"); } set { setValue<DateTime>("DateModification", value); } } [Data(DefaultValue = "")] public string Comment { get { return getValue<string>("Comment"); } set { setValue<string>("Comment", value); } } } [DataDefinition] public class Attachment : Entity, IDataWrapper { public static partial class Fields { public const string Id = "Id"; public const string FileName = "FileName"; public const string DateUploaded = "DateUploaded"; public const string FileLength = "FileLength"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [Data(IsPrimaryKey=true)] public Guid Id { get { return getValue<Guid>("Id"); } set { setValue<Guid>("Id", value); } } [Data(DefaultValue = "")] public string FileName { get { return getValue<string>("FileName"); } set { setValue<string>("FileName", value); } } [Data] public DateTime DateUploaded { get { return getValue<DateTime>("DateUploaded"); } set { setValue<DateTime>("DateUploaded", value); } } [Data] public int FileLength { get { return getValue<int>("FileLength"); } set { setValue<int>("FileLength", value); } } } [DataDefinition] [RelationPersistenceMode(SeparateTable = false)] public class WorkItemState : DataWrapper, IDataWrapper, IRelation { void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(State), Role = typeof(State), Multiplicity = Multiplicity.One, FkNames = "StateId")] public IEntity State; [RelationEnd(Type = typeof(WorkItem), Role = typeof(WorkItem), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity WorkItem; } [DataDefinition] [RelationPersistenceMode(SeparateTable = false)] public class BoardState : DataWrapper, IDataWrapper, IRelation { void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(Board), Role = typeof(Board), Multiplicity = Multiplicity.One, FkNames = "BoardId")] public IEntity Board; [RelationEnd(Type = typeof(State), Role = typeof(State), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity State; } [DataDefinition] public class BoardUser : DataWrapper, IDataWrapper, IRelation { public static partial class Fields { public const string IsOwner = "IsOwner"; } void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(Board), Role = typeof(Board), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity Board; [RelationEnd(Type = typeof(User), Role = typeof(User), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity User; [Data(DefaultValue = true)] public bool IsOwner { get { return getValue<bool>("IsOwner"); } set { setValue<bool>("IsOwner", value); } } } [DataDefinition(MustPersist = false)] public class IsUser : DataWrapper, IDataWrapper, IRelation { void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(User), Role = typeof(User), Multiplicity = Multiplicity.One)] public IEntity User; [RelationEnd(Type = typeof(CurrentUser), Role = typeof(CurrentUser), Multiplicity = Multiplicity.ZeroOrOne)] public IEntity CurrentUser; } [DataDefinition] [RelationPersistenceMode(SeparateTable = false)] public class ActivityWorkItem : DataWrapper, IDataWrapper, IRelation { void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(Activity), Role = typeof(Activity), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity Activity; [RelationEnd(Type = typeof(WorkItem), Role = typeof(WorkItem), Multiplicity = Multiplicity.One, FkNames = "WorkItemId")] public IEntity WorkItem; } [DataDefinition] [RelationPersistenceMode(SeparateTable = false)] public class ActivityUser : DataWrapper, IDataWrapper, IRelation { void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(User), Role = typeof(User), Multiplicity = Multiplicity.One, FkNames = "UserId")] public IEntity User; [RelationEnd(Type = typeof(Activity), Role = typeof(Activity), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity Activity; } [DataDefinition] [RelationPersistenceMode(SeparateTable = false)] public class WorkItemAttachment : DataWrapper, IDataWrapper, IRelation { void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(Attachment), Role = typeof(Attachment), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity Attachment; [RelationEnd(Type = typeof(WorkItem), Role = typeof(WorkItem), Multiplicity = Multiplicity.One, FkNames = "WorkItemId")] public IEntity WorkItem; } [DataDefinition] [RelationPersistenceMode(SeparateTable = false)] public class AttachmentUser : DataWrapper, IDataWrapper, IRelation { void IDataWrapper.InitData(DataRow data, string namePrefix) { base.InitData(data, null); } [RelationEnd(Type = typeof(User), Role = typeof(User), Multiplicity = Multiplicity.One, FkNames = "UserId")] public IEntity User; [RelationEnd(Type = typeof(Attachment), Role = typeof(Attachment), Multiplicity = Multiplicity.ZeroOrMany)] public IEntity Attachment; } }
25.196629
123
0.661538
[ "MIT" ]
Aspectize/Samples
LeanKanban/Schema/LeanKanban.Entities.cs
13,457
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("WindowsForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP")] [assembly: AssemblyProduct("WindowsForms")] [assembly: AssemblyCopyright("Copyright © HP 2021")] [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("6a2554a8-0132-4971-8d1c-d6e3ece3df27")] // 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.72973
84
0.748567
[ "Unlicense" ]
drualcman/Pagination
WindowsForms/Properties/AssemblyInfo.cs
1,399
C#
namespace GossbitBot_Chatroom { partial class StartUpForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(StartUpForm)); this.UserNameBox = new System.Windows.Forms.RichTextBox(); this.ChatButton = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // UserNameBox // this.UserNameBox.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.UserNameBox.Location = new System.Drawing.Point(23, 407); this.UserNameBox.Name = "UserNameBox"; this.UserNameBox.Size = new System.Drawing.Size(316, 30); this.UserNameBox.TabIndex = 0; this.UserNameBox.Text = ""; this.UserNameBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.UserNameBox_KeyDown); // // ChatButton // this.ChatButton.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ChatButton.Location = new System.Drawing.Point(345, 381); this.ChatButton.Name = "ChatButton"; this.ChatButton.Size = new System.Drawing.Size(139, 56); this.ChatButton.TabIndex = 1; this.ChatButton.Text = "Chat Now!"; this.ChatButton.UseVisualStyleBackColor = true; this.ChatButton.Click += new System.EventHandler(this.ChatButton_Click); // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(107, 12); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(309, 102); this.pictureBox1.TabIndex = 3; this.pictureBox1.TabStop = false; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(113, 117); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(136, 18); this.label2.TabIndex = 4; this.label2.Text = "There are currently"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(246, 117); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 18); this.label3.TabIndex = 5; this.label3.Text = "000"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(276, 117); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(106, 18); this.label4.TabIndex = 6; this.label4.Text = "people online!"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(20, 381); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(319, 18); this.label1.TabIndex = 7; this.label1.Text = "Please type your name then press Chat Now!"; // // StartUpForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Window; this.ClientSize = new System.Drawing.Size(513, 449); this.Controls.Add(this.label1); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.ChatButton); this.Controls.Add(this.UserNameBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "StartUpForm"; this.Text = "Chatroom"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.RichTextBox UserNameBox; private System.Windows.Forms.Button ChatButton; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label1; } }
46.785235
159
0.591881
[ "MIT" ]
TomLBarden/Project24
GossbitBot Chatroom/GossbitBot Chatroom/StartUpForm.Designer.cs
6,973
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.WebSites.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for AzureStorageState. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum AzureStorageState { [EnumMember(Value = "Ok")] Ok, [EnumMember(Value = "InvalidCredentials")] InvalidCredentials, [EnumMember(Value = "InvalidShare")] InvalidShare } internal static class AzureStorageStateEnumExtension { internal static string ToSerializedValue(this AzureStorageState? value) { return value == null ? null : ((AzureStorageState)value).ToSerializedValue(); } internal static string ToSerializedValue(this AzureStorageState value) { switch( value ) { case AzureStorageState.Ok: return "Ok"; case AzureStorageState.InvalidCredentials: return "InvalidCredentials"; case AzureStorageState.InvalidShare: return "InvalidShare"; } return null; } internal static AzureStorageState? ParseAzureStorageState(this string value) { switch( value ) { case "Ok": return AzureStorageState.Ok; case "InvalidCredentials": return AzureStorageState.InvalidCredentials; case "InvalidShare": return AzureStorageState.InvalidShare; } return null; } } }
31.328358
89
0.600286
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/websites/Microsoft.Azure.Management.WebSites/src/Generated/Models/AzureStorageState.cs
2,099
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 iam-2010-05-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.IdentityManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.IdentityManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListGroupPolicies operation /// </summary> public class ListGroupPoliciesResponseUnmarshaller : XmlResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { ListGroupPoliciesResponse response = new ListGroupPoliciesResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("ListGroupPoliciesResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, ListGroupPoliciesResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("IsTruncated", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; response.IsTruncated = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Marker", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Marker = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("PolicyNames/member", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); response.PolicyNames.Add(item); continue; } } } return; } public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchEntity")) { return new NoSuchEntityException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceFailure")) { return new ServiceFailureException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonIdentityManagementServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static ListGroupPoliciesResponseUnmarshaller _instance = new ListGroupPoliciesResponseUnmarshaller(); internal static ListGroupPoliciesResponseUnmarshaller GetInstance() { return _instance; } public static ListGroupPoliciesResponseUnmarshaller Instance { get { return _instance; } } } }
39.43609
180
0.599619
[ "Apache-2.0" ]
samritchie/aws-sdk-net
AWSSDK_DotNet35/Amazon.IdentityManagement/Model/Internal/MarshallTransformations/ListGroupPoliciesResponseUnmarshaller.cs
5,245
C#
using System; using System.Collections.Generic; using System.Text; using UnoContoso.Enums; using UnoContoso.Models; namespace UnoContoso.EventArgs { public class CustomerEventArgs { public EntityChanges Changes { get; set; } public Customer Customer { get; set; } public Guid CustomerId { get; set; } } }
19.166667
50
0.689855
[ "Apache-2.0" ]
MartinZikmund/Uno.Samples
UI/UnoContoso/UnoContoso.Shared/EventArgs/CustomerEventArgs.cs
347
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Natasha.Domain.Template { /// <summary> /// 引用模板 /// </summary> internal class UsingRecoder { internal readonly HashSet<string> _usings; internal readonly HashSet<Type> _usingTypes; public UsingRecoder() { _usings = new HashSet<string>(); _usingTypes = new HashSet<Type>(); } public UsingRecoder Using(string @using) { if (@using != default) { if (!_usings.Contains(@using)) { _usings.Add(@using); } } return this; } /// <summary> /// 从程序集里获取引用 /// </summary> /// <param name="assembly">程序集</param> /// <returns></returns> public UsingRecoder Using(Assembly assembly) { if (assembly != default) { try { Using(assembly.GetTypes()); } catch (Exception ex) { } } return this; } /// <summary> /// 设置命名空间 /// </summary> /// <param name="namespaces">命名空间</param> /// <returns></returns> public UsingRecoder Using(params Assembly[] namespaces) { for (int i = 0; i < namespaces.Length; i++) { Using(namespaces[i]); } return this; } public UsingRecoder Using(IEnumerable<Assembly> namespaces) { foreach (var item in namespaces) { Using(item); } return this; } public UsingRecoder Using(IEnumerable<Type> namespaces) { foreach (var item in namespaces) { Using(item); } return this; } public UsingRecoder Using(Type type) { if (type != null && !_usingTypes.Contains(type)) { _usingTypes.Add(type); return Using(type.Namespace); } return this; } } }
17.423358
67
0.43318
[ "MIT" ]
dotnetcore/Natasha
src/Natasha.Domain/Utils/UsingRecoder.cs
2,441
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Charlotte.Tools; using Charlotte.Common; using Charlotte.Common.Options; using Charlotte.Games.Enemies; using Charlotte.Games.Walls; using DxLibDLL; namespace Charlotte.Games { public class Game : IDisposable { public IScenario Scenario; public Status Status; // <---- prm public static Game I = null; public Game() { I = this; } public void Dispose() { this.WallScreen.Dispose(); this.WallScreen = null; I = null; } public Player Player = new Player(); public int Frame = 0; public void Perform() { this.Player.X = DDConsts.Screen_W / 4; this.Player.Y = DDConsts.Screen_H / 2; this.Player.BornScene.Fire(); DDCurtain.SetCurtain(10); for (; ; this.Frame++) { // プレイヤー行動 { bool bornOrDead = this.Player.BornScene.IsFlaming() || this.Player.DeadScene.IsFlaming(); bool dead = this.Player.DeadScene.IsFlaming(); double xa = 0.0; double ya = 0.0; if (!dead && 1 <= DDInput.DIR_4.GetInput()) // 左移動 { xa = -1.0; } if (!dead && 1 <= DDInput.DIR_6.GetInput()) // 右移動 { xa = 1.0; } if (!dead && 1 <= DDInput.DIR_8.GetInput()) // 上移動 { ya = -1.0; } if (!dead && 1 <= DDInput.DIR_2.GetInput()) // 下移動 { ya = 1.0; } double speed; if (1 <= DDInput.A.GetInput()) // 低速ボタン押下中 { speed = (double)this.Player.SpeedLevel; } else { speed = (double)(this.Player.SpeedLevel * 2); } this.Player.X += xa * speed; this.Player.Y += ya * speed; DDUtils.ToRange(ref this.Player.X, 0.0, DDConsts.Screen_W); DDUtils.ToRange(ref this.Player.Y, 0.0, DDConsts.Screen_H); if (!bornOrDead && 1 <= DDInput.B.GetInput()) // 攻撃ボタン押下中 { this.Player.Shoot(); } if (DDInput.L.GetInput() == 1) { this.Player.SpeedLevel--; } if (DDInput.R.GetInput() == 1) { this.Player.SpeedLevel++; } DDUtils.ToRange(ref this.Player.SpeedLevel, Player.SPEED_LEVEL_MIN, Player.SPEED_LEVEL_MAX); } { DDScene scene = this.Player.BornScene.GetScene(); if (scene.Numer != -1) { if (scene.Remaining == 0) { this.Player.MutekiScene.FireDelay(); } } } { DDScene scene = this.Player.DeadScene.GetScene(); if (scene.Numer != -1) { if (scene.Remaining == 0) { if (this.Status.RemainingLiveCount <= 0) break; this.Status.RemainingLiveCount--; this.Player.BornScene.FireDelay(); } } } { DDScene scene = this.Player.MutekiScene.GetScene(); if (scene.Numer != -1) { // noop } } if (this.Scenario.EachFrame() == false) break; this.EnemyEachFrame(); this.WeaponEachFrame(); DDCrashView cv = DDKey.GetInput(DX.KEY_INPUT_LSHIFT) == 0 ? null : new DDCrashView(); // Crash { DDCrash playerCrash = DDCrashUtils.Point(new D2Point(this.Player.X, this.Player.Y)); foreach (WeaponBox weapon in this.Weapons.Iterate()) weapon.Crash = weapon.Value.GetCrash(); foreach (EnemyBox enemy in this.Enemies.Iterate()) { DDCrash enemyCrash = enemy.Value.GetCrash(); if (cv != null) cv.Draw(enemyCrash); foreach (WeaponBox weapon in this.Weapons.Iterate()) { if (enemyCrash.IsCrashed(weapon.Crash)) { if (enemy.Value.Crashed(weapon.Value) == false) // ? 消滅 enemy.Dead = true; if (weapon.Value.Crashed(enemy.Value) == false) // ? 消滅 weapon.Dead = true; } } this.Weapons.RemoveAll(weapon => weapon.Dead); if (this.Player.BornScene.IsFlaming() == false && this.Player.DeadScene.IsFlaming() == false && this.Player.MutekiScene.IsFlaming() == false && enemyCrash.IsCrashed(playerCrash)) { foreach (DDScene scene in DDSceneUtils.Create(30)) // プレイヤ死亡効果 { this.DrawWall(); this.Player.Draw(); this.DrawEnemies(); DDDraw.SetAlpha(0.3); DDDraw.SetBright(1.0, 0.0, 0.0); DDDraw.DrawRect(DDGround.GeneralResource.WhiteBox, 0, 0, DDConsts.Screen_W, DDConsts.Screen_H); DDDraw.Reset(); { int ix = DoubleTools.ToInt(this.Player.X); int iy = DoubleTools.ToInt(this.Player.Y); DDDraw.SetBright(1.0, 1.0, 0.0); DDDraw.SetAlpha(scene.Rate); DDDraw.DrawRect_LTRB(DDGround.GeneralResource.WhiteBox, ix - 1, 0, ix + 1, DDConsts.Screen_H); DDDraw.SetAlpha(scene.RemainingRate); DDDraw.DrawRect_LTRB(DDGround.GeneralResource.WhiteBox, 0, iy - 1, DDConsts.Screen_W, iy + 1); DDDraw.Reset(); } DDEngine.EachFrame(); } this.Player.DeadScene.Fire(); } } this.Enemies.RemoveAll(enemy => enemy.Dead); } // ここから描画 this.DrawWall(); this.Player.Draw(); this.DrawEnemies(); this.DrawWeapons(); if (cv != null) { cv.DrawToScreen(0.8); cv.Dispose(); cv = null; } DDPrint.SetPrint(); DDPrint.Print(DDEngine.FrameProcessingMillis_Worst + " " + this.Enemies.Count + " SPEED=" + this.Player.SpeedLevel); DDEngine.EachFrame(); } } private IWall LastWall = null; private IWall Wall = new WallDark(); private int WallChangeNumer = -1; private int WallChangeDenom = -1; private DDSubScreen WallScreen = new DDSubScreen(DDConsts.Screen_W, DDConsts.Screen_H); public void SetWall(IWall wall, int denom = 180) { this.LastWall = this.Wall; this.Wall = wall; this.WallChangeNumer = 0; this.WallChangeDenom = denom; } private void DrawWall() { if (this.LastWall == null) { this.Wall.Draw(); } else { double a = this.WallChangeNumer * 1.0 / this.WallChangeDenom; this.LastWall.Draw(); using (this.WallScreen.Section()) { this.Wall.Draw(); } DDDraw.SetAlpha(a); DDDraw.DrawSimple(this.WallScreen.ToPicture(), 0, 0); DDDraw.Reset(); this.WallChangeNumer++; if (this.WallChangeDenom <= this.WallChangeNumer) { this.LastWall = null; this.WallChangeNumer = -1; this.WallChangeDenom = -1; } } } private class EnemyBox { public IEnemy Value; public bool Dead; } private DDList<EnemyBox> Enemies = new DDList<EnemyBox>(); public void AddEnemy(IEnemy enemy) { this.Enemies.Add(new EnemyBox() { Value = enemy, }); } private void EnemyEachFrame() { foreach (EnemyBox enemy in this.Enemies.Iterate()) { if (enemy.Value.EachFrame() == false) // ? 消滅 { enemy.Dead = true; } } this.Enemies.RemoveAll(enemy => enemy.Dead); } private void DrawEnemies() { foreach (EnemyBox enemy in this.Enemies.Iterate()) { enemy.Value.Draw(); } } private class WeaponBox { public IWeapon Value; public DDCrash Crash; public bool Dead; } private DDList<WeaponBox> Weapons = new DDList<WeaponBox>(); public void AddWeapon(IWeapon weapon) { this.Weapons.Add(new WeaponBox() { Value = weapon, }); } private void WeaponEachFrame() { foreach (WeaponBox weapon in this.Weapons.Iterate()) { if (weapon.Value.EachFrame() == false) // ? 消滅 { weapon.Dead = true; } } this.Weapons.RemoveAll(weapon => weapon.Dead); } private void DrawWeapons() { foreach (WeaponBox weapon in this.Weapons.Iterate()) { weapon.Value.Draw(); } } } }
21.336134
120
0.595116
[ "MIT" ]
stackprobe/G4YokoShoot
G4YokoShoot/G4YokoShoot/Games/Game.cs
7,733
C#
using Entia.Unity.Generation; namespace Entia.Resources.Generated { [global::Entia.Unity.Generation.GeneratedAttribute(Type = typeof(global::Entia.Resources.Debug), Link = "", Path = new string[] { "Entia", "Resources", "Debug" })][global::UnityEngine.AddComponentMenu("Entia/Resources/Entia.Resources.Debug")] public sealed partial class Debug : global::Entia.Unity.ResourceReference<global::Entia.Resources.Debug> { public ref global::System.String Name => ref base.Get((ref global::Entia.Resources.Debug data) => ref data.Name, ref this._Name); [global::UnityEngine.SerializeField, global::UnityEngine.Serialization.FormerlySerializedAsAttribute(nameof(Name))] global::System.String _Name; public override global::Entia.Resources.Debug Raw { get => new global::Entia.Resources.Debug { Name = this._Name }; set { this._Name = value.Name; } } } }
35.68
243
0.729821
[ "MIT" ]
Magicolo/Entia.Unity.Sample.Asteroimania
Assets/Generated/Entia/Resources/Debug.cs
892
C#
using Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas.Effects; using System; using Windows.Storage.Streams; using Windows.UI.Composition; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; namespace PianoSheetViewer { public class LoadedImageBrush : XamlCompositionBrushBase { private bool IsImageLoading = false; private LoadedImageSurface _surface; CompositionEffectBrush combinedBrush; ContrastEffect contrastEffect; ExposureEffect exposureEffect; TemperatureAndTintEffect temperatureAndTintEffect; GaussianBlurEffect graphicsEffect; SaturationEffect saturationEffect; public ICanvasImage Image { get { contrastEffect.Contrast = (float)ContrastAmount; exposureEffect.Exposure = (float)ExposureAmount; temperatureAndTintEffect.Tint = (float)TintAmount; temperatureAndTintEffect.Temperature = (float)TemperatureAmount; saturationEffect.Saturation = (float)SaturationAmount; graphicsEffect.BlurAmount = (float)BlurAmount; return graphicsEffect; } } public void SetSource(ICanvasImage source) { saturationEffect.Source = source; } public static readonly DependencyProperty BlurAmountProperty = DependencyProperty.Register("BlurAmount", typeof(double), typeof(LoadedImageBrush), new PropertyMetadata(0.0, new PropertyChangedCallback(OnBlurAmountChanged))); public double BlurAmount { get { return (double)GetValue(BlurAmountProperty); } set { SetValue(BlurAmountProperty, value); } } private static void OnBlurAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var brush = (LoadedImageBrush)d; brush.CompositionBrush?.Properties.InsertScalar("Blur.BlurAmount", (float)(double)e.NewValue); } public static readonly DependencyProperty ContrastAmountProperty = DependencyProperty.Register("ContrastAmount", typeof(double), typeof(LoadedImageBrush), new PropertyMetadata(0.0, new PropertyChangedCallback(OnContrastAmountChanged))); public double ContrastAmount { get { return (double)GetValue(ContrastAmountProperty); } set { SetValue(ContrastAmountProperty, value); } } private static void OnContrastAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var brush = (LoadedImageBrush)d; brush.CompositionBrush?.Properties.InsertScalar("ContrastEffect.Contrast", (float)(double)e.NewValue); } public static readonly DependencyProperty SaturationAmountProperty = DependencyProperty.Register("SaturationAmount", typeof(double), typeof(LoadedImageBrush), new PropertyMetadata(1.0, new PropertyChangedCallback(OnSaturationAmountChanged))); public double SaturationAmount { get { return (double)GetValue(SaturationAmountProperty); } set { SetValue(SaturationAmountProperty, value); } } private static void OnSaturationAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var brush = (LoadedImageBrush)d; brush.CompositionBrush?.Properties.InsertScalar("SaturationEffect.Saturation", (float)(double)e.NewValue); } public static readonly DependencyProperty ExposureAmountProperty = DependencyProperty.Register("ExposureAmount", typeof(double), typeof(LoadedImageBrush), new PropertyMetadata(0.0, new PropertyChangedCallback(OnExposureAmountChanged))); public double ExposureAmount { get { return (double)GetValue(ExposureAmountProperty); } set { SetValue(ExposureAmountProperty, value); } } private static void OnExposureAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var brush = (LoadedImageBrush)d; brush.CompositionBrush?.Properties.InsertScalar("ExposureEffect.Exposure", (float)(double)e.NewValue); } public static readonly DependencyProperty TintAmountProperty = DependencyProperty.Register("TintAmount", typeof(double), typeof(LoadedImageBrush), new PropertyMetadata(0.0, new PropertyChangedCallback(OnTintAmountChanged))); public double TintAmount { get { return (double)GetValue(TintAmountProperty); } set { SetValue(TintAmountProperty, value); } } private static void OnTintAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var brush = (LoadedImageBrush)d; brush.CompositionBrush?.Properties.InsertScalar("TemperatureAndTintEffect.Tint", (float)(double)e.NewValue); } public static readonly DependencyProperty TemperatureAmountProperty = DependencyProperty.Register("TemperatureAmount", typeof(double), typeof(LoadedImageBrush), new PropertyMetadata(0.0, new PropertyChangedCallback(OnTemperatureAmountChanged))); public double TemperatureAmount { get { return (double)GetValue(TemperatureAmountProperty); } set { SetValue(TemperatureAmountProperty, value); } } private static void OnTemperatureAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var brush = (LoadedImageBrush)d; brush.CompositionBrush?.Properties.InsertScalar("TemperatureAndTintEffect.Temperature", (float)(double)e.NewValue); } public LoadedImageBrush() { } public void LoadImageFromPath(string path) { var compositor = Window.Current.Compositor; _surface = LoadedImageSurface.StartLoadFromUri(new Uri(path)); _surface.LoadCompleted += Load_Completed; } public void LoadImageFromStream(IRandomAccessStream stream) { if (stream != null && IsImageLoading == false) { var compositor = Window.Current.Compositor; IsImageLoading = true; _surface = LoadedImageSurface.StartLoadFromStream(stream); _surface.LoadCompleted += Load_Completed; } } private void Load_Completed(LoadedImageSurface sender, LoadedImageSourceLoadCompletedEventArgs e) { IsImageLoading = false; if (e.Status == LoadedImageSourceLoadStatus.Success) { var compositor = Window.Current.Compositor; var brush = compositor.CreateSurfaceBrush(_surface); brush.Stretch = CompositionStretch.UniformToFill; saturationEffect = new SaturationEffect() { Name = "SaturationEffect", Saturation = (float)SaturationAmount, Source = new CompositionEffectSourceParameter("image") }; contrastEffect = new ContrastEffect() { Name = "ContrastEffect", Contrast = (float)ContrastAmount, Source = saturationEffect }; exposureEffect = new ExposureEffect() { Name = "ExposureEffect", Source = contrastEffect, Exposure = (float)ExposureAmount, }; temperatureAndTintEffect = new TemperatureAndTintEffect() { Name = "TemperatureAndTintEffect", Source = exposureEffect, Temperature = (float)TemperatureAmount, Tint = (float)TintAmount }; graphicsEffect = new GaussianBlurEffect() { Name = "Blur", Source = temperatureAndTintEffect, BlurAmount = (float)BlurAmount, BorderMode = EffectBorderMode.Hard, }; var graphicsEffectFactory = compositor.CreateEffectFactory(graphicsEffect, new[] { "SaturationEffect.Saturation", "ExposureEffect.Exposure", "Blur.BlurAmount", "TemperatureAndTintEffect.Temperature", "TemperatureAndTintEffect.Tint", "ContrastEffect.Contrast" }); combinedBrush = graphicsEffectFactory.CreateBrush(); combinedBrush.SetSourceParameter("image", brush); CompositionBrush = combinedBrush; } else { LoadImageFromPath("ms-appx:///Assets/StoreLogo.png"); } } protected override void OnDisconnected() { if (_surface != null) { _surface.Dispose(); _surface = null; } if (CompositionBrush != null) { CompositionBrush.Dispose(); CompositionBrush = null; } } } }
41.424107
253
0.622373
[ "MIT" ]
der3318/musicsheet-viewer
PianoSheetViewer/LoadedImageBrush.cs
9,281
C#
//----------------------------------------------------------------------- // <copyright file="Utils.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Akka.Actor; using Hocon; using Akka.Streams.Implementation; using Akka.TestKit; using Akka.Util.Internal; namespace Akka.Streams.TestKit.Tests { public static class Utils { public static Config UnboundedMailboxConfig { get; } = ConfigurationFactory.ParseString(@"akka.actor.default-mailbox.mailbox-type = ""Akka.Dispatch.UnboundedMailbox, Akka"""); public static void AssertAllStagesStopped(this AkkaSpec spec, Action block, IMaterializer materializer) { AssertAllStagesStopped(spec, () => { block(); return NotUsed.Instance; }, materializer); } public static T AssertAllStagesStopped<T>(this AkkaSpec spec, Func<T> block, IMaterializer materializer) { var impl = materializer as ActorMaterializerImpl; if (impl == null) return block(); var probe = spec.CreateTestProbe(impl.System); probe.Send(impl.Supervisor, StreamSupervisor.StopChildren.Instance); probe.ExpectMsg<StreamSupervisor.StoppedChildren>(); var result = block(); probe.Within(TimeSpan.FromSeconds(5), () => { IImmutableSet<IActorRef> children = ImmutableHashSet<IActorRef>.Empty; try { probe.AwaitAssert(() => { impl.Supervisor.Tell(StreamSupervisor.GetChildren.Instance, probe.Ref); children = probe.ExpectMsg<StreamSupervisor.Children>().Refs; if (children.Count != 0) throw new Exception($"expected no StreamSupervisor children, but got {children.Aggregate("", (s, @ref) => s + @ref + ", ")}"); }); } catch { children.ForEach(c=>c.Tell(StreamSupervisor.PrintDebugDump.Instance)); throw; } }); return result; } public static void AssertDispatcher(IActorRef @ref, string dispatcher) { var r = @ref as ActorRefWithCell; if (r == null) throw new Exception($"Unable to determine dispatcher of {@ref}"); if (r.Underlying.Props.Dispatcher != dispatcher) throw new Exception($"Expected {@ref} to use dispatcher [{dispatcher}], yet used : [{r.Underlying.Props.Dispatcher}]"); } public static T AwaitResult<T>(this Task<T> task, TimeSpan? timeout = null) { task.Wait(timeout??TimeSpan.FromSeconds(3)).ShouldBeTrue(); return task.Result; } } }
37.651163
154
0.547251
[ "Apache-2.0" ]
hueifeng/akka.net
src/core/Akka.Streams.TestKit.Tests/Utils.cs
3,240
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.MigrationHubConfig")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Migration Hub Config. AWS Migration Hub Config Service allows you to get and set the Migration Hub home region for use with AWS Migration Hub and Application Discovery Service")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Migration Hub Config. AWS Migration Hub Config Service allows you to get and set the Migration Hub home region for use with AWS Migration Hub and Application Discovery Service")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Migration Hub Config. AWS Migration Hub Config Service allows you to get and set the Migration Hub home region for use with AWS Migration Hub and Application Discovery Service")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Migration Hub Config. AWS Migration Hub Config Service allows you to get and set the Migration Hub home region for use with AWS Migration Hub and Application Discovery Service")] #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 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.7.0.60")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
51.980392
271
0.774425
[ "Apache-2.0" ]
ebattalio/aws-sdk-net
sdk/src/Services/MigrationHubConfig/Properties/AssemblyInfo.cs
2,651
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using Microsoft.Health.Fhir.Core; using Microsoft.Health.Fhir.Core.Models; using Xunit; namespace Microsoft.Health.Fhir.R5.Core.UnitTests.Operations.Versions { /// <summary> /// Provides R5 specific tests. /// </summary> public class VersionSpecificTests { private readonly IModelInfoProvider _provider; public VersionSpecificTests() { _provider = new VersionSpecificModelInfoProvider(); } [Fact] public void GivenR5Server_WhenSupportedVersionIsRequested_ThenCorrectVersionShouldBeReturned() { var version = _provider.SupportedVersion.ToString(); Assert.Equal("4.4.0", version); } } }
32.515152
102
0.550792
[ "MIT" ]
10thmagnitude/fhir-server
src/Microsoft.Health.Fhir.R5.Core.UnitTests/Operations/Versions/VersionSpecificTests.cs
1,075
C#
using EZServiceLocation; using Webjet.Movies.Domain.Contracts.Repository; using Webjet.Movies.Domain.Contracts.Services; using Webjet.Movies.Repository.APIs; using Webjet.Movies.Services; namespace Webjet.Movies.IoC.Map { public class MovieMap : ServiceMap { public override void Load() { For<IMovieRepository>().Use<MovieRepository>(); For<IMovieService>().Use<MovieService>(new ConstructorDependency(typeof(IMovieRepository))); } } }
29.235294
104
0.708249
[ "MIT" ]
AdGalesso/Webjet
Webjet.Movies.IoC/Map/MovieMap.cs
499
C#
using Microsoft.Extensions.Logging; using RapidCore.DependencyInjection; using RapidCore.Migration; namespace RapidCore.FunctionalTests.Migration.Implementation { public class FuncMigrationContext : IMigrationContext { public ILogger Logger { get; set; } public IRapidContainerAdapter Container { get; set; } public IMigrationEnvironment Environment { get; set; } public IMigrationStorage Storage { get; set; } public FuncMigrationDatabase Database { get; set; } } }
34.666667
62
0.730769
[ "MIT" ]
rapidcore/rapidcore
src/core/test-functional/Migration/Implementation/FuncMigrationContext.cs
522
C#
using System; namespace KinaUnaXamarin.Models.KinaUna { public class MobileNotification { public int NotificationId { get; set; } public string UserId { get; set; } public string ItemId { get; set; } public int ItemType { get; set; } public string Title { get; set; } public string Message { get; set; } public string IconLink { get; set; } public DateTime Time { get; set; } public string Language { get; set; } public bool Read { get; set; } } }
26.285714
47
0.57971
[ "MIT" ]
KinaUna/KinaUnaXamarin
KinaUnaXamarin/KinaUnaXamarin/Models/KinaUna/MobileNotification.cs
554
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201 { using static Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Extensions; /// <summary>A paged list of addons</summary> public partial class AddonList { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject into a new instance of <see cref="AddonList" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject instance to deserialize from.</param> internal AddonList(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } {_value = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonArray>("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonArray, out var __v) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IAddon[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IAddon) (Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.Addon.FromJson(__u) )) ))() : null : Value;} {_nextLink = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonString>("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} AfterFromJson(json); } /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IAddonList. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IAddonList. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IAddonList FromJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json ? new AddonList(json) : null; } /// <summary> /// Serializes this instance of <see cref="AddonList" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="AddonList" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SerializationMode.IncludeReadOnly)) { if (null != this._value) { var __w = new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.XNodeArray(); foreach( var __x in this._value ) { AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); } container.Add("value",__w); } } if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SerializationMode.IncludeReadOnly)) { AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); } AfterToJson(ref container); return container; } } }
67.147541
607
0.669922
[ "MIT" ]
Agazoth/azure-powershell
src/VMware/generated/api/Models/Api20211201/AddonList.json.cs
8,071
C#
/* * Selling Partner API for Fulfillment Inbound * * The Selling Partner API for Fulfillment Inbound lets you create applications that create and update inbound shipments of inventory to Amazon's fulfillment network. * * OpenAPI spec version: v0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ namespace AmazonSpApiSDK.Models.FulfillmentInbound { /// <summary> /// Indicates the unit of weight. /// </summary> /// <value>Indicates the unit of weight.</value> public enum UnitOfWeight { /// <summary> /// Enum Pounds for value: pounds /// </summary> Pounds, /// <summary> /// Enum Kilograms for value: kilograms /// </summary> Kilograms } }
22.085714
166
0.630013
[ "MIT" ]
KristopherMackowiak/Amazon-SP-API-CSharp
Source/AmazonSpApiSDK/Models/FulfillmentInbound/UnitOfWeight.cs
773
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Response to the GroupCollaborateBridgeGetInstancePagedSortedListRequest. /// Contains a table with column headings: "Service User Id", "Name", "Phone Number", "Is Phone Number Activated", /// "Country Code","National Prefix", "Extension", "Department", "Department Type", /// "Parent Department", "Parent Department Type", "Participants", "Is Default", "Max Room Participants", /// "Is Support Outdial". /// The column values for "Is default", "Is Support Outdial" can either be true, or false. /// <see cref="GroupCollaborateBridgeGetInstancePagedSortedListRequest"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""939fd5846dfae8bdf58308d6cb9ebb12:377""}]")] public class GroupCollaborateBridgeGetInstancePagedSortedListResponse : BroadWorksConnector.Ocip.Models.C.OCIDataResponse { private BroadWorksConnector.Ocip.Models.C.OCITable _collaborateBridgeTable; [XmlElement(ElementName = "collaborateBridgeTable", IsNullable = false, Namespace = "")] [Group(@"939fd5846dfae8bdf58308d6cb9ebb12:377")] public BroadWorksConnector.Ocip.Models.C.OCITable CollaborateBridgeTable { get => _collaborateBridgeTable; set { CollaborateBridgeTableSpecified = true; _collaborateBridgeTable = value; } } [XmlIgnore] protected bool CollaborateBridgeTableSpecified { get; set; } } }
40.818182
129
0.693764
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupCollaborateBridgeGetInstancePagedSortedListResponse.cs
1,796
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.Globalization; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { [Trait(Traits.Feature, Traits.Features.SarifErrorLogging)] public class SarifV2ErrorLoggerTests : SarifErrorLoggerTests { protected override string ErrorLogQualifier => ";version=2"; internal override string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd) { string expectedOutput = @"{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ ], ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"" }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}"; return FormatOutputText(expectedOutput, cmd); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void NoDiagnostics() { NoDiagnosticsImpl(); } internal override string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile) { string expectedOutput = @"{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ {{ ""ruleId"": ""CS5001"", ""ruleIndex"": 0, ""level"": ""error"", ""message"": {{ ""text"": ""Program does not contain a static 'Main' method suitable for an entry point"" }} }}, {{ ""ruleId"": ""CS0169"", ""ruleIndex"": 1, ""level"": ""warning"", ""message"": {{ ""text"": ""The field 'C.x' is never used"" }}, ""locations"": [ {{ ""physicalLocation"": {{ ""artifactLocation"": {{ ""uri"": ""{5}"" }}, ""region"": {{ ""startLine"": 4, ""startColumn"": 17, ""endLine"": 4, ""endColumn"": 18 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"", ""rules"": [ {{ ""id"": ""CS5001"", ""defaultConfiguration"": {{ ""level"": ""error"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }}, {{ ""id"": ""CS0169"", ""shortDescription"": {{ ""text"": ""Field is never used"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }} ] }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}"; return FormatOutputText( expectedOutput, cmd, AnalyzerForErrorLogTest.GetUriForPath(sourceFile)); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void SimpleCompilerDiagnostics() { SimpleCompilerDiagnosticsImpl(); } internal override string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile) { string expectedOutput = @"{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ ""results"": [ {{ ""ruleId"": ""CS5001"", ""ruleIndex"": 0, ""level"": ""error"", ""message"": {{ ""text"": ""Program does not contain a static 'Main' method suitable for an entry point"" }} }}, {{ ""ruleId"": ""CS0169"", ""ruleIndex"": 1, ""level"": ""warning"", ""message"": {{ ""text"": ""The field 'C.x' is never used"" }}, ""suppressions"": [ {{ ""kind"": ""inSource"" }} ], ""locations"": [ {{ ""physicalLocation"": {{ ""artifactLocation"": {{ ""uri"": ""{5}"" }}, ""region"": {{ ""startLine"": 5, ""startColumn"": 17, ""endLine"": 5, ""endColumn"": 18 }} }} }} ], ""properties"": {{ ""warningLevel"": 3 }} }} ], ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"", ""rules"": [ {{ ""id"": ""CS5001"", ""defaultConfiguration"": {{ ""level"": ""error"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"", ""NotConfigurable"" ] }} }}, {{ ""id"": ""CS0169"", ""shortDescription"": {{ ""text"": ""Field is never used"" }}, ""properties"": {{ ""category"": ""Compiler"", ""tags"": [ ""Compiler"", ""Telemetry"" ] }} }} ] }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}"; return FormatOutputText( expectedOutput, cmd, AnalyzerForErrorLogTest.GetUriForPath(sourceFile)); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void SimpleCompilerDiagnosticsSuppressed() { SimpleCompilerDiagnosticsSuppressedImpl(); } internal override string GetExpectedOutputForAnalyzerDiagnosticsWithAndWithoutLocation(MockCSharpCompiler cmd) { string expectedOutput = @"{{ ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"", ""version"": ""2.1.0"", ""runs"": [ {{ {5}, ""tool"": {{ ""driver"": {{ ""name"": ""{0}"", ""version"": ""{1}"", ""dottedQuadFileVersion"": ""{2}"", ""semanticVersion"": ""{3}"", ""language"": ""{4}"", {6} }} }}, ""columnKind"": ""utf16CodeUnits"" }} ] }}"; return FormatOutputText( expectedOutput, cmd, AnalyzerForErrorLogTest.GetExpectedV2ErrorLogResultsText(cmd.Compilation), AnalyzerForErrorLogTest.GetExpectedV2ErrorLogRulesText()); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void AnalyzerDiagnosticsWithAndWithoutLocation() { AnalyzerDiagnosticsWithAndWithoutLocationImpl(); } private string FormatOutputText( string s, CommonCompiler compiler, params object[] additionalArguments) { var arguments = new object[] { compiler.GetToolName(), compiler.GetCompilerVersion(), compiler.GetAssemblyVersion(), compiler.GetAssemblyVersion().ToString(fieldCount: 3), compiler.GetCultureName() }.Concat(additionalArguments).ToArray(); return string.Format(CultureInfo.InvariantCulture, s, arguments); } } }
28.935275
127
0.43843
[ "MIT" ]
06needhamt/roslyn
src/Compilers/CSharp/Test/CommandLine/SarifV2ErrorLoggerTests.cs
8,943
C#
using System; using System.Globalization; using NetTopologySuite.Geometries; namespace NetTopologySuite.Mathematics { /// <summary> /// Represents a vector in 3-dimensional Cartesian space. /// </summary> /// <author>Martin Davis</author> public class Vector3D { /// <summary> /// Creates a new vector with all components set to Zero /// </summary> public static Vector3D Zero => new Vector3D(0,0,0); // ReSharper disable InconsistentNaming /// <summary> /// Computes the dot product of the 3D vectors AB and CD. /// </summary> /// <param name="A">The start point of the 1st vector</param> /// <param name="B">The end point of the 1st vector</param> /// <param name="C">The start point of the 2nd vector</param> /// <param name="D">The end point of the 2nd vector</param> /// <returns>The dot product</returns> public static double Dot(Coordinate A, Coordinate B, Coordinate C, Coordinate D) { double ABx = B.X - A.X; double ABy = B.Y - A.Y; double ABz = B.Z - A.Z; double CDx = D.X - C.X; double CDy = D.Y - C.Y; double CDz = D.Z - C.Z; return ABx * CDx + ABy * CDy + ABz * CDz; } // ReSharper restore InconsistentNaming /// <summary> /// Calculates the cross product of two vectors. /// </summary> /// <param name="left">First source vector.</param> /// <param name="right">Second source vector.</param> public static Vector3D Cross(Vector3D left, Vector3D right) { return new Vector3D( (left.Y * right.Z) - (left.Z * right.Y), (left.Z * right.X) - (left.X * right.Z), (left.X * right.Y) - (left.Y * right.X)); } /// <summary> /// Creates a new vector with given <paramref name="x"/>, <paramref name="y"/> and <paramref name="z"/> components. /// </summary> /// <param name="x">The x component</param> /// <param name="y">The y component</param> /// <param name="z">The z component</param> /// <returns>A new vector</returns> public static Vector3D Create(double x, double y, double z) { return new Vector3D(x, y, z); } /// <summary> /// Creates a vector from a 3D <see cref="Coordinate"/>. /// <para/> /// The coordinate should have the /// X,Y and Z ordinates specified. /// </summary> /// <param name="coord">The coordinate to copy</param> /// <returns>A new vector</returns> public static Vector3D Create(Coordinate coord) { return new Vector3D(coord); } /// <summary> /// Computes the 3D dot-product of two <see cref="Coordinate"/>s /// </summary> /// <param name="v1">The 1st vector</param> /// <param name="v2">The 2nd vector</param> /// <returns>The dot product of the (coordinate) vectors</returns> public static double Dot(Coordinate v1, Coordinate v2) { return v1.X * v2.X + v1.Y * v2.Y + v1.Z * v2.Z; } private readonly double _x; private readonly double _y; private readonly double _z; /// <summary> /// Creates a new 3D vector from a <see cref="Coordinate"/>.<para/> The coordinate should have /// the X,Y and Z ordinates specified. /// </summary> /// <param name="coord">The coordinate to copy</param> public Vector3D(Coordinate coord) { _x = coord.X; _y = coord.Y; _z = coord.Z; } /// <summary> /// Creates a new vector with the direction and magnitude /// of the difference between the <paramref name="to"/> /// and <paramref name="from"/> <see cref="Coordinate"/>s. /// </summary> /// <param name="from">The origin coordinate</param> /// <param name="to">The destination coordinate</param> public Vector3D(Coordinate from, Coordinate to) { _x = to.X - from.X; _y = to.Y - from.Y; _z = to.Z - from.Z; } /// <summary> /// Creates a new vector with the given <paramref name="x"/>, <paramref name="y"/> and <paramref name="z"/> components /// </summary> /// <param name="x">The x component</param> /// <param name="y">The y component</param> /// <param name="z">The z component</param> public Vector3D(double x, double y, double z) { _x = x; _y = y; _z = z; } /// <summary> /// Creates a new <see cref="Vector3D"/> using a <see cref="Vector2D"/> plus a value for <paramref name="z"/> component /// </summary> /// <param name="value">A vector containing the values with which to initialize the X and Y components.</param> /// <param name="z">Initial value for the Z component of the vector.</param> public Vector3D(Vector2D value, double z) { _x = value.X; _y = value.Y; _z = z; } /// <summary> /// Gets a value indicating the x-ordinate /// </summary> public double X => _x; /// <summary> /// Gets a value indicating the y-ordinate /// </summary> public double Y => _y; /// <summary> /// Gets a value indicating the z-ordinate /// </summary> public double Z => _z; /// <summary> /// Computes a vector which is the sum /// of this vector and the given vector. /// </summary> /// <param name="v">The vector to add</param> /// <returns>The sum of this and <c>v</c></returns> public Vector3D Add(Vector3D v) { return Create(X + v.X, Y + v.Y, Z + v.Z); } /// <summary> /// Computes a vector which is the difference /// of this vector and the given vector. /// </summary> /// <param name="v">The vector to subtract</param> /// <returns>The difference of this and <c>v</c></returns> public Vector3D Subtract(Vector3D v) { return Create(X - v.X, Y - v.Y, Z - v.Z); } /// <summary> /// Creates a new vector which has the same direction /// and with length equals to the length of this vector /// divided by the scalar value <c>d</c>. /// </summary> /// <param name="d">The scalar divisor</param> /// <returns>A new vector with divided length</returns> public Vector3D Divide(double d) { return Create(_x / d, _y / d, _z / d); } /// <summary> /// Computes the dot-product of this <see cref="Vector3D"/> and <paramref name="v"/> /// </summary> /// <paramref name="v">The 2nd vector</paramref> /// <returns>The dot product of the vectors</returns> public double Dot(Vector3D v) { return _x * v._x + _y * v._y + _z * v._z; } /// <summary> /// Computes the cross-product of this <see cref="Vector3D"/> and <paramref name="v"/> /// </summary> /// <paramref name="v">The 2nd vector</paramref> /// <returns>The cross product of the vectors</returns> public Vector3D Cross(Vector3D v) { return Vector3D.Cross(this, v); } /// <summary> /// Computes the length of this vector /// </summary> /// <returns>The length of this vector</returns> public double Length() { return Math.Sqrt(_x * _x + _y * _y + _z * _z); } /// <summary> /// Computes the length of vector <paramref name="v"/>. /// </summary> /// <param name="v">A coordinate representing a 3D Vector</param> /// <returns>The length of <paramref name="v"/></returns> public static double Length(Coordinate v) { return Math.Sqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z); } /// <summary> /// Computes a vector having identical direction /// but normalized to have length 1. /// </summary> /// <returns>A new normalized vector</returns> public Vector3D Normalize() { double length = Length(); if (length > 0.0) return Divide(Length()); return Create(0.0, 0.0, 0.0); } /// <summary> /// Computes a vector having identical direction as <c>v</c> /// but normalized to have length 1. /// </summary> /// <param name="v">A coordinate representing a 3D vector</param> /// <returns>A coordinate representing the normalized vector</returns> public static Coordinate Normalize(Coordinate v) { double len = Length(v); return new CoordinateZ(v.X / len, v.Y / len, v.Z / len); } /// <inheritdoc cref="object.ToString()"/> public override string ToString() { return string.Format(NumberFormatInfo.InvariantInfo, "[{0}, {1}, {2}]", _x, _y, _z); } ///<inheritdoc cref="object.Equals(object)"/> public override bool Equals(object o) { if (!(o is Vector3D v)) { return false; } return _x == v.X && _y == v.Y && _z == v.Z; } ///<inheritdoc cref="object.GetHashCode()"/> public override int GetHashCode() { // Algorithm from Effective Java by Joshua Bloch int result = 17; result = 37 * result + _x.GetHashCode(); result = 37 * result + _y.GetHashCode(); result = 37 * result + _z.GetHashCode(); return result; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="left">The first vector to add.</param> /// <param name="right">The second vector to add.</param> /// <returns>The sum of the two vectors.</returns> public static Vector3D operator +(Vector3D left, Vector3D right) { return new Vector3D(left.X + right.X, left.Y + right.Y, left.Z + right.Z); } /// <summary> /// Modulates a vector with another by performing component-wise multiplication. /// </summary> /// <param name="left">The first vector to multiply.</param> /// <param name="right">The second vector to multiply.</param> /// <returns>The multiplication of the two vectors.</returns> public static Vector3D operator *(Vector3D left, Vector3D right) { return new Vector3D(left.X * right.X, left.Y * right.Y, left.Z * right.Z); } /// <summary> /// Assert a vector (return it unchanged). /// </summary> /// <param name="value">The vector to assert (unchanged).</param> /// <returns>The asserted (unchanged) vector.</returns> public static Vector3D operator +(Vector3D value) { return value; } /// <summary> /// Subtracts two vectors. /// </summary> /// <param name="left">The first vector to subtract.</param> /// <param name="right">The second vector to subtract.</param> /// <returns>The difference of the two vectors.</returns> public static Vector3D operator -(Vector3D left, Vector3D right) { return new Vector3D(left.X - right.X, left.Y - right.Y, left.Z - right.Z); } /// <summary> /// Reverses the direction of a given vector. /// </summary> /// <param name="value">The vector to negate.</param> /// <returns>A vector facing in the opposite direction.</returns> public static Vector3D operator -(Vector3D value) { return new Vector3D(-value.X, -value.Y, -value.Z); } /// <summary> /// Scales a vector by the given value. /// </summary> /// <param name="value">The vector to scale.</param> /// <param name="scale">The amount by which to scale the vector.</param> /// <returns>The scaled vector.</returns> public static Vector3D operator *(double scale, Vector3D value) { return new Vector3D(value.X * scale, value.Y * scale, value.Z * scale); } /// <summary> /// Scales a vector by the given value. /// </summary> /// <param name="value">The vector to scale.</param> /// <param name="scale">The amount by which to scale the vector.</param> /// <returns>The scaled vector.</returns> public static Vector3D operator *(Vector3D value, double scale) { return new Vector3D(value.X * scale, value.Y * scale, value.Z * scale); } /// <summary> /// Scales a vector by the given value. /// </summary> /// <param name="value">The vector to scale.</param> /// <param name="scale">The amount by which to scale the vector.</param> /// <returns>The scaled vector.</returns> public static Vector3D operator /(Vector3D value, double scale) { return new Vector3D(value.X / scale, value.Y / scale, value.Z / scale); } /// <summary> /// Scales a vector by the given value. /// </summary> /// <param name="value">The vector to scale.</param> /// <param name="scale">The amount by which to scale the vector.</param> /// <returns>The scaled vector.</returns> public static Vector3D operator /(Vector3D value, Vector3D scale) { return new Vector3D(value.X / scale.X, value.Y / scale.Y, value.Z / scale.Z); } /// <summary> /// Tests for equality between two objects. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> public static bool operator ==(Vector3D left, Vector3D right) { if (left is null) return right is null; return left.Equals(right); } /// <summary> /// Tests for inequality between two objects. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> public static bool operator !=(Vector3D left, Vector3D right) { if (left is null) return !(right is null); return !left.Equals(right); } } }
37.235294
147
0.535611
[ "EPL-1.0" ]
ArneD/NetTopologySuite
src/NetTopologySuite/Mathematics/Vector3D.cs
15,194
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation { using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.ModelConfiguration.Configuration.Types; using System.Data.Entity.ModelConfiguration.Edm; using System.Data.Entity.Utilities; /// <summary> /// Used to configure an independent constraint on a navigation property. /// </summary> public class IndependentConstraintConfiguration : ConstraintConfiguration { private static readonly ConstraintConfiguration _instance = new IndependentConstraintConfiguration(); private IndependentConstraintConfiguration() { } /// <summary> /// Gets the Singleton instance of the IndependentConstraintConfiguration class. /// </summary> public static ConstraintConfiguration Instance { get { return _instance; } } internal override ConstraintConfiguration Clone() { return _instance; } internal override void Configure( AssociationType associationType, AssociationEndMember dependentEnd, EntityTypeConfiguration entityTypeConfiguration) { DebugCheck.NotNull(associationType); DebugCheck.NotNull(dependentEnd); DebugCheck.NotNull(entityTypeConfiguration); associationType.MarkIndependent(); } } }
35.565217
133
0.665037
[ "Apache-2.0" ]
TerraVenil/entityframework
src/EntityFramework/ModelConfiguration/Configuration/Properties/Navigation/IndependentConstraintConfiguration.cs
1,636
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Batch.Protocol.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// An Azure Batch job. /// </summary> public partial class CloudJob { /// <summary> /// Initializes a new instance of the CloudJob class. /// </summary> public CloudJob() { CustomInit(); } /// <summary> /// Initializes a new instance of the CloudJob class. /// </summary> /// <param name="id">A string that uniquely identifies the job within /// the account.</param> /// <param name="displayName">The display name for the job.</param> /// <param name="usesTaskDependencies">Whether tasks in the job can /// define dependencies on each other. The default is false.</param> /// <param name="url">The URL of the job.</param> /// <param name="eTag">The ETag of the job.</param> /// <param name="lastModified">The last modified time of the /// job.</param> /// <param name="creationTime">The creation time of the job.</param> /// <param name="state">The current state of the job.</param> /// <param name="stateTransitionTime">The time at which the job entered /// its current state.</param> /// <param name="previousState">The previous state of the job.</param> /// <param name="previousStateTransitionTime">The time at which the job /// entered its previous state.</param> /// <param name="priority">The priority of the job.</param> /// <param name="constraints">The execution constraints for the /// job.</param> /// <param name="jobManagerTask">Details of a Job Manager task to be /// launched when the job is started.</param> /// <param name="jobPreparationTask">The Job Preparation task.</param> /// <param name="jobReleaseTask">The Job Release task.</param> /// <param name="commonEnvironmentSettings">The list of common /// environment variable settings. These environment variables are set /// for all tasks in the job (including the Job Manager, Job /// Preparation and Job Release tasks).</param> /// <param name="poolInfo">The pool settings associated with the /// job.</param> /// <param name="onAllTasksComplete">The action the Batch service /// should take when all tasks in the job are in the completed /// state.</param> /// <param name="onTaskFailure">The action the Batch service should /// take when any task in the job fails.</param> /// <param name="networkConfiguration">The network configuration for /// the job.</param> /// <param name="metadata">A list of name-value pairs associated with /// the job as metadata.</param> /// <param name="executionInfo">The execution information for the /// job.</param> /// <param name="stats">Resource usage statistics for the entire /// lifetime of the job. The statistics may not be immediately /// available. The Batch service performs periodic roll-up of /// statistics. The typical delay is about 30 minutes.</param> public CloudJob(string id = default(string), string displayName = default(string), bool? usesTaskDependencies = default(bool?), string url = default(string), string eTag = default(string), System.DateTime? lastModified = default(System.DateTime?), System.DateTime? creationTime = default(System.DateTime?), JobState? state = default(JobState?), System.DateTime? stateTransitionTime = default(System.DateTime?), JobState? previousState = default(JobState?), System.DateTime? previousStateTransitionTime = default(System.DateTime?), int? priority = default(int?), JobConstraints constraints = default(JobConstraints), JobManagerTask jobManagerTask = default(JobManagerTask), JobPreparationTask jobPreparationTask = default(JobPreparationTask), JobReleaseTask jobReleaseTask = default(JobReleaseTask), IList<EnvironmentSetting> commonEnvironmentSettings = default(IList<EnvironmentSetting>), PoolInformation poolInfo = default(PoolInformation), OnAllTasksComplete? onAllTasksComplete = default(OnAllTasksComplete?), OnTaskFailure? onTaskFailure = default(OnTaskFailure?), JobNetworkConfiguration networkConfiguration = default(JobNetworkConfiguration), IList<MetadataItem> metadata = default(IList<MetadataItem>), JobExecutionInformation executionInfo = default(JobExecutionInformation), JobStatistics stats = default(JobStatistics)) { Id = id; DisplayName = displayName; UsesTaskDependencies = usesTaskDependencies; Url = url; ETag = eTag; LastModified = lastModified; CreationTime = creationTime; State = state; StateTransitionTime = stateTransitionTime; PreviousState = previousState; PreviousStateTransitionTime = previousStateTransitionTime; Priority = priority; Constraints = constraints; JobManagerTask = jobManagerTask; JobPreparationTask = jobPreparationTask; JobReleaseTask = jobReleaseTask; CommonEnvironmentSettings = commonEnvironmentSettings; PoolInfo = poolInfo; OnAllTasksComplete = onAllTasksComplete; OnTaskFailure = onTaskFailure; NetworkConfiguration = networkConfiguration; Metadata = metadata; ExecutionInfo = executionInfo; Stats = stats; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets a string that uniquely identifies the job within the /// account. /// </summary> /// <remarks> /// The ID is case-preserving and case-insensitive (that is, you may /// not have two IDs within an account that differ only by case). /// </remarks> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets the display name for the job. /// </summary> [JsonProperty(PropertyName = "displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets whether tasks in the job can define dependencies on /// each other. The default is false. /// </summary> [JsonProperty(PropertyName = "usesTaskDependencies")] public bool? UsesTaskDependencies { get; set; } /// <summary> /// Gets or sets the URL of the job. /// </summary> [JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// Gets or sets the ETag of the job. /// </summary> /// <remarks> /// This is an opaque string. You can use it to detect whether the job /// has changed between requests. In particular, you can be pass the /// ETag when updating a job to specify that your changes should take /// effect only if nobody else has modified the job in the meantime. /// </remarks> [JsonProperty(PropertyName = "eTag")] public string ETag { get; set; } /// <summary> /// Gets or sets the last modified time of the job. /// </summary> /// <remarks> /// This is the last time at which the job level data, such as the job /// state or priority, changed. It does not factor in task-level /// changes such as adding new tasks or tasks changing state. /// </remarks> [JsonProperty(PropertyName = "lastModified")] public System.DateTime? LastModified { get; set; } /// <summary> /// Gets or sets the creation time of the job. /// </summary> [JsonProperty(PropertyName = "creationTime")] public System.DateTime? CreationTime { get; set; } /// <summary> /// Gets or sets the current state of the job. /// </summary> /// <remarks> /// Possible values include: 'active', 'disabling', 'disabled', /// 'enabling', 'terminating', 'completed', 'deleting' /// </remarks> [JsonProperty(PropertyName = "state")] public JobState? State { get; set; } /// <summary> /// Gets or sets the time at which the job entered its current state. /// </summary> [JsonProperty(PropertyName = "stateTransitionTime")] public System.DateTime? StateTransitionTime { get; set; } /// <summary> /// Gets or sets the previous state of the job. /// </summary> /// <remarks> /// This property is not set if the job is in its initial Active state. /// Possible values include: 'active', 'disabling', 'disabled', /// 'enabling', 'terminating', 'completed', 'deleting' /// </remarks> [JsonProperty(PropertyName = "previousState")] public JobState? PreviousState { get; set; } /// <summary> /// Gets or sets the time at which the job entered its previous state. /// </summary> /// <remarks> /// This property is not set if the job is in its initial Active state. /// </remarks> [JsonProperty(PropertyName = "previousStateTransitionTime")] public System.DateTime? PreviousStateTransitionTime { get; set; } /// <summary> /// Gets or sets the priority of the job. /// </summary> /// <remarks> /// Priority values can range from -1000 to 1000, with -1000 being the /// lowest priority and 1000 being the highest priority. The default /// value is 0. /// </remarks> [JsonProperty(PropertyName = "priority")] public int? Priority { get; set; } /// <summary> /// Gets or sets the execution constraints for the job. /// </summary> [JsonProperty(PropertyName = "constraints")] public JobConstraints Constraints { get; set; } /// <summary> /// Gets or sets details of a Job Manager task to be launched when the /// job is started. /// </summary> [JsonProperty(PropertyName = "jobManagerTask")] public JobManagerTask JobManagerTask { get; set; } /// <summary> /// Gets or sets the Job Preparation task. /// </summary> /// <remarks> /// The Job Preparation task is a special task run on each node before /// any other task of the job. /// </remarks> [JsonProperty(PropertyName = "jobPreparationTask")] public JobPreparationTask JobPreparationTask { get; set; } /// <summary> /// Gets or sets the Job Release task. /// </summary> /// <remarks> /// The Job Release task is a special task run at the end of the job on /// each node that has run any other task of the job. /// </remarks> [JsonProperty(PropertyName = "jobReleaseTask")] public JobReleaseTask JobReleaseTask { get; set; } /// <summary> /// Gets or sets the list of common environment variable settings. /// These environment variables are set for all tasks in the job /// (including the Job Manager, Job Preparation and Job Release tasks). /// </summary> /// <remarks> /// Individual tasks can override an environment setting specified here /// by specifying the same setting name with a different value. /// </remarks> [JsonProperty(PropertyName = "commonEnvironmentSettings")] public IList<EnvironmentSetting> CommonEnvironmentSettings { get; set; } /// <summary> /// Gets or sets the pool settings associated with the job. /// </summary> [JsonProperty(PropertyName = "poolInfo")] public PoolInformation PoolInfo { get; set; } /// <summary> /// Gets or sets the action the Batch service should take when all /// tasks in the job are in the completed state. /// </summary> /// <remarks> /// The default is noaction. Possible values include: 'noAction', /// 'terminateJob' /// </remarks> [JsonProperty(PropertyName = "onAllTasksComplete")] public OnAllTasksComplete? OnAllTasksComplete { get; set; } /// <summary> /// Gets or sets the action the Batch service should take when any task /// in the job fails. /// </summary> /// <remarks> /// A task is considered to have failed if has a failureInfo. A /// failureInfo is set if the task completes with a non-zero exit code /// after exhausting its retry count, or if there was an error starting /// the task, for example due to a resource file download error. The /// default is noaction. Possible values include: 'noAction', /// 'performExitOptionsJobAction' /// </remarks> [JsonProperty(PropertyName = "onTaskFailure")] public OnTaskFailure? OnTaskFailure { get; set; } /// <summary> /// Gets or sets the network configuration for the job. /// </summary> [JsonProperty(PropertyName = "networkConfiguration")] public JobNetworkConfiguration NetworkConfiguration { get; set; } /// <summary> /// Gets or sets a list of name-value pairs associated with the job as /// metadata. /// </summary> /// <remarks> /// The Batch service does not assign any meaning to metadata; it is /// solely for the use of user code. /// </remarks> [JsonProperty(PropertyName = "metadata")] public IList<MetadataItem> Metadata { get; set; } /// <summary> /// Gets or sets the execution information for the job. /// </summary> [JsonProperty(PropertyName = "executionInfo")] public JobExecutionInformation ExecutionInfo { get; set; } /// <summary> /// Gets or sets resource usage statistics for the entire lifetime of /// the job. The statistics may not be immediately available. The Batch /// service performs periodic roll-up of statistics. The typical delay /// is about 30 minutes. /// </summary> [JsonProperty(PropertyName = "stats")] public JobStatistics Stats { get; set; } } }
45.838906
1,338
0.616604
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/Batch/DataPlane/Azure.Batch/GeneratedProtocol/Models/CloudJob.cs
15,081
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request the user's incoming calling plan settings. /// The response is either a UserIncomingCallingPlanGetResponse or an ErrorResponse. /// <see cref="UserIncomingCallingPlanGetResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""3dd296d55b56269ae23d86a934b8b35c:98""}]")] public class UserIncomingCallingPlanGetRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _userId; [XmlElement(ElementName = "userId", IsNullable = false, Namespace = "")] [Group(@"3dd296d55b56269ae23d86a934b8b35c:98")] [MinLength(1)] [MaxLength(161)] public string UserId { get => _userId; set { UserIdSpecified = true; _userId = value; } } [XmlIgnore] protected bool UserIdSpecified { get; set; } } }
29.534884
128
0.637008
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/UserIncomingCallingPlanGetRequest.cs
1,270
C#
using System.ComponentModel; namespace DevPython { partial class SaveOpenDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.controlEncodingComboBox = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(26, 11); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(55, 13); this.label1.TabIndex = 0; this.label1.Text = "Encoding:"; // // controlEncodingComboBox // this.controlEncodingComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.controlEncodingComboBox.DisplayMember = "Display"; this.controlEncodingComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.controlEncodingComboBox.FormattingEnabled = true; this.controlEncodingComboBox.Location = new System.Drawing.Point(87, 8); this.controlEncodingComboBox.Name = "controlEncodingComboBox"; this.controlEncodingComboBox.Size = new System.Drawing.Size(178, 21); this.controlEncodingComboBox.TabIndex = 1; this.controlEncodingComboBox.ValueMember = "Value"; // // SaveOpenDialog // this.BackColor = System.Drawing.SystemColors.Control; this.Controls.Add(this.controlEncodingComboBox); this.Controls.Add(this.label1); this.FileDlgCaption = ""; this.FileDlgCheckFileExists = false; this.FileDlgDefaultExt = ""; this.FileDlgDefaultViewMode = Win32Types.FolderViewMode.List; this.FileDlgFilter = ""; this.FileDlgOkCaption = ""; this.FileDlgStartLocation = FileDialogExtenders.AddonWindowLocation.Bottom; this.Name = "SaveOpenDialog"; this.Size = new System.Drawing.Size(422, 38); this.EventFileNameChanged += new FileDialogExtenders.FileDialogControlBase.PathChangedEventHandler(this.SaveOpenDialog_EventFileNameChanged); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox controlEncodingComboBox; } }
42.418919
171
0.628863
[ "MIT" ]
BloodmageThalnos/DevPython_Csharp
SaveOpenDialog.designer.cs
3,139
C#
using UnityEngine.Experimental.Rendering; namespace UnityEngine.Rendering.Universal.Internal { // Note: this pass can't be done at the same time as post-processing as it needs to be done in // advance in case we're doing on-tile color grading. /// <summary> /// Renders a color grading LUT texture. /// </summary> public class ColorGradingLutPass : ScriptableRenderPass { readonly Material m_LutBuilderLdr; readonly Material m_LutBuilderHdr; readonly GraphicsFormat m_HdrLutFormat; readonly GraphicsFormat m_LdrLutFormat; RenderTargetHandle m_InternalLut; bool m_AllowColorGradingACESHDR = true; public ColorGradingLutPass(RenderPassEvent evt, PostProcessData data) { base.profilingSampler = new ProfilingSampler(nameof(ColorGradingLutPass)); renderPassEvent = evt; overrideCameraTarget = true; Material Load(Shader shader) { if (shader == null) { Debug.LogError($"Missing shader. {GetType().DeclaringType.Name} render pass will not execute. Check for missing reference in the renderer resources."); return null; } return CoreUtils.CreateEngineMaterial(shader); } m_LutBuilderLdr = Load(data.shaders.lutBuilderLdrPS); m_LutBuilderHdr = Load(data.shaders.lutBuilderHdrPS); // Warm up lut format as IsFormatSupported adds GC pressure... const FormatUsage kFlags = FormatUsage.Linear | FormatUsage.Render; if (SystemInfo.IsFormatSupported(GraphicsFormat.R16G16B16A16_SFloat, kFlags)) m_HdrLutFormat = GraphicsFormat.R16G16B16A16_SFloat; else if (SystemInfo.IsFormatSupported(GraphicsFormat.B10G11R11_UFloatPack32, kFlags)) m_HdrLutFormat = GraphicsFormat.B10G11R11_UFloatPack32; else // Obviously using this for log lut encoding is a very bad idea for precision but we // need it for compatibility reasons and avoid black screens on platforms that don't // support floating point formats. Expect banding and posterization artifact if this // ends up being used. m_HdrLutFormat = GraphicsFormat.R8G8B8A8_UNorm; m_LdrLutFormat = GraphicsFormat.R8G8B8A8_UNorm; base.useNativeRenderPass = false; if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3 && Graphics.minOpenGLESVersion <= OpenGLESVersion.OpenGLES30 && SystemInfo.graphicsDeviceName.StartsWith("Adreno (TM) 3")) m_AllowColorGradingACESHDR = false; } public void Setup(in RenderTargetHandle internalLut) { m_InternalLut = internalLut; } /// <inheritdoc/> public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { var cmd = CommandBufferPool.Get(); using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.ColorGradingLUT))) { // Fetch all color grading settings var stack = VolumeManager.instance.stack; var channelMixer = stack.GetComponent<ChannelMixer>(); var colorAdjustments = stack.GetComponent<ColorAdjustments>(); var curves = stack.GetComponent<ColorCurves>(); var liftGammaGain = stack.GetComponent<LiftGammaGain>(); var shadowsMidtonesHighlights = stack.GetComponent<ShadowsMidtonesHighlights>(); var splitToning = stack.GetComponent<SplitToning>(); var tonemapping = stack.GetComponent<Tonemapping>(); var whiteBalance = stack.GetComponent<WhiteBalance>(); ref var postProcessingData = ref renderingData.postProcessingData; bool hdr = postProcessingData.gradingMode == ColorGradingMode.HighDynamicRange; // Prepare texture & material int lutHeight = postProcessingData.lutSize; int lutWidth = lutHeight * lutHeight; var format = hdr ? m_HdrLutFormat : m_LdrLutFormat; var material = hdr ? m_LutBuilderHdr : m_LutBuilderLdr; var desc = new RenderTextureDescriptor(lutWidth, lutHeight, format, 0); desc.vrUsage = VRTextureUsage.None; // We only need one for both eyes in VR cmd.GetTemporaryRT(m_InternalLut.id, desc, FilterMode.Bilinear); // Prepare data var lmsColorBalance = ColorUtils.ColorBalanceToLMSCoeffs(whiteBalance.temperature.value, whiteBalance.tint.value); var hueSatCon = new Vector4(colorAdjustments.hueShift.value / 360f, colorAdjustments.saturation.value / 100f + 1f, colorAdjustments.contrast.value / 100f + 1f, 0f); var channelMixerR = new Vector4(channelMixer.redOutRedIn.value / 100f, channelMixer.redOutGreenIn.value / 100f, channelMixer.redOutBlueIn.value / 100f, 0f); var channelMixerG = new Vector4(channelMixer.greenOutRedIn.value / 100f, channelMixer.greenOutGreenIn.value / 100f, channelMixer.greenOutBlueIn.value / 100f, 0f); var channelMixerB = new Vector4(channelMixer.blueOutRedIn.value / 100f, channelMixer.blueOutGreenIn.value / 100f, channelMixer.blueOutBlueIn.value / 100f, 0f); var shadowsHighlightsLimits = new Vector4( shadowsMidtonesHighlights.shadowsStart.value, shadowsMidtonesHighlights.shadowsEnd.value, shadowsMidtonesHighlights.highlightsStart.value, shadowsMidtonesHighlights.highlightsEnd.value ); var (shadows, midtones, highlights) = ColorUtils.PrepareShadowsMidtonesHighlights( shadowsMidtonesHighlights.shadows.value, shadowsMidtonesHighlights.midtones.value, shadowsMidtonesHighlights.highlights.value ); var (lift, gamma, gain) = ColorUtils.PrepareLiftGammaGain( liftGammaGain.lift.value, liftGammaGain.gamma.value, liftGammaGain.gain.value ); var (splitShadows, splitHighlights) = ColorUtils.PrepareSplitToning( splitToning.shadows.value, splitToning.highlights.value, splitToning.balance.value ); var lutParameters = new Vector4(lutHeight, 0.5f / lutWidth, 0.5f / lutHeight, lutHeight / (lutHeight - 1f)); // Fill in constants material.SetVector(ShaderConstants._Lut_Params, lutParameters); material.SetVector(ShaderConstants._ColorBalance, lmsColorBalance); material.SetVector(ShaderConstants._ColorFilter, colorAdjustments.colorFilter.value.linear); material.SetVector(ShaderConstants._ChannelMixerRed, channelMixerR); material.SetVector(ShaderConstants._ChannelMixerGreen, channelMixerG); material.SetVector(ShaderConstants._ChannelMixerBlue, channelMixerB); material.SetVector(ShaderConstants._HueSatCon, hueSatCon); material.SetVector(ShaderConstants._Lift, lift); material.SetVector(ShaderConstants._Gamma, gamma); material.SetVector(ShaderConstants._Gain, gain); material.SetVector(ShaderConstants._Shadows, shadows); material.SetVector(ShaderConstants._Midtones, midtones); material.SetVector(ShaderConstants._Highlights, highlights); material.SetVector(ShaderConstants._ShaHiLimits, shadowsHighlightsLimits); material.SetVector(ShaderConstants._SplitShadows, splitShadows); material.SetVector(ShaderConstants._SplitHighlights, splitHighlights); // YRGB curves material.SetTexture(ShaderConstants._CurveMaster, curves.master.value.GetTexture()); material.SetTexture(ShaderConstants._CurveRed, curves.red.value.GetTexture()); material.SetTexture(ShaderConstants._CurveGreen, curves.green.value.GetTexture()); material.SetTexture(ShaderConstants._CurveBlue, curves.blue.value.GetTexture()); // Secondary curves material.SetTexture(ShaderConstants._CurveHueVsHue, curves.hueVsHue.value.GetTexture()); material.SetTexture(ShaderConstants._CurveHueVsSat, curves.hueVsSat.value.GetTexture()); material.SetTexture(ShaderConstants._CurveLumVsSat, curves.lumVsSat.value.GetTexture()); material.SetTexture(ShaderConstants._CurveSatVsSat, curves.satVsSat.value.GetTexture()); // Tonemapping (baked into the lut for HDR) if (hdr) { material.shaderKeywords = null; switch (tonemapping.mode.value) { case TonemappingMode.Neutral: material.EnableKeyword(ShaderKeywordStrings.TonemapNeutral); break; case TonemappingMode.ACES: material.EnableKeyword(m_AllowColorGradingACESHDR ? ShaderKeywordStrings.TonemapACES : ShaderKeywordStrings.TonemapNeutral); break; default: break; // None } } renderingData.cameraData.xr.StopSinglePass(cmd); // Render the lut cmd.Blit(null, m_InternalLut.id, material); renderingData.cameraData.xr.StartSinglePass(cmd); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } /// <inheritdoc/> public override void OnFinishCameraStackRendering(CommandBuffer cmd) { cmd.ReleaseTemporaryRT(m_InternalLut.id); } public void Cleanup() { CoreUtils.Destroy(m_LutBuilderLdr); CoreUtils.Destroy(m_LutBuilderHdr); } // Precomputed shader ids to same some CPU cycles (mostly affects mobile) static class ShaderConstants { public static readonly int _Lut_Params = Shader.PropertyToID("_Lut_Params"); public static readonly int _ColorBalance = Shader.PropertyToID("_ColorBalance"); public static readonly int _ColorFilter = Shader.PropertyToID("_ColorFilter"); public static readonly int _ChannelMixerRed = Shader.PropertyToID("_ChannelMixerRed"); public static readonly int _ChannelMixerGreen = Shader.PropertyToID("_ChannelMixerGreen"); public static readonly int _ChannelMixerBlue = Shader.PropertyToID("_ChannelMixerBlue"); public static readonly int _HueSatCon = Shader.PropertyToID("_HueSatCon"); public static readonly int _Lift = Shader.PropertyToID("_Lift"); public static readonly int _Gamma = Shader.PropertyToID("_Gamma"); public static readonly int _Gain = Shader.PropertyToID("_Gain"); public static readonly int _Shadows = Shader.PropertyToID("_Shadows"); public static readonly int _Midtones = Shader.PropertyToID("_Midtones"); public static readonly int _Highlights = Shader.PropertyToID("_Highlights"); public static readonly int _ShaHiLimits = Shader.PropertyToID("_ShaHiLimits"); public static readonly int _SplitShadows = Shader.PropertyToID("_SplitShadows"); public static readonly int _SplitHighlights = Shader.PropertyToID("_SplitHighlights"); public static readonly int _CurveMaster = Shader.PropertyToID("_CurveMaster"); public static readonly int _CurveRed = Shader.PropertyToID("_CurveRed"); public static readonly int _CurveGreen = Shader.PropertyToID("_CurveGreen"); public static readonly int _CurveBlue = Shader.PropertyToID("_CurveBlue"); public static readonly int _CurveHueVsHue = Shader.PropertyToID("_CurveHueVsHue"); public static readonly int _CurveHueVsSat = Shader.PropertyToID("_CurveHueVsSat"); public static readonly int _CurveLumVsSat = Shader.PropertyToID("_CurveLumVsSat"); public static readonly int _CurveSatVsSat = Shader.PropertyToID("_CurveSatVsSat"); } } }
55.396476
200
0.65002
[ "MIT" ]
Liaoer/ToonShader
Packages/com.unity.render-pipelines.universal@12.1.3/Runtime/Passes/ColorGradingLutPass.cs
12,575
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace addressbook_web_tests { class ContactModificateTest { } }
15.230769
33
0.762626
[ "Apache-2.0" ]
Yuliya-Kirich/csharp_training
addressbook-web-tests/addressbook-web-tests/tests/ContactModificateTest.cs
200
C#
#if TESTING using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Authentication.Twitter; using Microsoft.AspNet.Identity; using MusicStore.Mocks.Common; namespace MusicStore.Mocks.Twitter { /// <summary> /// Summary description for TwitterNotifications /// </summary> internal class TwitterNotifications { internal static async Task OnAuthenticated(TwitterAuthenticatedContext context) { if (context.Principal != null) { Helpers.ThrowIfConditionFailed(() => context.UserId == "valid_user_id", "UserId is not valid"); Helpers.ThrowIfConditionFailed(() => context.ScreenName == "valid_screen_name", "ScreenName is not valid"); Helpers.ThrowIfConditionFailed(() => context.AccessToken == "valid_oauth_token", "AccessToken is not valid"); Helpers.ThrowIfConditionFailed(() => context.AccessTokenSecret == "valid_oauth_token_secret", "AccessTokenSecret is not valid"); context.Principal.Identities.First().AddClaim(new Claim("ManageStore", "false")); } await Task.FromResult(0); } internal static async Task OnReturnEndpoint(TwitterReturnEndpointContext context) { if (context.Principal != null && context.SignInScheme == IdentityOptions.ExternalCookieAuthenticationScheme) { //This way we will know all notifications were fired. var identity = context.Principal.Identities.First(); var manageStoreClaim = identity?.Claims.Where(c => c.Type == "ManageStore" && c.Value == "false").FirstOrDefault(); if (manageStoreClaim != null) { identity.RemoveClaim(manageStoreClaim); identity.AddClaim(new Claim("ManageStore", "Allowed")); } } await Task.FromResult(0); } internal static void OnApplyRedirect(TwitterApplyRedirectContext context) { context.Response.Redirect(context.RedirectUri + "&custom_redirect_uri=custom"); } } } #endif
41.471698
144
0.633758
[ "Apache-2.0" ]
harryi3t/MusicStore
test/E2ETests/compiler/shared/Mocks/Twitter/TwitterNotifications.cs
2,200
C#
// <auto-generated /> namespace BudouCSharpNuget.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class Init : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(Init)); string IMigrationMetadata.Id { get { return "201908230942016_Init"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
26.666667
87
0.6125
[ "Apache-2.0" ]
NitecoOPS/BudouCSharp
BudouCSharpNuget/Migrations/201908230942016_Init.Designer.cs
800
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.Diagnostics; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.Win32.SafeHandles { public sealed partial class SafePipeHandle : SafeHandle { private const int DefaultInvalidHandle = -1; // For anonymous pipes, SafePipeHandle.handle is the file descriptor of the pipe, and the // _named* fields remain null. For named pipes, SafePipeHandle.handle is a copy of the file descriptor // extracted from the Socket's SafeHandle, and the _named* fields are the socket and its safe handle. // This allows operations related to file descriptors to be performed directly on the SafePipeHandle, // and operations that should go through the Socket to be done via _namedPipeSocket. We keep the // Socket's SafeHandle alive as long as this SafeHandle is alive. private Socket _namedPipeSocket; private SafeHandle _namedPipeSocketHandle; private static PropertyInfo s_safeHandleProperty; internal SafePipeHandle(Socket namedPipeSocket) : base((IntPtr)DefaultInvalidHandle, ownsHandle: true) { Debug.Assert(namedPipeSocket != null); _namedPipeSocket = namedPipeSocket; // TODO: Issue https://github.com/dotnet/corefx/issues/6807 // This is unfortunately the only way of getting at the Socket's file descriptor right now, until #6807 is implemented. PropertyInfo safeHandleProperty = s_safeHandleProperty ?? (s_safeHandleProperty = typeof(Socket).GetTypeInfo().GetDeclaredProperty("SafeHandle")); Debug.Assert(safeHandleProperty != null, "Socket.SafeHandle could not be found."); _namedPipeSocketHandle = (SafeHandle)safeHandleProperty?.GetValue(namedPipeSocket, null); bool ignored = false; _namedPipeSocketHandle.DangerousAddRef(ref ignored); SetHandle(_namedPipeSocketHandle.DangerousGetHandle()); } internal Socket NamedPipeSocket => _namedPipeSocket; internal SafeHandle NamedPipeSocketHandle => _namedPipeSocketHandle; protected override void Dispose(bool disposing) { base.Dispose(disposing); // must be called before trying to Dispose the socket if (disposing && _namedPipeSocket != null) { _namedPipeSocket.Dispose(); _namedPipeSocket = null; } } protected override bool ReleaseHandle() { Debug.Assert(!IsInvalid); // Clean up resources for named handles if (_namedPipeSocketHandle != null) { SetHandle(DefaultInvalidHandle); _namedPipeSocketHandle.DangerousRelease(); _namedPipeSocketHandle = null; return true; } // Clean up resources for anonymous handles return (long)handle >= 0 ? Interop.Sys.Close(handle) == 0 : true; } public override bool IsInvalid { [SecurityCritical] get { return (long)handle < 0 && _namedPipeSocket == null; } } } }
41.345238
158
0.656205
[ "MIT" ]
OceanYan/corefx
src/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Unix.cs
3,473
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace BMS.Data.Migrations { public partial class ModelsInitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Name", table: "AspNetUserTokens", type: "nvarchar(450)", nullable: false, oldClrType: typeof(string), oldType: "nvarchar(128)", oldMaxLength: 128); migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AspNetUserTokens", type: "nvarchar(450)", nullable: false, oldClrType: typeof(string), oldType: "nvarchar(128)", oldMaxLength: 128); migrationBuilder.AlterColumn<string>( name: "ProviderKey", table: "AspNetUserLogins", type: "nvarchar(450)", nullable: false, oldClrType: typeof(string), oldType: "nvarchar(128)", oldMaxLength: 128); migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AspNetUserLogins", type: "nvarchar(450)", nullable: false, oldClrType: typeof(string), oldType: "nvarchar(128)", oldMaxLength: 128); migrationBuilder.CreateTable( name: "Building", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1") }, constraints: table => { table.PrimaryKey("PK_Building", x => x.Id); }); migrationBuilder.CreateTable( name: "Cities", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(type: "nvarchar(80)", maxLength: 80, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Cities", x => x.Id); }); migrationBuilder.CreateTable( name: "Fees", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Amount = table.Column<double>(type: "float", nullable: false), CreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false), Type = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false), Description = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Fees", x => x.Id); }); migrationBuilder.CreateTable( name: "PaymentTypes", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Type = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false) }, constraints: table => { table.PrimaryKey("PK_PaymentTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "PropertyFloors", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Floor = table.Column<byte>(type: "tinyint", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PropertyFloors", x => x.Id); }); migrationBuilder.CreateTable( name: "PropertyStatusMonthly", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Status = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false) }, constraints: table => { table.PrimaryKey("PK_PropertyStatusMonthly", x => x.Id); }); migrationBuilder.CreateTable( name: "PropertyTypes", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Type = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false) }, constraints: table => { table.PrimaryKey("PK_PropertyTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Tenants", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FirstName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false), MiddleName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true), LastName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false), Email = table.Column<string>(type: "nvarchar(80)", maxLength: 80, nullable: false), Phone = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Tenants", x => x.Id); }); migrationBuilder.CreateTable( name: "Addresses", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CityId = table.Column<int>(type: "int", nullable: false), District = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true), ZipCode = table.Column<byte>(type: "tinyint", nullable: false), Street = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true), StreetNumber = table.Column<string>(type: "nvarchar(6)", maxLength: 6, nullable: true), BlockNumber = table.Column<string>(type: "nvarchar(6)", maxLength: 6, nullable: true), EntranceNumber = table.Column<string>(type: "nvarchar(6)", maxLength: 6, nullable: true), Floor = table.Column<int>(type: "int", nullable: true), AppartmentNumber = table.Column<int>(type: "int", nullable: true), BuildingId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Addresses", x => x.Id); table.ForeignKey( name: "FK_Addresses_Building_BuildingId", column: x => x.BuildingId, principalTable: "Building", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Addresses_Cities_CityId", column: x => x.CityId, principalTable: "Cities", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "BuildingAccounts", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), AccountType = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false), TotalAmount = table.Column<decimal>(type: "decimal(18,2)", nullable: false), BuildingId = table.Column<int>(type: "int", nullable: false), PaymentTypeId = table.Column<int>(type: "int", nullable: false), Description = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false) }, constraints: table => { table.PrimaryKey("PK_BuildingAccounts", x => x.Id); table.ForeignKey( name: "FK_BuildingAccounts_Building_BuildingId", column: x => x.BuildingId, principalTable: "Building", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_BuildingAccounts_PaymentTypes_PaymentTypeId", column: x => x.PaymentTypeId, principalTable: "PaymentTypes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "CompanyOwners", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CompanyName = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false), UIC = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: true), CompanyOwnerFullName = table.Column<string>(type: "nvarchar(150)", maxLength: 150, nullable: false), Email = table.Column<string>(type: "nvarchar(80)", maxLength: 80, nullable: false), Phone = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false), AddressId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_CompanyOwners", x => x.Id); table.ForeignKey( name: "FK_CompanyOwners_Addresses_AddressId", column: x => x.AddressId, principalTable: "Addresses", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Owners", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FirstName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false), MiddleName = table.Column<string>(type: "nvarchar(max)", nullable: true), LastName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false), Email = table.Column<string>(type: "nvarchar(80)", maxLength: 80, nullable: true), Phone = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false), AddressId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Owners", x => x.Id); table.ForeignKey( name: "FK_Owners_Addresses_AddressId", column: x => x.AddressId, principalTable: "Addresses", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "OutgoingPayments", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Amount = table.Column<decimal>(type: "decimal(18,2)", nullable: false), DateOfPayment = table.Column<DateTime>(type: "datetime2", nullable: false), Description = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), PaymentTypeId = table.Column<int>(type: "int", nullable: true), AccountId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_OutgoingPayments", x => x.Id); table.ForeignKey( name: "FK_OutgoingPayments_BuildingAccounts_AccountId", column: x => x.AccountId, principalTable: "BuildingAccounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_OutgoingPayments_PaymentTypes_PaymentTypeId", column: x => x.PaymentTypeId, principalTable: "PaymentTypes", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Properties", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), BuildingId = table.Column<int>(type: "int", nullable: false), PropertyTypeId = table.Column<int>(type: "int", nullable: false), PropertyFloorId = table.Column<int>(type: "int", nullable: false), AppartNumber = table.Column<int>(type: "int", nullable: false), PropertyPart = table.Column<double>(type: "float", nullable: false), DogCount = table.Column<int>(type: "int", nullable: true), TenantId = table.Column<int>(type: "int", nullable: false), CompanyOwnerId = table.Column<int>(type: "int", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Properties", x => x.Id); table.ForeignKey( name: "FK_Properties_Building_BuildingId", column: x => x.BuildingId, principalTable: "Building", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Properties_CompanyOwners_CompanyOwnerId", column: x => x.CompanyOwnerId, principalTable: "CompanyOwners", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Properties_PropertyFloors_PropertyFloorId", column: x => x.PropertyFloorId, principalTable: "PropertyFloors", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Properties_PropertyTypes_PropertyTypeId", column: x => x.PropertyTypeId, principalTable: "PropertyTypes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Properties_Tenants_TenantId", column: x => x.TenantId, principalTable: "Tenants", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "IncomingPayments", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), PropertyId = table.Column<int>(type: "int", nullable: true), PaymentTypeId = table.Column<int>(type: "int", nullable: true), PaidDate = table.Column<DateTime>(type: "datetime2", nullable: false), Amount = table.Column<decimal>(type: "decimal(18,2)", nullable: false), PaymentPeriod = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: false), AccountId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_IncomingPayments", x => x.Id); table.ForeignKey( name: "FK_IncomingPayments_BuildingAccounts_AccountId", column: x => x.AccountId, principalTable: "BuildingAccounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_IncomingPayments_PaymentTypes_PaymentTypeId", column: x => x.PaymentTypeId, principalTable: "PaymentTypes", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_IncomingPayments_Properties_PropertyId", column: x => x.PropertyId, principalTable: "Properties", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PropertiesOwners", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), OwnerId = table.Column<int>(type: "int", nullable: false), PropertyId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PropertiesOwners", x => x.Id); table.ForeignKey( name: "FK_PropertiesOwners_Owners_OwnerId", column: x => x.OwnerId, principalTable: "Owners", principalColumn: "Id"); table.ForeignKey( name: "FK_PropertiesOwners_Properties_PropertyId", column: x => x.PropertyId, principalTable: "Properties", principalColumn: "Id"); }); migrationBuilder.CreateTable( name: "PropertyDebtsMonthly", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), OccurrenceDate = table.Column<DateTime>(type: "datetime2", nullable: false), PropertyId = table.Column<int>(type: "int", nullable: false), PropertyStatusId = table.Column<int>(type: "int", nullable: true), FeeId = table.Column<int>(type: "int", nullable: false), IsPaid = table.Column<bool>(type: "bit", nullable: false), Descrtiption = table.Column<string>(type: "nvarchar(250)", maxLength: 250, nullable: true) }, constraints: table => { table.PrimaryKey("PK_PropertyDebtsMonthly", x => x.Id); table.ForeignKey( name: "FK_PropertyDebtsMonthly_Fees_FeeId", column: x => x.FeeId, principalTable: "Fees", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PropertyDebtsMonthly_Properties_PropertyId", column: x => x.PropertyId, principalTable: "Properties", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PropertyDebtsMonthly_PropertyStatusMonthly_PropertyStatusId", column: x => x.PropertyStatusId, principalTable: "PropertyStatusMonthly", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Addresses_BuildingId", table: "Addresses", column: "BuildingId", unique: true); migrationBuilder.CreateIndex( name: "IX_Addresses_CityId", table: "Addresses", column: "CityId"); migrationBuilder.CreateIndex( name: "IX_BuildingAccounts_BuildingId", table: "BuildingAccounts", column: "BuildingId"); migrationBuilder.CreateIndex( name: "IX_BuildingAccounts_PaymentTypeId", table: "BuildingAccounts", column: "PaymentTypeId", unique: true); migrationBuilder.CreateIndex( name: "IX_CompanyOwners_AddressId", table: "CompanyOwners", column: "AddressId", unique: true); migrationBuilder.CreateIndex( name: "IX_IncomingPayments_AccountId", table: "IncomingPayments", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_IncomingPayments_PaymentTypeId", table: "IncomingPayments", column: "PaymentTypeId"); migrationBuilder.CreateIndex( name: "IX_IncomingPayments_PropertyId", table: "IncomingPayments", column: "PropertyId"); migrationBuilder.CreateIndex( name: "IX_OutgoingPayments_AccountId", table: "OutgoingPayments", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_OutgoingPayments_PaymentTypeId", table: "OutgoingPayments", column: "PaymentTypeId"); migrationBuilder.CreateIndex( name: "IX_Owners_AddressId", table: "Owners", column: "AddressId", unique: true); migrationBuilder.CreateIndex( name: "IX_Properties_BuildingId", table: "Properties", column: "BuildingId"); migrationBuilder.CreateIndex( name: "IX_Properties_CompanyOwnerId", table: "Properties", column: "CompanyOwnerId"); migrationBuilder.CreateIndex( name: "IX_Properties_PropertyFloorId", table: "Properties", column: "PropertyFloorId"); migrationBuilder.CreateIndex( name: "IX_Properties_PropertyTypeId", table: "Properties", column: "PropertyTypeId"); migrationBuilder.CreateIndex( name: "IX_Properties_TenantId", table: "Properties", column: "TenantId"); migrationBuilder.CreateIndex( name: "IX_PropertiesOwners_OwnerId", table: "PropertiesOwners", column: "OwnerId"); migrationBuilder.CreateIndex( name: "IX_PropertiesOwners_PropertyId", table: "PropertiesOwners", column: "PropertyId"); migrationBuilder.CreateIndex( name: "IX_PropertyDebtsMonthly_FeeId", table: "PropertyDebtsMonthly", column: "FeeId"); migrationBuilder.CreateIndex( name: "IX_PropertyDebtsMonthly_PropertyId", table: "PropertyDebtsMonthly", column: "PropertyId"); migrationBuilder.CreateIndex( name: "IX_PropertyDebtsMonthly_PropertyStatusId", table: "PropertyDebtsMonthly", column: "PropertyStatusId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "IncomingPayments"); migrationBuilder.DropTable( name: "OutgoingPayments"); migrationBuilder.DropTable( name: "PropertiesOwners"); migrationBuilder.DropTable( name: "PropertyDebtsMonthly"); migrationBuilder.DropTable( name: "BuildingAccounts"); migrationBuilder.DropTable( name: "Owners"); migrationBuilder.DropTable( name: "Fees"); migrationBuilder.DropTable( name: "Properties"); migrationBuilder.DropTable( name: "PropertyStatusMonthly"); migrationBuilder.DropTable( name: "PaymentTypes"); migrationBuilder.DropTable( name: "CompanyOwners"); migrationBuilder.DropTable( name: "PropertyFloors"); migrationBuilder.DropTable( name: "PropertyTypes"); migrationBuilder.DropTable( name: "Tenants"); migrationBuilder.DropTable( name: "Addresses"); migrationBuilder.DropTable( name: "Building"); migrationBuilder.DropTable( name: "Cities"); migrationBuilder.AlterColumn<string>( name: "Name", table: "AspNetUserTokens", type: "nvarchar(128)", maxLength: 128, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(450)"); migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AspNetUserTokens", type: "nvarchar(128)", maxLength: 128, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(450)"); migrationBuilder.AlterColumn<string>( name: "ProviderKey", table: "AspNetUserLogins", type: "nvarchar(128)", maxLength: 128, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(450)"); migrationBuilder.AlterColumn<string>( name: "LoginProvider", table: "AspNetUserLogins", type: "nvarchar(128)", maxLength: 128, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(450)"); } } }
44.805599
120
0.482298
[ "MIT" ]
IvayloFilipov/BuildingManagementSystem
BMS.Data/Migrations/20210606120244_Models-InitialCreate.cs
28,812
C#
using System; using System.Collections.Generic; using Xamarin.Forms; namespace GaslandsHQ.Pages2 { public partial class SelectVehiclePage : ContentPage { public SelectVehiclePage() { InitializeComponent(); } } }
16.4375
56
0.646388
[ "MIT" ]
MysterDru/gaslands-hq
GaslandsHQ/Pages2/SelectVehiclePage.xaml.cs
265
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Trump.ExamAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
42.752193
261
0.553167
[ "MIT" ]
PowerDG/DgERM
aspnet-core/BedTest/Trump.ExamAPI/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs
19,495
C#
namespace RRHHPlanilla { partial class Prestaciones { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // Prestaciones // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1339, 619); this.Name = "Prestaciones"; this.Text = "Prestaciones"; this.ResumeLayout(false); } #endregion } }
30.23913
107
0.54637
[ "MIT" ]
fernanger27/Recurso
RRHHPlanilla/RRHHPlanilla/Prestaciones.Designer.cs
1,393
C#
using System; namespace FullTrustProcess { public abstract class STATaskData { public Delegate Executer { get; } protected STATaskData(Delegate Executer) { this.Executer = Executer; } } }
16.466667
48
0.595142
[ "Apache-2.0" ]
zhuxb711/FileManager
FullTrustProcess/STATaskData.cs
249
C#
// %BANNER_BEGIN% // --------------------------------------------------------------------- // %COPYRIGHT_BEGIN% // // Copyright (c) 2018 Magic Leap, Inc. All Rights Reserved. // Use of this file is governed by the Creator Agreement, located // here: https://id.magicleap.com/creator-terms // // %COPYRIGHT_END% // --------------------------------------------------------------------- // %BANNER_END% using UnityEngine; using UnityEngine.XR.MagicLeap; namespace MagicLeap { /// <summary> /// Updates the transform and sound based on Raycast hit position /// </summary> public class RaycastAudio : MonoBehaviour { #region Private Variables [SerializeField, Tooltip("The reference to the class to handle results from.")] private BaseRaycast _raycast; [SerializeField, Tooltip("The default distance for the cursor when a hit is not detected.")] private float _defaultDistance = 9.0f; [SerializeField, Tooltip("When enabled the cursor will scale down once a certain minimum distance is hit.")] private bool _scaleWhenClose = true; // Stores default color private Color _color; // Stores result of raycast private bool _hit = false; // Stores Renderer component private Renderer _render; #endregion #region Public Properties /// <summary> /// Gettor for _hit. /// </summary> public bool Hit { get { return _hit; } } public float dist = 0.0f; #endregion #region Unity Methods /// <summary> /// Initializes variables and makes sure needed components exist. /// </summary> void Awake() { // Check if the Layer is set to Default and disable any child colliders. if (gameObject.layer == LayerMask.NameToLayer("Default")) { Collider[] colliders = GetComponentsInChildren<Collider>(); // Disable any active colliders. foreach (Collider collider in colliders) { collider.enabled = false; } // Warn user if any colliders had to be disabled. if (colliders.Length > 0) { Debug.LogWarning("Colliders have been disabled on this RaycastVisualizer.\nIf this is undesirable, change this object's layer to something other than Default."); } } if (_raycast == null) { Debug.LogError("Error: RaycastVisualizer._raycast is not set, disabling script."); enabled = false; return; } _render = GetComponent<Renderer>(); if (_render == null) { Debug.LogError("Error: RaycastVisualizer._render is not set, disabling script."); enabled = false; return; } _color = _render.material.color; } #endregion #region Event Handlers /// <summary> /// Callback handler called when raycast has a result. /// Updates the transform an color on the Hit Position and Normal from the assigned object. /// </summary> /// <param name="state"> The state of the raycast result.</param> /// <param name="result"> The hit results (point, normal, distance).</param> /// <param name="confidence"> Confidence value of hit. 0 no hit, 1 sure hit.</param> public void OnRaycastHit(MLWorldRays.MLWorldRaycastResultState state, RaycastHit result, float confidence) { if (state != MLWorldRays.MLWorldRaycastResultState.RequestFailed && state != MLWorldRays.MLWorldRaycastResultState.NoCollision) { //result.distance is the hit distance // Update the cursor position and normal. transform.position = result.point; transform.LookAt(result.normal + result.point); transform.localScale = Vector3.one; dist = result.distance; //check if the raycast is in an unobserved part of room if (! (state == MLWorldRays.MLWorldRaycastResultState.HitObserved)) { } _hit = true; } else { // Case where the raycast went wrong } } #endregion } }
33.875
181
0.541133
[ "MIT" ]
BXB2/cleARsight
cleARsight/Assets/Bobby'sUploads/RaycastAudio.cs
4,609
C#
using System; using System.Globalization; using System.IO; using Android.Graphics; using Android.Graphics.Drawables; using Cirrious.MvvmCross.Converters; namespace WshLst.MonoForAndroid { public class Base64ToBitmapDrawableConverter : MvxBaseValueConverter { public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var bitmapDrawable = (BitmapDrawable) value; using (var ms = new MemoryStream()) { bitmapDrawable.Bitmap.Compress(Bitmap.CompressFormat.Jpeg, 70, ms); return System.Convert.ToBase64String(ms.ToArray()); } } public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var base64 = (string) value; var bytes = System.Convert.FromBase64String(base64); var drawable = BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length); return new BitmapDrawable(drawable); } } }
27.147059
106
0.76273
[ "Apache-2.0" ]
Redth/WshLst
WshLst.MonoForAndroid/NativeConveters.cs
923
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("Smash.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Smash.Tests")] [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("5e1a1e71-dc69-47c8-bbb6-711ceca5edc1")] // 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.567568
84
0.746043
[ "BSD-2-Clause" ]
xoofx/smash
src/Smash.Tests/Properties/AssemblyInfo.cs
1,393
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the workmail-2017-10-01.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.WorkMail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WorkMail.Model.Internal.MarshallTransformations { /// <summary> /// DescribeEmailMonitoringConfiguration Request Marshaller /// </summary> public class DescribeEmailMonitoringConfigurationRequestMarshaller : IMarshaller<IRequest, DescribeEmailMonitoringConfigurationRequest> , 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((DescribeEmailMonitoringConfigurationRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeEmailMonitoringConfigurationRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.WorkMail"); string target = "WorkMailService.DescribeEmailMonitoringConfiguration"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-10-01"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetOrganizationId()) { context.Writer.WritePropertyName("OrganizationId"); context.Writer.Write(publicRequest.OrganizationId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeEmailMonitoringConfigurationRequestMarshaller _instance = new DescribeEmailMonitoringConfigurationRequestMarshaller(); internal static DescribeEmailMonitoringConfigurationRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeEmailMonitoringConfigurationRequestMarshaller Instance { get { return _instance; } } } }
37.300971
187
0.654867
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/WorkMail/Generated/Model/Internal/MarshallTransformations/DescribeEmailMonitoringConfigurationRequestMarshaller.cs
3,842
C#
public interface IActiveRecord { RecordState DirtyState { get; set; } } public static class ActiveRecordExtensions { public static bool Save(this IActiveRecord record) { return true; } }
15.142857
54
0.693396
[ "MIT" ]
dingjimmy/Level
Level/IActiveRecord.cs
212
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.IO; using Microsoft.CSharp; //using Microsoft.JScript; using Microsoft.VisualBasic; using log4net; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenMetaverse; namespace OpenSim.Region.ScriptEngine.Shared.CodeTools { public class Compiler : ICompiler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // * Uses "LSL2Converter" to convert LSL to C# if necessary. // * Compiles C#-code into an assembly // * Returns assembly name ready for AppDomain load. // // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details. // internal enum enumCompileType { lsl = 0, cs = 1, vb = 2, js = 3, yp = 4 } /// <summary> /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs. /// </summary> public int LinesToRemoveOnError = 3; private enumCompileType DefaultCompileLanguage; private bool WriteScriptSourceToDebugFile; private bool CompileWithDebugInformation; private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase); private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase); private string FilePrefix; private string ScriptEnginesPath = null; // mapping between LSL and C# line/column numbers private ICodeConverter LSL_Converter; private List<string> m_warnings = new List<string>(); // private object m_syncy = new object(); private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider(); private static VBCodeProvider VBcodeProvider = new VBCodeProvider(); // private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider(); private static CSharpCodeProvider YPcodeProvider = new CSharpCodeProvider(); // YP is translated into CSharp private static YP2CSConverter YP_Converter = new YP2CSConverter(); // private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files private static UInt64 scriptCompileCounter = 0; // And a counter public IScriptEngine m_scriptEngine; private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps = new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>(); public Compiler(IScriptEngine scriptEngine) { m_scriptEngine = scriptEngine;; ScriptEnginesPath = scriptEngine.ScriptEnginePath; ReadConfig(); } public bool in_startup = true; public void ReadConfig() { // Get some config WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false); CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true); // Get file prefix from scriptengine name and make it file system safe: FilePrefix = "CommonCompiler"; foreach (char c in Path.GetInvalidFileNameChars()) { FilePrefix = FilePrefix.Replace(c, '_'); } // First time we start? Delete old files if (in_startup) { in_startup = false; DeleteOldFiles(); } // Map name and enum type of our supported languages LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs); LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb); LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl); LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js); LanguageMapping.Add(enumCompileType.yp.ToString(), enumCompileType.yp); // Allowed compilers string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl"); AllowedCompilers.Clear(); #if DEBUG m_log.Debug("[Compiler]: Allowed languages: " + allowComp); #endif foreach (string strl in allowComp.Split(',')) { string strlan = strl.Trim(" \t".ToCharArray()).ToLower(); if (!LanguageMapping.ContainsKey(strlan)) { m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\"."); } else { #if DEBUG //m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\"."); #endif } AllowedCompilers.Add(strlan, true); } if (AllowedCompilers.Count == 0) m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!"); // Default language string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower(); // Is this language recognized at all? if (!LanguageMapping.ContainsKey(defaultCompileLanguage)) { m_log.Error("[Compiler]: " + "Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\"."); defaultCompileLanguage = "lsl"; } // Is this language in allow-list? if (!AllowedCompilers.ContainsKey(defaultCompileLanguage)) { m_log.Error("[Compiler]: " + "Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!"); } else { #if DEBUG // m_log.Debug("[Compiler]: " + // "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language."); #endif // LANGUAGE IS IN ALLOW-LIST DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage]; } // We now have an allow-list, a mapping list, and a default language } /// <summary> /// Delete old script files /// </summary> private void DeleteOldFiles() { // CREATE FOLDER IF IT DOESNT EXIST if (!Directory.Exists(ScriptEnginesPath)) { try { Directory.CreateDirectory(ScriptEnginesPath); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString()); } } if (!Directory.Exists(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()))) { try { Directory.CreateDirectory(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString())); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()) + "\": " + ex.ToString()); } } foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_compiled*")) { try { File.Delete(file); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString()); } } foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*")) { try { File.Delete(file); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString()); } } } ////private ICodeCompiler icc = codeProvider.CreateCompiler(); //public string CompileFromFile(string LSOFileName) //{ // switch (Path.GetExtension(LSOFileName).ToLower()) // { // case ".txt": // case ".lsl": // Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS"); // return CompileFromLSLText(File.ReadAllText(LSOFileName)); // case ".cs": // Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS"); // return CompileFromCSText(File.ReadAllText(LSOFileName)); // default: // throw new Exception("Unknown script type."); // } //} public string GetCompilerOutput(string assetID) { return Path.Combine(ScriptEnginesPath, Path.Combine( m_scriptEngine.World.RegionInfo.RegionID.ToString(), FilePrefix + "_compiled_" + assetID + ".dll")); } public string GetCompilerOutput(UUID assetID) { return GetCompilerOutput(assetID.ToString()); } /// <summary> /// Converts script from LSL to CS and calls CompileFromCSText /// </summary> /// <param name="Script">LSL script</param> /// <returns>Filename to .dll assembly</returns> public void PerformScriptCompile(string Script, string asset, UUID ownerUUID, out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap) { linemap = null; m_warnings.Clear(); assembly = GetCompilerOutput(asset); if (!Directory.Exists(ScriptEnginesPath)) { try { Directory.CreateDirectory(ScriptEnginesPath); } catch (Exception) { } } if (!Directory.Exists(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()))) { try { Directory.CreateDirectory(ScriptEnginesPath); } catch (Exception) { } } // Don't recompile if we already have it // Performing 3 file exists tests for every script can still be slow if (File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map")) { // If we have already read this linemap file, then it will be in our dictionary. // Don't build another copy of the dictionary (saves memory) and certainly // don't keep reading the same file from disk multiple times. if (!m_lineMaps.ContainsKey(assembly)) m_lineMaps[assembly] = ReadMapFile(assembly + ".map"); linemap = m_lineMaps[assembly]; return; } if (Script == String.Empty) { throw new Exception("Cannot find script assembly and no script text present"); } enumCompileType language = DefaultCompileLanguage; if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture)) language = enumCompileType.cs; if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture)) { language = enumCompileType.vb; // We need to remove //vb, it won't compile with that Script = Script.Substring(4, Script.Length - 4); } if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture)) language = enumCompileType.lsl; if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture)) language = enumCompileType.js; if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture)) language = enumCompileType.yp; if (!AllowedCompilers.ContainsKey(language.ToString())) { // Not allowed to compile to this language! string errtext = String.Empty; errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!"; throw new Exception(errtext); } if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false) { // Not allowed to compile to this language! string errtext = String.Empty; errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!"; throw new Exception(errtext); } string compileScript = Script; if (language == enumCompileType.lsl) { // Its LSL, convert it to C# LSL_Converter = (ICodeConverter)new CSCodeGenerator(); compileScript = LSL_Converter.Convert(Script); // copy converter warnings into our warnings. foreach (string warning in LSL_Converter.GetWarnings()) { AddWarning(warning); } linemap = ((CSCodeGenerator)LSL_Converter).PositionMap; // Write the linemap to a file and save it in our dictionary for next time. m_lineMaps[assembly] = linemap; WriteMapFile(assembly + ".map", linemap); } if (language == enumCompileType.yp) { // Its YP, convert it to C# compileScript = YP_Converter.Convert(Script); } switch (language) { case enumCompileType.cs: case enumCompileType.lsl: compileScript = CreateCSCompilerScript(compileScript); break; case enumCompileType.vb: compileScript = CreateVBCompilerScript(compileScript); break; // case enumCompileType.js: // compileScript = CreateJSCompilerScript(compileScript); // break; case enumCompileType.yp: compileScript = CreateYPCompilerScript(compileScript); break; } assembly = CompileFromDotNetText(compileScript, language, asset, assembly); return; } public string[] GetWarnings() { return m_warnings.ToArray(); } private void AddWarning(string warning) { if (!m_warnings.Contains(warning)) { m_warnings.Add(warning); } } // private static string CreateJSCompilerScript(string compileScript) // { // compileScript = String.Empty + // "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" + // "package SecondLife {\r\n" + // "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + // compileScript + // "} }\r\n"; // return compileScript; // } private static string CreateCSCompilerScript(string compileScript) { compileScript = String.Empty + "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" + String.Empty + "namespace SecondLife { " + String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + @"public Script() { } " + compileScript + "} }\r\n"; return compileScript; } private static string CreateYPCompilerScript(string compileScript) { compileScript = String.Empty + "using OpenSim.Region.ScriptEngine.Shared.YieldProlog; " + "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" + String.Empty + "namespace SecondLife { " + String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + //@"public Script() { } " + @"static OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP YP=null; " + @"public Script() { YP= new OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP(); } " + compileScript + "} }\r\n"; return compileScript; } private static string CreateVBCompilerScript(string compileScript) { compileScript = String.Empty + "Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " + String.Empty + "NameSpace SecondLife:" + String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass: " + "\r\nPublic Sub New()\r\nEnd Sub: " + compileScript + ":End Class :End Namespace\r\n"; return compileScript; } /// <summary> /// Compile .NET script to .Net assembly (.dll) /// </summary> /// <param name="Script">CS script</param> /// <returns>Filename to .dll assembly</returns> internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly) { string ext = "." + lang.ToString(); // Output assembly name scriptCompileCounter++; try { File.Delete(assembly); } catch (Exception e) // NOTLEGIT - Should be just FileIOException { throw new Exception("Unable to delete old existing " + "script-file before writing new. Compile aborted: " + e.ToString()); } // DEBUG - write source to disk if (WriteScriptSourceToDebugFile) { string srcFileName = FilePrefix + "_source_" + Path.GetFileNameWithoutExtension(assembly) + ext; try { File.WriteAllText(Path.Combine(Path.Combine( ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()), srcFileName), Script); } catch (Exception ex) //NOTLEGIT - Should be just FileIOException { m_log.Error("[Compiler]: Exception while " + "trying to write script source to file \"" + srcFileName + "\": " + ex.ToString()); } } // Do actual compile CompilerParameters parameters = new CompilerParameters(); parameters.IncludeDebugInformation = true; string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.dll")); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll")); if (lang == enumCompileType.yp) { parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll")); } parameters.GenerateExecutable = false; parameters.OutputAssembly = assembly; parameters.IncludeDebugInformation = CompileWithDebugInformation; //parameters.WarningLevel = 1; // Should be 4? parameters.TreatWarningsAsErrors = false; CompilerResults results; switch (lang) { case enumCompileType.vb: results = VBcodeProvider.CompileAssemblyFromSource( parameters, Script); break; case enumCompileType.cs: case enumCompileType.lsl: bool complete = false; bool retried = false; do { lock (CScodeProvider) { results = CScodeProvider.CompileAssemblyFromSource( parameters, Script); } // Deal with an occasional segv in the compiler. // Rarely, if ever, occurs twice in succession. // Line # == 0 and no file name are indications that // this is a native stack trace rather than a normal // error log. if (results.Errors.Count > 0) { if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) && results.Errors[0].Line == 0) { // System.Console.WriteLine("retrying failed compilation"); retried = true; } else { complete = true; } } else { complete = true; } } while (!complete); break; // case enumCompileType.js: // results = JScodeProvider.CompileAssemblyFromSource( // parameters, Script); // break; case enumCompileType.yp: results = YPcodeProvider.CompileAssemblyFromSource( parameters, Script); break; default: throw new Exception("Compiler is not able to recongnize " + "language type \"" + lang.ToString() + "\""); } // Check result // Go through errors // // WARNINGS AND ERRORS // bool hadErrors = false; string errtext = String.Empty; if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { string severity = CompErr.IsWarning ? "Warning" : "Error"; KeyValuePair<int, int> lslPos; // Show 5 errors max, but check entire list for errors if (severity == "Error") { lslPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]); string text = CompErr.ErrorText; // Use LSL type names if (lang == enumCompileType.lsl) text = ReplaceTypes(CompErr.ErrorText); // The Second Life viewer's script editor begins // countingn lines and columns at 0, so we subtract 1. errtext += String.Format("({0},{1}): {4} {2}: {3}\n", lslPos.Key - 1, lslPos.Value - 1, CompErr.ErrorNumber, text, severity); hadErrors = true; } } } if (hadErrors) { throw new Exception(errtext); } // On today's highly asynchronous systems, the result of // the compile may not be immediately apparent. Wait a // reasonable amount of time before giving up on it. if (!File.Exists(assembly)) { for (int i = 0; i < 20 && !File.Exists(assembly); i++) { System.Threading.Thread.Sleep(250); } // One final chance... if (!File.Exists(assembly)) { errtext = String.Empty; errtext += "No compile error. But not able to locate compiled file."; throw new Exception(errtext); } } // m_log.DebugFormat("[Compiler] Compiled new assembly "+ // "for {0}", asset); // Because windows likes to perform exclusive locks, we simply // write out a textual representation of the file here // // Read the binary file into a buffer // FileInfo fi = new FileInfo(assembly); if (fi == null) { errtext = String.Empty; errtext += "No compile error. But not able to stat file."; throw new Exception(errtext); } Byte[] data = new Byte[fi.Length]; try { FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read); fs.Read(data, 0, data.Length); fs.Close(); } catch (Exception) { errtext = String.Empty; errtext += "No compile error. But not able to open file."; throw new Exception(errtext); } // Convert to base64 // string filetext = System.Convert.ToBase64String(data); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] buf = enc.GetBytes(filetext); FileStream sfs = File.Create(assembly + ".text"); sfs.Write(buf, 0, buf.Length); sfs.Close(); return assembly; } private class kvpSorter : IComparer<KeyValuePair<int, int>> { public int Compare(KeyValuePair<int, int> a, KeyValuePair<int, int> b) { return a.Key.CompareTo(b.Key); } } public static KeyValuePair<int, int> FindErrorPosition(int line, int col, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap) { if (positionMap == null || positionMap.Count == 0) return new KeyValuePair<int, int>(line, col); KeyValuePair<int, int> ret = new KeyValuePair<int, int>(); if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col), out ret)) return ret; List<KeyValuePair<int, int>> sorted = new List<KeyValuePair<int, int>>(positionMap.Keys); sorted.Sort(new kvpSorter()); int l = 1; int c = 1; foreach (KeyValuePair<int, int> cspos in sorted) { if (cspos.Key >= line) { if (cspos.Key > line) return new KeyValuePair<int, int>(l, c); if (cspos.Value > col) return new KeyValuePair<int, int>(l, c); c = cspos.Value; if (c == 0) c++; } else { l = cspos.Key; } } return new KeyValuePair<int, int>(l, c); } string ReplaceTypes(string message) { message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString", "string"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger", "integer"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat", "float"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list", "list"); return message; } private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap) { string mapstring = String.Empty; foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap) { KeyValuePair<int, int> k = kvp.Key; KeyValuePair<int, int> v = kvp.Value; mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value); } System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] mapbytes = enc.GetBytes(mapstring); FileStream mfs = File.Create(filename); mfs.Write(mapbytes, 0, mapbytes.Length); mfs.Close(); } private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename) { Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap; try { StreamReader r = File.OpenText(filename); linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>(); string line; while ((line = r.ReadLine()) != null) { String[] parts = line.Split(new Char[] { ',' }); int kk = System.Convert.ToInt32(parts[0]); int kv = System.Convert.ToInt32(parts[1]); int vk = System.Convert.ToInt32(parts[2]); int vv = System.Convert.ToInt32(parts[3]); KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv); KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv); linemap[k] = v; } } catch { linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>(); } return linemap; } } }
41.125301
222
0.528417
[ "BSD-3-Clause" ]
N3X15/VoxelSim
OpenSim/Region/ScriptEngine/Shared/CodeTools/Compiler.cs
34,134
C#
namespace PhotoDealer.Web.Tests { using System; using System.Transactions; using Microsoft.VisualStudio.TestTools.UnitTesting; using PhotoDealer.Data; using PhotoDealer.Data.Models; [TestClass] public class CategoryGroupRepositoryTests { private static TransactionScope tran; [TestInitialize] public void TestInit() { tran = new TransactionScope(); } [TestCleanup] public void TestCleanUp() { tran.Dispose(); } [TestMethod] public void AddCategoryGroup_WhenGroupIsValid_ShouldAddToDb() { var context = new AppDbContext(); var data = new PhotoDealerData(context); var categoryGroup = new CategoryGroup() { GroupName = "Test category group", }; data.CategoryGroups.Add(categoryGroup); data.SaveChanges(); var categoryGroupInDb = context.CategoryGroups.Find(categoryGroup.CategoryGroupId); Assert.IsNotNull(categoryGroupInDb); Assert.AreEqual(categoryGroup.GroupName, categoryGroupInDb.GroupName); } [TestMethod] public void FindCategoryGroup_WhenCategoryGroupInDb_ShouldReturnCategoryGroup() { var context = new AppDbContext(); var data = new PhotoDealerData(context); var categoryGroup = new CategoryGroup() { GroupName = "Test category group", }; context.CategoryGroups.Add(categoryGroup); data.SaveChanges(); var categoryGroupInDb = data.CategoryGroups.GetById(categoryGroup.CategoryGroupId); Assert.IsNotNull(categoryGroupInDb); Assert.AreEqual(categoryGroup.GroupName, categoryGroupInDb.GroupName); } [TestMethod] public void DeleteCategoryGroup_WhenCategoryGroupInDb_ShouldDeletecategoryGroup() { var context = new AppDbContext(); var data = new PhotoDealerData(context); var categoryGroup = new CategoryGroup() { GroupName = "Test category group", }; context.CategoryGroups.Add(categoryGroup); data.SaveChanges(); data.CategoryGroups.Delete(categoryGroup.CategoryGroupId); var categoryGroupInDb = context.CategoryGroups.Find(categoryGroup.CategoryGroupId); Assert.IsNotNull(categoryGroupInDb); } [TestMethod] public void UpdateCategoryGroupName_WhenCategoryGroupInDb_ShouldUpdateName() { var context = new AppDbContext(); var data = new PhotoDealerData(context); var categoryGroup = new CategoryGroup() { GroupName = "Test category group", }; string newName = "Updated Test category group"; context.CategoryGroups.Add(categoryGroup); data.SaveChanges(); var categoryGroupInDb = context.CategoryGroups.Find(categoryGroup.CategoryGroupId); categoryGroupInDb.GroupName = newName; data.CategoryGroups.Update(categoryGroupInDb); categoryGroupInDb = data.CategoryGroups.GetById(categoryGroup.CategoryGroupId); Assert.IsNotNull(categoryGroupInDb); Assert.AreEqual(newName, categoryGroupInDb.GroupName); } } }
30.321739
95
0.614568
[ "MIT" ]
StefanMihaylov/PhotoDealer
Source/Test/PhotoDealer.Web.Tests/CategoryGroupRepositoryTests.cs
3,489
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelButton : MonoBehaviour { public int sceneToLoad; public void LoadLevel() { SceneManager.LoadScene(sceneToLoad); } }
18.266667
44
0.744526
[ "MIT" ]
JoakimKar/Slash-Runner
Assets/Scripts/LevelButton.cs
274
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace GChatAPI.Data { public class Message { public int Id { get; set; } [Required] public string? Text { get; set; } [Required] public DateTime Timestamp { get; set; } [Required] public int ChatId { get; set; } public Chat? Chat { get; set; } [Required] public string? SenderId { get; set; } public User? Sender { get; set; } } }
21.392857
47
0.580968
[ "MIT" ]
geuermax/GChat
src/GChat/Data/Models/Message.cs
601
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #pragma warning disable 1591 namespace EIDSS.Reports.Document.Lim.ContainerContent { /// <summary> ///Represents a strongly typed in-memory cache of data. ///</summary> [global::System.Serializable()] [global::System.ComponentModel.DesignerCategoryAttribute("code")] [global::System.ComponentModel.ToolboxItem(true)] [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")] [global::System.Xml.Serialization.XmlRootAttribute("ContainerContentDataSet")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")] public partial class ContainerContentDataSet : global::System.Data.DataSet { private spRepLimContainerContentDataTable tablespRepLimContainerContent; private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public ContainerContentDataSet() { this.BeginInit(); this.InitClass(); global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); base.Tables.CollectionChanged += schemaChangedHandler; base.Relations.CollectionChanged += schemaChangedHandler; this.EndInit(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected ContainerContentDataSet(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : base(info, context, false) { if ((this.IsBinarySerialized(info, context) == true)) { this.InitVars(false); global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); this.Tables.CollectionChanged += schemaChangedHandler1; this.Relations.CollectionChanged += schemaChangedHandler1; return; } string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { global::System.Data.DataSet ds = new global::System.Data.DataSet(); ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); if ((ds.Tables["spRepLimContainerContent"] != null)) { base.Tables.Add(new spRepLimContainerContentDataTable(ds.Tables["spRepLimContainerContent"])); } this.DataSetName = ds.DataSetName; this.Prefix = ds.Prefix; this.Namespace = ds.Namespace; this.Locale = ds.Locale; this.CaseSensitive = ds.CaseSensitive; this.EnforceConstraints = ds.EnforceConstraints; this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); this.InitVars(); } else { this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); } this.GetSerializationData(info, context); global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); base.Tables.CollectionChanged += schemaChangedHandler; this.Relations.CollectionChanged += schemaChangedHandler; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] [global::System.ComponentModel.Browsable(false)] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] public spRepLimContainerContentDataTable spRepLimContainerContent { get { return this.tablespRepLimContainerContent; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] [global::System.ComponentModel.BrowsableAttribute(true)] [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)] public override global::System.Data.SchemaSerializationMode SchemaSerializationMode { get { return this._schemaSerializationMode; } set { this._schemaSerializationMode = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] public new global::System.Data.DataTableCollection Tables { get { return base.Tables; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] public new global::System.Data.DataRelationCollection Relations { get { return base.Relations; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override void InitializeDerivedDataSet() { this.BeginInit(); this.InitClass(); this.EndInit(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public override global::System.Data.DataSet Clone() { ContainerContentDataSet cln = ((ContainerContentDataSet)(base.Clone())); cln.InitVars(); cln.SchemaSerializationMode = this.SchemaSerializationMode; return cln; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override bool ShouldSerializeTables() { return false; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override bool ShouldSerializeRelations() { return false; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) { if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { this.Reset(); global::System.Data.DataSet ds = new global::System.Data.DataSet(); ds.ReadXml(reader); if ((ds.Tables["spRepLimContainerContent"] != null)) { base.Tables.Add(new spRepLimContainerContentDataTable(ds.Tables["spRepLimContainerContent"])); } this.DataSetName = ds.DataSetName; this.Prefix = ds.Prefix; this.Namespace = ds.Namespace; this.Locale = ds.Locale; this.CaseSensitive = ds.CaseSensitive; this.EnforceConstraints = ds.EnforceConstraints; this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); this.InitVars(); } else { this.ReadXml(reader); this.InitVars(); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() { global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream(); this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null)); stream.Position = 0; return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] internal void InitVars() { this.InitVars(true); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] internal void InitVars(bool initTable) { this.tablespRepLimContainerContent = ((spRepLimContainerContentDataTable)(base.Tables["spRepLimContainerContent"])); if ((initTable == true)) { if ((this.tablespRepLimContainerContent != null)) { this.tablespRepLimContainerContent.InitVars(); } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private void InitClass() { this.DataSetName = "ContainerContentDataSet"; this.Prefix = ""; this.Namespace = "http://tempuri.org/ContainerContentDataSet.xsd"; this.EnforceConstraints = true; this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; this.tablespRepLimContainerContent = new spRepLimContainerContentDataTable(); base.Tables.Add(this.tablespRepLimContainerContent); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private bool ShouldSerializespRepLimContainerContent() { return false; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) { if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) { this.InitVars(); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { ContainerContentDataSet ds = new ContainerContentDataSet(); global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); any.Namespace = ds.Namespace; sequence.Items.Add(any); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte())); ) { ; } if ((s1.Position == s1.Length)) { return type; } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return type; } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public delegate void spRepLimContainerContentRowChangeEventHandler(object sender, spRepLimContainerContentRowChangeEvent e); /// <summary> ///Represents the strongly named DataTable class. ///</summary> [global::System.Serializable()] [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")] public partial class spRepLimContainerContentDataTable : global::System.Data.TypedTableBase<spRepLimContainerContentRow> { private global::System.Data.DataColumn columnFreezerBarcode; private global::System.Data.DataColumn columnFreezerName; private global::System.Data.DataColumn columnFreezerNote; private global::System.Data.DataColumn columnFreezerType; private global::System.Data.DataColumn columnSubDivisionBarcode; private global::System.Data.DataColumn columnSubDivisionName; private global::System.Data.DataColumn columnSubDivisionNote; private global::System.Data.DataColumn columnSubDivisionType; private global::System.Data.DataColumn columnContainerBarcode; private global::System.Data.DataColumn columnContainerID; private global::System.Data.DataColumn columnFieldID; private global::System.Data.DataColumn columnMaterialType; private global::System.Data.DataColumn columnPath; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public spRepLimContainerContentDataTable() { this.TableName = "spRepLimContainerContent"; this.BeginInit(); this.InitClass(); this.EndInit(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] internal spRepLimContainerContentDataTable(global::System.Data.DataTable table) { this.TableName = table.TableName; if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { this.CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { this.Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { this.Namespace = table.Namespace; } this.Prefix = table.Prefix; this.MinimumCapacity = table.MinimumCapacity; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected spRepLimContainerContentDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.InitVars(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn FreezerBarcodeColumn { get { return this.columnFreezerBarcode; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn FreezerNameColumn { get { return this.columnFreezerName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn FreezerNoteColumn { get { return this.columnFreezerNote; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn FreezerTypeColumn { get { return this.columnFreezerType; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn SubDivisionBarcodeColumn { get { return this.columnSubDivisionBarcode; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn SubDivisionNameColumn { get { return this.columnSubDivisionName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn SubDivisionNoteColumn { get { return this.columnSubDivisionNote; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn SubDivisionTypeColumn { get { return this.columnSubDivisionType; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn ContainerBarcodeColumn { get { return this.columnContainerBarcode; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn ContainerIDColumn { get { return this.columnContainerID; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn FieldIDColumn { get { return this.columnFieldID; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn MaterialTypeColumn { get { return this.columnMaterialType; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataColumn PathColumn { get { return this.columnPath; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] [global::System.ComponentModel.Browsable(false)] public int Count { get { return this.Rows.Count; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public spRepLimContainerContentRow this[int index] { get { return ((spRepLimContainerContentRow)(this.Rows[index])); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public event spRepLimContainerContentRowChangeEventHandler spRepLimContainerContentRowChanging; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public event spRepLimContainerContentRowChangeEventHandler spRepLimContainerContentRowChanged; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public event spRepLimContainerContentRowChangeEventHandler spRepLimContainerContentRowDeleting; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public event spRepLimContainerContentRowChangeEventHandler spRepLimContainerContentRowDeleted; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void AddspRepLimContainerContentRow(spRepLimContainerContentRow row) { this.Rows.Add(row); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public spRepLimContainerContentRow AddspRepLimContainerContentRow(string FreezerBarcode, string FreezerName, string FreezerNote, string FreezerType, string SubDivisionBarcode, string SubDivisionName, string SubDivisionNote, string SubDivisionType, string ContainerBarcode, long ContainerID, string FieldID, string MaterialType, string Path) { spRepLimContainerContentRow rowspRepLimContainerContentRow = ((spRepLimContainerContentRow)(this.NewRow())); object[] columnValuesArray = new object[] { FreezerBarcode, FreezerName, FreezerNote, FreezerType, SubDivisionBarcode, SubDivisionName, SubDivisionNote, SubDivisionType, ContainerBarcode, ContainerID, FieldID, MaterialType, Path}; rowspRepLimContainerContentRow.ItemArray = columnValuesArray; this.Rows.Add(rowspRepLimContainerContentRow); return rowspRepLimContainerContentRow; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public override global::System.Data.DataTable Clone() { spRepLimContainerContentDataTable cln = ((spRepLimContainerContentDataTable)(base.Clone())); cln.InitVars(); return cln; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override global::System.Data.DataTable CreateInstance() { return new spRepLimContainerContentDataTable(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] internal void InitVars() { this.columnFreezerBarcode = base.Columns["FreezerBarcode"]; this.columnFreezerName = base.Columns["FreezerName"]; this.columnFreezerNote = base.Columns["FreezerNote"]; this.columnFreezerType = base.Columns["FreezerType"]; this.columnSubDivisionBarcode = base.Columns["SubDivisionBarcode"]; this.columnSubDivisionName = base.Columns["SubDivisionName"]; this.columnSubDivisionNote = base.Columns["SubDivisionNote"]; this.columnSubDivisionType = base.Columns["SubDivisionType"]; this.columnContainerBarcode = base.Columns["ContainerBarcode"]; this.columnContainerID = base.Columns["ContainerID"]; this.columnFieldID = base.Columns["FieldID"]; this.columnMaterialType = base.Columns["MaterialType"]; this.columnPath = base.Columns["Path"]; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private void InitClass() { this.columnFreezerBarcode = new global::System.Data.DataColumn("FreezerBarcode", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnFreezerBarcode); this.columnFreezerName = new global::System.Data.DataColumn("FreezerName", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnFreezerName); this.columnFreezerNote = new global::System.Data.DataColumn("FreezerNote", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnFreezerNote); this.columnFreezerType = new global::System.Data.DataColumn("FreezerType", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnFreezerType); this.columnSubDivisionBarcode = new global::System.Data.DataColumn("SubDivisionBarcode", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnSubDivisionBarcode); this.columnSubDivisionName = new global::System.Data.DataColumn("SubDivisionName", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnSubDivisionName); this.columnSubDivisionNote = new global::System.Data.DataColumn("SubDivisionNote", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnSubDivisionNote); this.columnSubDivisionType = new global::System.Data.DataColumn("SubDivisionType", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnSubDivisionType); this.columnContainerBarcode = new global::System.Data.DataColumn("ContainerBarcode", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnContainerBarcode); this.columnContainerID = new global::System.Data.DataColumn("ContainerID", typeof(long), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnContainerID); this.columnFieldID = new global::System.Data.DataColumn("FieldID", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnFieldID); this.columnMaterialType = new global::System.Data.DataColumn("MaterialType", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnMaterialType); this.columnPath = new global::System.Data.DataColumn("Path", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnPath); this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] { this.columnContainerID}, false)); this.columnFreezerType.ReadOnly = true; this.columnSubDivisionType.ReadOnly = true; this.columnContainerID.Unique = true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public spRepLimContainerContentRow NewspRepLimContainerContentRow() { return ((spRepLimContainerContentRow)(this.NewRow())); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) { return new spRepLimContainerContentRow(builder); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override global::System.Type GetRowType() { return typeof(spRepLimContainerContentRow); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((this.spRepLimContainerContentRowChanged != null)) { this.spRepLimContainerContentRowChanged(this, new spRepLimContainerContentRowChangeEvent(((spRepLimContainerContentRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((this.spRepLimContainerContentRowChanging != null)) { this.spRepLimContainerContentRowChanging(this, new spRepLimContainerContentRowChangeEvent(((spRepLimContainerContentRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((this.spRepLimContainerContentRowDeleted != null)) { this.spRepLimContainerContentRowDeleted(this, new spRepLimContainerContentRowChangeEvent(((spRepLimContainerContentRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) { base.OnRowDeleting(e); if ((this.spRepLimContainerContentRowDeleting != null)) { this.spRepLimContainerContentRowDeleting(this, new spRepLimContainerContentRowChangeEvent(((spRepLimContainerContentRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void RemovespRepLimContainerContentRow(spRepLimContainerContentRow row) { this.Rows.Remove(row); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); ContainerContentDataSet ds = new ContainerContentDataSet(); global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "spRepLimContainerContentDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte())); ) { ; } if ((s1.Position == s1.Length)) { return type; } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return type; } } /// <summary> ///Represents strongly named DataRow class. ///</summary> public partial class spRepLimContainerContentRow : global::System.Data.DataRow { private spRepLimContainerContentDataTable tablespRepLimContainerContent; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] internal spRepLimContainerContentRow(global::System.Data.DataRowBuilder rb) : base(rb) { this.tablespRepLimContainerContent = ((spRepLimContainerContentDataTable)(this.Table)); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string FreezerBarcode { get { try { return ((string)(this[this.tablespRepLimContainerContent.FreezerBarcodeColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'FreezerBarcode\' in table \'spRepLimContainerContent\' is DBNu" + "ll.", e); } } set { this[this.tablespRepLimContainerContent.FreezerBarcodeColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string FreezerName { get { try { return ((string)(this[this.tablespRepLimContainerContent.FreezerNameColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'FreezerName\' in table \'spRepLimContainerContent\' is DBNull." + "", e); } } set { this[this.tablespRepLimContainerContent.FreezerNameColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string FreezerNote { get { try { return ((string)(this[this.tablespRepLimContainerContent.FreezerNoteColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'FreezerNote\' in table \'spRepLimContainerContent\' is DBNull." + "", e); } } set { this[this.tablespRepLimContainerContent.FreezerNoteColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string FreezerType { get { try { return ((string)(this[this.tablespRepLimContainerContent.FreezerTypeColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'FreezerType\' in table \'spRepLimContainerContent\' is DBNull." + "", e); } } set { this[this.tablespRepLimContainerContent.FreezerTypeColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string SubDivisionBarcode { get { try { return ((string)(this[this.tablespRepLimContainerContent.SubDivisionBarcodeColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'SubDivisionBarcode\' in table \'spRepLimContainerContent\' is " + "DBNull.", e); } } set { this[this.tablespRepLimContainerContent.SubDivisionBarcodeColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string SubDivisionName { get { try { return ((string)(this[this.tablespRepLimContainerContent.SubDivisionNameColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'SubDivisionName\' in table \'spRepLimContainerContent\' is DBN" + "ull.", e); } } set { this[this.tablespRepLimContainerContent.SubDivisionNameColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string SubDivisionNote { get { try { return ((string)(this[this.tablespRepLimContainerContent.SubDivisionNoteColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'SubDivisionNote\' in table \'spRepLimContainerContent\' is DBN" + "ull.", e); } } set { this[this.tablespRepLimContainerContent.SubDivisionNoteColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string SubDivisionType { get { try { return ((string)(this[this.tablespRepLimContainerContent.SubDivisionTypeColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'SubDivisionType\' in table \'spRepLimContainerContent\' is DBN" + "ull.", e); } } set { this[this.tablespRepLimContainerContent.SubDivisionTypeColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string ContainerBarcode { get { try { return ((string)(this[this.tablespRepLimContainerContent.ContainerBarcodeColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'ContainerBarcode\' in table \'spRepLimContainerContent\' is DB" + "Null.", e); } } set { this[this.tablespRepLimContainerContent.ContainerBarcodeColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public long ContainerID { get { try { return ((long)(this[this.tablespRepLimContainerContent.ContainerIDColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'ContainerID\' in table \'spRepLimContainerContent\' is DBNull." + "", e); } } set { this[this.tablespRepLimContainerContent.ContainerIDColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string FieldID { get { try { return ((string)(this[this.tablespRepLimContainerContent.FieldIDColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'FieldID\' in table \'spRepLimContainerContent\' is DBNull.", e); } } set { this[this.tablespRepLimContainerContent.FieldIDColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string MaterialType { get { try { return ((string)(this[this.tablespRepLimContainerContent.MaterialTypeColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'MaterialType\' in table \'spRepLimContainerContent\' is DBNull" + ".", e); } } set { this[this.tablespRepLimContainerContent.MaterialTypeColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public string Path { get { try { return ((string)(this[this.tablespRepLimContainerContent.PathColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'Path\' in table \'spRepLimContainerContent\' is DBNull.", e); } } set { this[this.tablespRepLimContainerContent.PathColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsFreezerBarcodeNull() { return this.IsNull(this.tablespRepLimContainerContent.FreezerBarcodeColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetFreezerBarcodeNull() { this[this.tablespRepLimContainerContent.FreezerBarcodeColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsFreezerNameNull() { return this.IsNull(this.tablespRepLimContainerContent.FreezerNameColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetFreezerNameNull() { this[this.tablespRepLimContainerContent.FreezerNameColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsFreezerNoteNull() { return this.IsNull(this.tablespRepLimContainerContent.FreezerNoteColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetFreezerNoteNull() { this[this.tablespRepLimContainerContent.FreezerNoteColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsFreezerTypeNull() { return this.IsNull(this.tablespRepLimContainerContent.FreezerTypeColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetFreezerTypeNull() { this[this.tablespRepLimContainerContent.FreezerTypeColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsSubDivisionBarcodeNull() { return this.IsNull(this.tablespRepLimContainerContent.SubDivisionBarcodeColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetSubDivisionBarcodeNull() { this[this.tablespRepLimContainerContent.SubDivisionBarcodeColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsSubDivisionNameNull() { return this.IsNull(this.tablespRepLimContainerContent.SubDivisionNameColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetSubDivisionNameNull() { this[this.tablespRepLimContainerContent.SubDivisionNameColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsSubDivisionNoteNull() { return this.IsNull(this.tablespRepLimContainerContent.SubDivisionNoteColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetSubDivisionNoteNull() { this[this.tablespRepLimContainerContent.SubDivisionNoteColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsSubDivisionTypeNull() { return this.IsNull(this.tablespRepLimContainerContent.SubDivisionTypeColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetSubDivisionTypeNull() { this[this.tablespRepLimContainerContent.SubDivisionTypeColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsContainerBarcodeNull() { return this.IsNull(this.tablespRepLimContainerContent.ContainerBarcodeColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetContainerBarcodeNull() { this[this.tablespRepLimContainerContent.ContainerBarcodeColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsContainerIDNull() { return this.IsNull(this.tablespRepLimContainerContent.ContainerIDColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetContainerIDNull() { this[this.tablespRepLimContainerContent.ContainerIDColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsFieldIDNull() { return this.IsNull(this.tablespRepLimContainerContent.FieldIDColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetFieldIDNull() { this[this.tablespRepLimContainerContent.FieldIDColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsMaterialTypeNull() { return this.IsNull(this.tablespRepLimContainerContent.MaterialTypeColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetMaterialTypeNull() { this[this.tablespRepLimContainerContent.MaterialTypeColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool IsPathNull() { return this.IsNull(this.tablespRepLimContainerContent.PathColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public void SetPathNull() { this[this.tablespRepLimContainerContent.PathColumn] = global::System.Convert.DBNull; } } /// <summary> ///Row event argument class ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public class spRepLimContainerContentRowChangeEvent : global::System.EventArgs { private spRepLimContainerContentRow eventRow; private global::System.Data.DataRowAction eventAction; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public spRepLimContainerContentRowChangeEvent(spRepLimContainerContentRow row, global::System.Data.DataRowAction action) { this.eventRow = row; this.eventAction = action; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public spRepLimContainerContentRow Row { get { return this.eventRow; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public global::System.Data.DataRowAction Action { get { return this.eventAction; } } } } } namespace EIDSS.Reports.Document.Lim.ContainerContent.ContainerContentDataSetTableAdapters { /// <summary> ///Represents the connection and commands used to retrieve and save data. ///</summary> [global::System.ComponentModel.DesignerCategoryAttribute("code")] [global::System.ComponentModel.ToolboxItem(true)] [global::System.ComponentModel.DataObjectAttribute(true)] [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + ", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] public partial class spRepLimContainerContentTableAdapter : global::System.ComponentModel.Component { private global::System.Data.SqlClient.SqlDataAdapter _adapter; private global::System.Data.SqlClient.SqlConnection _connection; private global::System.Data.SqlClient.SqlCommand[] _commandCollection; private bool _clearBeforeFill; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public spRepLimContainerContentTableAdapter() { this.ClearBeforeFill = true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private global::System.Data.SqlClient.SqlDataAdapter Adapter { get { if ((this._adapter == null)) { this.InitAdapter(); } return this._adapter; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] internal global::System.Data.SqlClient.SqlConnection Connection { get { if ((this._connection == null)) { this.InitConnection(); } return this._connection; } set { this._connection = value; if ((this.Adapter.InsertCommand != null)) { this.Adapter.InsertCommand.Connection = value; } if ((this.Adapter.DeleteCommand != null)) { this.Adapter.DeleteCommand.Connection = value; } if ((this.Adapter.UpdateCommand != null)) { this.Adapter.UpdateCommand.Connection = value; } for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { if ((this.CommandCollection[i] != null)) { ((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value; } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] protected global::System.Data.SqlClient.SqlCommand[] CommandCollection { get { if ((this._commandCollection == null)) { this.InitCommandCollection(); } return this._commandCollection; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] public bool ClearBeforeFill { get { return this._clearBeforeFill; } set { this._clearBeforeFill = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private void InitAdapter() { this._adapter = new global::System.Data.SqlClient.SqlDataAdapter(); global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping(); tableMapping.SourceTable = "Table"; tableMapping.DataSetTable = "spRepLimContainerContent"; tableMapping.ColumnMappings.Add("FreezerBarcode", "FreezerBarcode"); tableMapping.ColumnMappings.Add("FreezerName", "FreezerName"); tableMapping.ColumnMappings.Add("FreezerNote", "FreezerNote"); tableMapping.ColumnMappings.Add("FreezerType", "FreezerType"); tableMapping.ColumnMappings.Add("SubDivisionBarcode", "SubDivisionBarcode"); tableMapping.ColumnMappings.Add("SubDivisionName", "SubDivisionName"); tableMapping.ColumnMappings.Add("SubDivisionNote", "SubDivisionNote"); tableMapping.ColumnMappings.Add("SubDivisionType", "SubDivisionType"); tableMapping.ColumnMappings.Add("ContainerBarcode", "ContainerBarcode"); tableMapping.ColumnMappings.Add("ContainerID", "ContainerID"); tableMapping.ColumnMappings.Add("FieldID", "FieldID"); tableMapping.ColumnMappings.Add("MaterialType", "MaterialType"); tableMapping.ColumnMappings.Add("Path", "Path"); this._adapter.TableMappings.Add(tableMapping); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private void InitConnection() { this._connection = new global::System.Data.SqlClient.SqlConnection(); this._connection.ConnectionString = global::EIDSS.Reports.Properties.Settings.Default.eidss_v6ConnectionString; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] private void InitCommandCollection() { this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); this._commandCollection[0].Connection = this.Connection; this._commandCollection[0].CommandText = "dbo.spRepLimContainerContent"; this._commandCollection[0].CommandType = global::System.Data.CommandType.StoredProcedure; this._commandCollection[0].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@RETURN_VALUE", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.ReturnValue, 10, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._commandCollection[0].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@LangID", global::System.Data.SqlDbType.NVarChar, 10, global::System.Data.ParameterDirection.Input, 0, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._commandCollection[0].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@ContID", global::System.Data.SqlDbType.BigInt, 8, global::System.Data.ParameterDirection.Input, 19, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._commandCollection[0].Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@FreezerID", global::System.Data.SqlDbType.BigInt, 8, global::System.Data.ParameterDirection.Input, 19, 0, null, global::System.Data.DataRowVersion.Current, false, null, "", "", "")); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)] public virtual int Fill(ContainerContentDataSet.spRepLimContainerContentDataTable dataTable, string LangID, global::System.Nullable<long> ContID, global::System.Nullable<long> FreezerID) { this.Adapter.SelectCommand = this.CommandCollection[0]; if ((LangID == null)) { this.Adapter.SelectCommand.Parameters[1].Value = global::System.DBNull.Value; } else { this.Adapter.SelectCommand.Parameters[1].Value = ((string)(LangID)); } if ((ContID.HasValue == true)) { this.Adapter.SelectCommand.Parameters[2].Value = ((long)(ContID.Value)); } else { this.Adapter.SelectCommand.Parameters[2].Value = global::System.DBNull.Value; } if ((FreezerID.HasValue == true)) { this.Adapter.SelectCommand.Parameters[3].Value = ((long)(FreezerID.Value)); } else { this.Adapter.SelectCommand.Parameters[3].Value = global::System.DBNull.Value; } if ((this.ClearBeforeFill == true)) { dataTable.Clear(); } int returnValue = this.Adapter.Fill(dataTable); return returnValue; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)] public virtual ContainerContentDataSet.spRepLimContainerContentDataTable GetData(string LangID, global::System.Nullable<long> ContID, global::System.Nullable<long> FreezerID) { this.Adapter.SelectCommand = this.CommandCollection[0]; if ((LangID == null)) { this.Adapter.SelectCommand.Parameters[1].Value = global::System.DBNull.Value; } else { this.Adapter.SelectCommand.Parameters[1].Value = ((string)(LangID)); } if ((ContID.HasValue == true)) { this.Adapter.SelectCommand.Parameters[2].Value = ((long)(ContID.Value)); } else { this.Adapter.SelectCommand.Parameters[2].Value = global::System.DBNull.Value; } if ((FreezerID.HasValue == true)) { this.Adapter.SelectCommand.Parameters[3].Value = ((long)(FreezerID.Value)); } else { this.Adapter.SelectCommand.Parameters[3].Value = global::System.DBNull.Value; } ContainerContentDataSet.spRepLimContainerContentDataTable dataTable = new ContainerContentDataSet.spRepLimContainerContentDataTable(); this.Adapter.Fill(dataTable); return dataTable; } } } #pragma warning restore 1591
58.255513
355
0.599235
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6/vb/EIDSS/EIDSS.Reports/Document/Lim/ContainerContent/ContainerContentDataSet.Designer.cs
76,608
C#
using System; using System.ComponentModel; using CoreGraphics; using Xamarin.PropertyEditing.ViewModels; namespace Xamarin.PropertyEditing.Mac { internal class SolidColorBrushEditorViewController : NotifyingViewController<BrushPropertyViewModel> { public SolidColorBrushEditorViewController (IHostResourceProvider hostResources) { if (hostResources == null) throw new ArgumentNullException (nameof (hostResources)); this.hostResources = hostResources; PreferredContentSize = new CGSize (PreferredContentSizeWidth, PreferredContentSizeHeight); } public override void OnPropertyChanged (object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof (BrushPropertyViewModel.Solid): if (this.brushEditor != null) this.brushEditor.ViewModel = ViewModel.Solid; break; case nameof (BrushPropertyViewModel.Value): if (this.brushEditor != null) this.brushEditor.ViewModel = ViewModel.Solid; break; } } public override void OnViewModelChanged (BrushPropertyViewModel oldModel) { if (this.brushEditor != null) this.brushEditor.ViewModel = ViewModel?.Solid; } public override void ViewDidLoad () { base.ViewDidLoad (); if (ViewModel != null) this.brushEditor.ViewModel = ViewModel?.Solid; } public override void LoadView () { View = this.brushEditor = new SolidColorBrushEditor (this.hostResources) { ViewModel = ViewModel?.Solid }; } private readonly IHostResourceProvider hostResources; private SolidColorBrushEditor brushEditor; } }
26.745763
93
0.748416
[ "MIT" ]
netonjm/Xamarin.PropertyEditing
Xamarin.PropertyEditing.Mac/Controls/Custom/SolidColorBrushEditorViewController.cs
1,578
C#
// Copyright (c) 2016 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/ // Licensed under MIT licence. See License.txt in the project root for license information. using System; using System.ComponentModel.DataAnnotations; using System.Linq; namespace ServiceLayer.BookServices.QueryObjects { public enum BooksFilterBy { [Display(Name = "All")] NoFilter = 0, [Display(Name = "By Votes...")] ByVotes, [Display(Name = "By Year published...")] ByPublicationYear } public static class BookListDtoFilter { public const string AllBooksNotPublishedString = "Coming Soon"; public static IQueryable<BookListDto> FilterBooksBy( this IQueryable<BookListDto> books, BooksFilterBy filterBy, string filterValue) { if (string.IsNullOrEmpty(filterValue)) return books; switch (filterBy) { case BooksFilterBy.NoFilter: return books; case BooksFilterBy.ByVotes: var filterVote = int.Parse(filterValue); return books.Where(x => x.ReviewsAverageVotes > filterVote); case BooksFilterBy.ByPublicationYear: if (filterValue == AllBooksNotPublishedString) return books.Where( x => x.PublishedOn > DateTime.UtcNow); var filterYear = int.Parse(filterValue); return books.Where( x => x.PublishedOn.Year == filterYear && x.PublishedOn <= DateTime.UtcNow); default: throw new ArgumentOutOfRangeException (nameof(filterBy), filterBy, null); } } /*************************************************************** #A The method is given both the type of filter and the user selected filter value #B If the filter value isn't set then it returns the IQueryable with no change #C Same for no filter selected - it returns the IQueryable with no change #D The filter by votes is a value and above, e.g. 3 and above. Note: not reviews returns null, and the test is always false #E If the "coming soon" was picked then we only return books not yet published #F If we have a specific year we filter on that. Note that we also remove future books (in case the user chose this year's date) * ************************************************************/ } }
45.650794
136
0.517385
[ "MIT" ]
CAH-FlyChen/EfCore.GenericBizRunner
ServiceLayer/BookServices/QueryObjects/BookListDtoFilter.cs
2,878
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace SharpSoundDevice { /* /// This is a plugin Loader that loads each plugin into a separate appDomain. Unfortunately, the overhead of passing between domains is too big, performance goes to shit. public class PluginMarshall : MarshalByRefObject, IAudioDevice { #region SetupRegion private static Dictionary<string, AppDomain> appDomains = new Dictionary<string, AppDomain>(); public static PluginMarshall Create(string assemblyFilename, string bridgeDllDir) { AppDomain appDomain; var pluginAssemblyPath = GetAssemblyPath(assemblyFilename, bridgeDllDir); if (pluginAssemblyPath == null) { Logging.Log(string.Format("Unable to find assembly file. AssemblyFilename: {0}, BridgeDllDir: {1}", assemblyFilename, bridgeDllDir)); return null; } if (appDomains.ContainsKey(assemblyFilename)) { appDomain = appDomains[assemblyFilename]; } else { appDomain = CreateAppDomain(assemblyFilename, Path.GetDirectoryName(pluginAssemblyPath)); appDomains[assemblyFilename] = appDomain; } var marshall = (PluginMarshall)appDomain.CreateInstanceAndUnwrap(typeof(PluginMarshall).Assembly.FullName, typeof(PluginMarshall).FullName); var asm = marshall.LoadPluginAssembly(pluginAssemblyPath); marshall.CreatePluginInstance(asm); return marshall.HasInstance ? marshall : null; } private static string GetAssemblyPath(string assemblyFilename, string bridgeDllDir) { Logging.Log(string.Format("Locating Assembly: {0} BridgeDllDir: {1}", assemblyFilename, bridgeDllDir)); string requestAssemblyPath = null; var intermediaryDir = assemblyFilename.EndsWith(".dll") ? assemblyFilename.Substring(0, assemblyFilename.Length - 4) : assemblyFilename; var filename = assemblyFilename.EndsWith(".dll") ? assemblyFilename : assemblyFilename + ".dll"; // Look in: // bridgeDllDir/assemblyFilename.dll // bridgeDllDir/assemblyFilename/assemblyFilename.dll var path1 = Path.Combine(bridgeDllDir, filename); var path2 = Path.Combine(bridgeDllDir, intermediaryDir, filename); if (File.Exists(path1)) requestAssemblyPath = path1; else if (File.Exists(path2)) requestAssemblyPath = path2; return requestAssemblyPath; } private static AppDomain CreateAppDomain(string assemblyFilename, string appDomainBaseDir) { var info = new AppDomainSetup { ApplicationBase = appDomainBaseDir }; var appDomain = AppDomain.CreateDomain("PluginDomain " + assemblyFilename, null, info); Logging.Log("Created AppDomain: " + appDomain.FriendlyName); Logging.Log("AppDomain BaseDir:" + appDomainBaseDir); return appDomain; } private class DomainResolver : MarshalByRefObject { private readonly string assemblyFilename; private readonly string bridgeDllDir; public DomainResolver(string assemblyFilename, string bridgeDllDir) { this.assemblyFilename = assemblyFilename; this.bridgeDllDir = bridgeDllDir; } public Assembly Resolve(object s, ResolveEventArgs e) { var folderPath = bridgeDllDir; var requestedAssemblyName = e.Name; string requestAssemblyPath = null; var path1 = Path.Combine(folderPath, requestedAssemblyName + ".dll"); var path2 = Path.Combine(folderPath, assemblyFilename, requestedAssemblyName + ".dll"); if (File.Exists(path1)) requestAssemblyPath = path1; else if (File.Exists(path2)) requestAssemblyPath = path2; if (requestAssemblyPath == null) return null; var requestedAssembly = Assembly.LoadFrom(requestAssemblyPath); return requestedAssembly; } } /// <summary> /// Works within an isolated AppDomain. /// /// Tracks down and loads the actual SharpSoundDevice plugin dll into the appdomain. /// Sets up AssemblyResolver to resolve plugin's dependencies, without affecting other plugins /// </summary> /// <param name="pluginAssemblyPath"></param> private Assembly LoadPluginAssembly(string pluginAssemblyPath) { try { Logging.Log(string.Format("Attempting load load Assembly {0} into AppDomain {1}", pluginAssemblyPath, AppDomain.CurrentDomain.FriendlyName)); var asm = Assembly.LoadFile(pluginAssemblyPath); Logging.Log("Loaded assembly " + asm.FullName); return asm; } catch (Exception ex) { Logging.Log("Unexpected error while trying to load assembly " + pluginAssemblyPath + ":\n" + ex.GetTrace()); return null; } } /// <summary> /// Creates an instance of the first IAudioDevice class found in the assembly, sets it to the internal property of the marshaller /// </summary> /// <param name="asm"></param> private void CreatePluginInstance(Assembly asm) { Logging.Log("Searching for classes in assembly " + asm.FullName); var exported = asm.GetExportedTypes().Where(x => x.GetInterfaces().Contains(typeof(IAudioDevice))).ToList(); Logging.Log("Number of classes: " + exported.Count); if (exported.Count == 0) { Logging.Log("No class implementing IAudioDevice was found in the specified assembly"); return; } var type = exported.First(); Logging.Log("Found at least one plugin class, calling parameterless constructor for " + type.FullName); var obj = type.GetConstructor(new Type[0]).Invoke(null); if (obj == null) { Logging.Log("Constructor call failed"); return; } Logging.Log("Attempting to cast new object to IAudioDevice"); IAudioDevice instance; try { instance = (IAudioDevice)obj; } catch (Exception e) { Logging.Log("Cast failed: " + e.Message); return; } Logging.Log("Successfully created new plugin instance"); this.Instance = instance; this.HasInstance = true; } #endregion private IAudioDevice Instance { get; set; } public bool HasInstance { get; private set; } public int CurrentProgram { get { return Instance.CurrentProgram; } } public int DeviceId { get { return Instance.DeviceId; } set { Instance.DeviceId = value; } } public DeviceInfo DeviceInfo { get { return Instance.DeviceInfo; } } public IHostInfo HostInfo { get { return Instance.HostInfo; } set { Instance.HostInfo = value; } } public Parameter[] ParameterInfo { get { return Instance.ParameterInfo; } } public Port[] PortInfo { get { return Instance.PortInfo; } } public void CloseEditor() { Instance.CloseEditor(); } public void DisposeDevice() { Instance.DisposeDevice(); } public Program GetProgramData(int index) { return Instance.GetProgramData(index); } public void HostChanged() { Instance.HostChanged(); } public void InitializeDevice() { Instance.InitializeDevice(); } public void OpenEditor(IntPtr parentWindow) { Instance.OpenEditor(parentWindow); } private static List<double> times = new List<double>(); public void ProcessSample(double[][] input, double[][] output, uint bufferSize) { Instance.ProcessSample(input, output, bufferSize); } public void ProcessSample(IntPtr input, IntPtr output, uint inChannelCount, uint outChannelCount, uint bufferSize) { Instance.ProcessSample(input, output, inChannelCount, outChannelCount, bufferSize); } public bool SendEvent(Event ev) { return Instance.SendEvent(ev); } public void SetProgramData(Program program, int index) { Instance.SetProgramData(program, index); } public void Start() { Instance.Start(); } public void Stop() { Instance.Stop(); } } */ }
26.639456
171
0.696885
[ "MIT" ]
ValdemarOrn/SharpSoundDevice
SharpSoundDevice/PluginMarshall.cs
7,834
C#
// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; namespace PixelCrushers.DialogueSystem.SequencerCommands { /// <summary> /// Implements sequencer command: Voice(audioClip, animation[, finalAnimation[, gameobject|speaker|listener]]) /// Works with Animation or Animator components. /// </summary> [AddComponentMenu("")] // Hide from menu. public class SequencerCommandVoice : SequencerCommand { private float stopTime = 0; Transform subject = null; private string finalClipName = string.Empty; private Animation anim = null; private Animator animator = null; private AudioSource audioSource = null; private AudioClip audioClip = null; public void Start() { string audioClipName = GetParameter(0); string animationClipName = GetParameter(1); finalClipName = GetParameter(2); subject = GetSubject(3); anim = (subject == null) ? null : subject.GetComponent<Animation>(); animator = (subject == null) ? null : subject.GetComponent<Animator>(); if ((anim == null) && (animator == null)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Voice({1}, {2}, {3}, {4}) command: No Animator or Animation component found on {3}.", new System.Object[] { DialogueDebug.Prefix, audioClipName, animationClipName, finalClipName, (subject != null) ? subject.name : GetParameter(3) })); } else if (string.IsNullOrEmpty(audioClipName)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Voice({1}, {2}, {3}, {4}) command: Audio clip name is blank.", new System.Object[] { DialogueDebug.Prefix, audioClipName, animationClipName, finalClipName, subject.name })); } else if (string.IsNullOrEmpty(animationClipName)) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Voice({1}, {2}, {3}, {4}) command: Animation name is blank.", new System.Object[] { DialogueDebug.Prefix, audioClipName, animationClipName, finalClipName, subject.name })); } else { DialogueManager.LoadAsset(audioClipName, typeof(AudioClip), (asset) => { audioClip = asset as AudioClip; if (audioClip == null) { if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Sequencer: Voice({1}, {2}, {3}, {4}) command: Audio clip is null.", new System.Object[] { DialogueDebug.Prefix, audioClipName, animationClipName, finalClipName, subject.name })); stopTime = 0; } else { if (IsAudioMuted()) { if (DialogueDebug.logInfo) Debug.Log(string.Format("{0}: Sequencer: Voice({1}, {2}, {3}, {4}): Audio is muted; not playing it.", new System.Object[] { DialogueDebug.Prefix, audioClipName, animationClipName, finalClipName, Tools.GetObjectName(subject) })); } else { audioSource.clip = audioClip; audioSource.Play(); } try { if (animator != null) { animator.CrossFade(animationClipName, 0.3f); stopTime = DialogueTime.time + audioClip.length; } else { anim.CrossFade(animationClipName); stopTime = DialogueTime.time + Mathf.Max(0.1f, anim[animationClipName].length - 0.3f); if (audioClip.length > anim[animationClipName].length) stopTime = DialogueTime.time + audioClip.length; } } catch (System.Exception) { stopTime = 0; } } }); } } public void Update() { if (DialogueTime.time >= stopTime) Stop(); } public void OnDialogueSystemPause() { if (audioSource == null) return; audioSource.Pause(); } public void OnDialogueSystemUnpause() { if (audioSource == null) return; audioSource.Play(); } public void OnDestroy() { if (animator != null) { if (!string.IsNullOrEmpty(finalClipName)) { animator.CrossFade(finalClipName, 0.3f); } } else if (anim != null) { if (!string.IsNullOrEmpty(finalClipName)) { anim.CrossFade(finalClipName); } else if (anim.clip != null) { anim.CrossFade(anim.clip.name); } } if ((audioSource != null) && (DialogueTime.time < stopTime)) { audioSource.Stop(); } DialogueManager.UnloadAsset(audioClip); } } }
42.408759
329
0.479174
[ "Unlicense" ]
Gingerbread-Fetus/Don-tSayItHasan
Don't Say it Hasan!/Assets/Plugins/Pixel Crushers/Dialogue System/Scripts/MVC/Sequencer/Commands/SequencerCommandVoice.cs
5,810
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedParticipantsClientSnippets { /// <summary>Snippet for CreateParticipant</summary> public void CreateParticipantRequestObject() { // Snippet: CreateParticipant(CreateParticipantRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; // Make the request Participant response = participantsClient.CreateParticipant(request); // End snippet } /// <summary>Snippet for CreateParticipantAsync</summary> public async Task CreateParticipantRequestObjectAsync() { // Snippet: CreateParticipantAsync(CreateParticipantRequest, CallSettings) // Additional: CreateParticipantAsync(CreateParticipantRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; // Make the request Participant response = await participantsClient.CreateParticipantAsync(request); // End snippet } /// <summary>Snippet for CreateParticipant</summary> public void CreateParticipant() { // Snippet: CreateParticipant(string, Participant, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; Participant participant = new Participant(); // Make the request Participant response = participantsClient.CreateParticipant(parent, participant); // End snippet } /// <summary>Snippet for CreateParticipantAsync</summary> public async Task CreateParticipantAsync() { // Snippet: CreateParticipantAsync(string, Participant, CallSettings) // Additional: CreateParticipantAsync(string, Participant, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; Participant participant = new Participant(); // Make the request Participant response = await participantsClient.CreateParticipantAsync(parent, participant); // End snippet } /// <summary>Snippet for CreateParticipant</summary> public void CreateParticipantResourceNames() { // Snippet: CreateParticipant(ConversationName, Participant, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); Participant participant = new Participant(); // Make the request Participant response = participantsClient.CreateParticipant(parent, participant); // End snippet } /// <summary>Snippet for CreateParticipantAsync</summary> public async Task CreateParticipantResourceNamesAsync() { // Snippet: CreateParticipantAsync(ConversationName, Participant, CallSettings) // Additional: CreateParticipantAsync(ConversationName, Participant, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); Participant participant = new Participant(); // Make the request Participant response = await participantsClient.CreateParticipantAsync(parent, participant); // End snippet } /// <summary>Snippet for GetParticipant</summary> public void GetParticipantRequestObject() { // Snippet: GetParticipant(GetParticipantRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; // Make the request Participant response = participantsClient.GetParticipant(request); // End snippet } /// <summary>Snippet for GetParticipantAsync</summary> public async Task GetParticipantRequestObjectAsync() { // Snippet: GetParticipantAsync(GetParticipantRequest, CallSettings) // Additional: GetParticipantAsync(GetParticipantRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; // Make the request Participant response = await participantsClient.GetParticipantAsync(request); // End snippet } /// <summary>Snippet for GetParticipant</summary> public void GetParticipant() { // Snippet: GetParticipant(string, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request Participant response = participantsClient.GetParticipant(name); // End snippet } /// <summary>Snippet for GetParticipantAsync</summary> public async Task GetParticipantAsync() { // Snippet: GetParticipantAsync(string, CallSettings) // Additional: GetParticipantAsync(string, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request Participant response = await participantsClient.GetParticipantAsync(name); // End snippet } /// <summary>Snippet for GetParticipant</summary> public void GetParticipantResourceNames() { // Snippet: GetParticipant(ParticipantName, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName name = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request Participant response = participantsClient.GetParticipant(name); // End snippet } /// <summary>Snippet for GetParticipantAsync</summary> public async Task GetParticipantResourceNamesAsync() { // Snippet: GetParticipantAsync(ParticipantName, CallSettings) // Additional: GetParticipantAsync(ParticipantName, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName name = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request Participant response = await participantsClient.GetParticipantAsync(name); // End snippet } /// <summary>Snippet for ListParticipants</summary> public void ListParticipantsRequestObject() { // Snippet: ListParticipants(ListParticipantsRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ListParticipantsRequest request = new ListParticipantsRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), }; // Make the request PagedEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipants(request); // Iterate over all response items, lazily performing RPCs as required foreach (Participant item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListParticipantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipantsAsync</summary> public async Task ListParticipantsRequestObjectAsync() { // Snippet: ListParticipantsAsync(ListParticipantsRequest, CallSettings) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ListParticipantsRequest request = new ListParticipantsRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), }; // Make the request PagedAsyncEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipantsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Participant item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListParticipantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipants</summary> public void ListParticipants() { // Snippet: ListParticipants(string, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; // Make the request PagedEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipants(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Participant item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListParticipantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipantsAsync</summary> public async Task ListParticipantsAsync() { // Snippet: ListParticipantsAsync(string, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; // Make the request PagedAsyncEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipantsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Participant item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListParticipantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipants</summary> public void ListParticipantsResourceNames() { // Snippet: ListParticipants(ConversationName, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); // Make the request PagedEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipants(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Participant item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListParticipantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipantsAsync</summary> public async Task ListParticipantsResourceNamesAsync() { // Snippet: ListParticipantsAsync(ConversationName, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); // Make the request PagedAsyncEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipantsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Participant item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListParticipantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for UpdateParticipant</summary> public void UpdateParticipantRequestObject() { // Snippet: UpdateParticipant(UpdateParticipantRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new FieldMask(), }; // Make the request Participant response = participantsClient.UpdateParticipant(request); // End snippet } /// <summary>Snippet for UpdateParticipantAsync</summary> public async Task UpdateParticipantRequestObjectAsync() { // Snippet: UpdateParticipantAsync(UpdateParticipantRequest, CallSettings) // Additional: UpdateParticipantAsync(UpdateParticipantRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new FieldMask(), }; // Make the request Participant response = await participantsClient.UpdateParticipantAsync(request); // End snippet } /// <summary>Snippet for UpdateParticipant</summary> public void UpdateParticipant() { // Snippet: UpdateParticipant(Participant, FieldMask, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) Participant participant = new Participant(); FieldMask updateMask = new FieldMask(); // Make the request Participant response = participantsClient.UpdateParticipant(participant, updateMask); // End snippet } /// <summary>Snippet for UpdateParticipantAsync</summary> public async Task UpdateParticipantAsync() { // Snippet: UpdateParticipantAsync(Participant, FieldMask, CallSettings) // Additional: UpdateParticipantAsync(Participant, FieldMask, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) Participant participant = new Participant(); FieldMask updateMask = new FieldMask(); // Make the request Participant response = await participantsClient.UpdateParticipantAsync(participant, updateMask); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContentRequestObject() { // Snippet: AnalyzeContent(AnalyzeContentRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), ReplyAudioConfig = new OutputAudioConfig(), TextInput = new TextInput(), QueryParams = new QueryParameters(), RequestId = "", }; // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(request); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContentRequestObjectAsync() { // Snippet: AnalyzeContentAsync(AnalyzeContentRequest, CallSettings) // Additional: AnalyzeContentAsync(AnalyzeContentRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), ReplyAudioConfig = new OutputAudioConfig(), TextInput = new TextInput(), QueryParams = new QueryParameters(), RequestId = "", }; // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(request); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent1() { // Snippet: AnalyzeContent(string, TextInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent1Async() { // Snippet: AnalyzeContentAsync(string, TextInput, CallSettings) // Additional: AnalyzeContentAsync(string, TextInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent1ResourceNames() { // Snippet: AnalyzeContent(ParticipantName, TextInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent1ResourceNamesAsync() { // Snippet: AnalyzeContentAsync(ParticipantName, TextInput, CallSettings) // Additional: AnalyzeContentAsync(ParticipantName, TextInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent2() { // Snippet: AnalyzeContent(string, EventInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, eventInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent2Async() { // Snippet: AnalyzeContentAsync(string, EventInput, CallSettings) // Additional: AnalyzeContentAsync(string, EventInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, eventInput); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent2ResourceNames() { // Snippet: AnalyzeContent(ParticipantName, EventInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, eventInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent2ResourceNamesAsync() { // Snippet: AnalyzeContentAsync(ParticipantName, EventInput, CallSettings) // Additional: AnalyzeContentAsync(ParticipantName, EventInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, eventInput); // End snippet } /// <summary>Snippet for SuggestArticles</summary> public void SuggestArticlesRequestObject() { // Snippet: SuggestArticles(SuggestArticlesRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, }; // Make the request SuggestArticlesResponse response = participantsClient.SuggestArticles(request); // End snippet } /// <summary>Snippet for SuggestArticlesAsync</summary> public async Task SuggestArticlesRequestObjectAsync() { // Snippet: SuggestArticlesAsync(SuggestArticlesRequest, CallSettings) // Additional: SuggestArticlesAsync(SuggestArticlesRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, }; // Make the request SuggestArticlesResponse response = await participantsClient.SuggestArticlesAsync(request); // End snippet } /// <summary>Snippet for SuggestArticles</summary> public void SuggestArticles() { // Snippet: SuggestArticles(string, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestArticlesResponse response = participantsClient.SuggestArticles(parent); // End snippet } /// <summary>Snippet for SuggestArticlesAsync</summary> public async Task SuggestArticlesAsync() { // Snippet: SuggestArticlesAsync(string, CallSettings) // Additional: SuggestArticlesAsync(string, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestArticlesResponse response = await participantsClient.SuggestArticlesAsync(parent); // End snippet } /// <summary>Snippet for SuggestArticles</summary> public void SuggestArticlesResourceNames() { // Snippet: SuggestArticles(ParticipantName, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestArticlesResponse response = participantsClient.SuggestArticles(parent); // End snippet } /// <summary>Snippet for SuggestArticlesAsync</summary> public async Task SuggestArticlesResourceNamesAsync() { // Snippet: SuggestArticlesAsync(ParticipantName, CallSettings) // Additional: SuggestArticlesAsync(ParticipantName, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestArticlesResponse response = await participantsClient.SuggestArticlesAsync(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswers</summary> public void SuggestFaqAnswersRequestObject() { // Snippet: SuggestFaqAnswers(SuggestFaqAnswersRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, }; // Make the request SuggestFaqAnswersResponse response = participantsClient.SuggestFaqAnswers(request); // End snippet } /// <summary>Snippet for SuggestFaqAnswersAsync</summary> public async Task SuggestFaqAnswersRequestObjectAsync() { // Snippet: SuggestFaqAnswersAsync(SuggestFaqAnswersRequest, CallSettings) // Additional: SuggestFaqAnswersAsync(SuggestFaqAnswersRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, }; // Make the request SuggestFaqAnswersResponse response = await participantsClient.SuggestFaqAnswersAsync(request); // End snippet } /// <summary>Snippet for SuggestFaqAnswers</summary> public void SuggestFaqAnswers() { // Snippet: SuggestFaqAnswers(string, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestFaqAnswersResponse response = participantsClient.SuggestFaqAnswers(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswersAsync</summary> public async Task SuggestFaqAnswersAsync() { // Snippet: SuggestFaqAnswersAsync(string, CallSettings) // Additional: SuggestFaqAnswersAsync(string, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestFaqAnswersResponse response = await participantsClient.SuggestFaqAnswersAsync(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswers</summary> public void SuggestFaqAnswersResourceNames() { // Snippet: SuggestFaqAnswers(ParticipantName, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestFaqAnswersResponse response = participantsClient.SuggestFaqAnswers(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswersAsync</summary> public async Task SuggestFaqAnswersResourceNamesAsync() { // Snippet: SuggestFaqAnswersAsync(ParticipantName, CallSettings) // Additional: SuggestFaqAnswersAsync(ParticipantName, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestFaqAnswersResponse response = await participantsClient.SuggestFaqAnswersAsync(parent); // End snippet } } }
48.752252
146
0.629885
[ "Apache-2.0" ]
Mattlk13/google-cloud-dotnet
apis/Google.Cloud.Dialogflow.V2/Google.Cloud.Dialogflow.V2.Snippets/ParticipantsClientSnippets.g.cs
43,292
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BooleanAndToCollapsingVisibilityMultiValueConverter.cs" company="WildGums"> // Copyright (c) 2008 - 2017 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Windows; using System.Windows.Data; using System.Windows.Markup; namespace Orc.Controls.Converters { public class BooleanAndToCollapsingVisibilityMultiValueConverter : MarkupExtension, IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { foreach (var obj in values) { if (!(obj is bool)) { return Visibility.Collapsed; } else if(!(bool)obj) { return Visibility.Collapsed; } } return Visibility.Visible; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { // Not supported (and IMultiValueConverter must return null if no conversion is supported) return null; } public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }
32.755102
120
0.522118
[ "MIT" ]
GreenKn1ght/Orc.Controls
src/Orc.Controls/Converters/BooleanAndToCollapsingVisibilityMultiValueConverter.cs
1,607
C#
using Microsoft.VisualStudio.TestPlatform.Utilities; using NUnit.Framework; using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.Text; namespace ScottPlotTests.Axis { class AutoAxis { [Test] public void Test_AxisAutoY_Repeated() { double[] xs = { 1, 2, 3, 4, 5 }; double[] ys = { 1, 4, 9, 16, 25 }; var plt = new ScottPlot.Plot(400, 300); plt.PlotScatter(xs, ys); plt.SetAxisLimits(-5, 10, -15, 40); for (int i = 0; i < 10; i++) plt.AxisAutoY(); TestTools.SaveFig(plt); } [Test] public void Test_AxisAutoX_Repeated() { double[] xs = { 1, 2, 3, 4, 5 }; double[] ys = { 1, 4, 9, 16, 25 }; var plt = new ScottPlot.Plot(400, 300); plt.PlotScatter(xs, ys); plt.SetAxisLimits(-5, 10, -15, 40); for (int i = 0; i < 10; i++) plt.AxisAutoX(); TestTools.SaveFig(plt); } [Test] public void Test_AxisAuto_SignalWithMinMaxIndexSet() { var plt = new ScottPlot.Plot(400, 300); var sig = plt.PlotSignal(ScottPlot.DataGen.Sin(1000), sampleRate: 10); sig.MinRenderIndex = 450; sig.MaxRenderIndex = 550; plt.AxisAuto(); var limits = plt.GetAxisLimits(); Console.WriteLine($"AutoAxis Limits: {limits}"); Assert.Less(limits.XMin, limits.XMax); Assert.Less(limits.YMin, limits.YMax); TestTools.SaveFig(plt); } } }
26.52381
82
0.517654
[ "MIT" ]
MosheBarkan/ScottPlot
src/tests/Axis/AutoAxis.cs
1,673
C#
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon 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; using System.Diagnostics; using System.Globalization; using System.Reflection; using Remotion.Utilities; // ReSharper disable once CheckNamespace namespace Remotion.Development.UnitTesting { /// <summary> /// Provides utility functions for accessing non-public types and members. /// </summary> static partial class PrivateInvoke { // static members private static MethodInfo GetMethod (Type type, string methodName, BindingFlags bindingFlags, object[] arguments) { Debug.Assert (methodName != null); return (MethodInfo) GetMethodBaseInternal (type, methodName, type.GetMethods (bindingFlags), arguments); } private static ConstructorInfo GetConstructor (Type type, BindingFlags bindingFlags, object[] arguments) { return (ConstructorInfo) GetMethodBaseInternal (type, null, type.GetConstructors (bindingFlags), arguments); } private static MethodBase GetMethodBaseInternal (Type type, string methodName, MethodBase[] methods, object[] arguments) { MethodBase callMethod = null; foreach (MethodBase method in methods) { if (methodName == null || methodName == method.Name) { ParameterInfo[] parameters = method.GetParameters (); if (parameters.Length == arguments.Length) { bool isMatch = true; for (int i = 0; i < parameters.Length; ++i) { object argument = arguments[i]; Type parameterType = parameters[i].ParameterType; if (! ( (argument == null && ! parameterType.IsValueType) // null is a valid argument for any reference type || (argument != null && parameterType.IsAssignableFrom (argument.GetType())))) { isMatch = false; break; } } if (isMatch) { if (callMethod != null) { var message = string.Format ("There is no method \"{0}\" in type {1} that accepts the specified argument types.", methodName, type); throw new AmbiguousMatchException (message); } callMethod = method; } } } } if (callMethod == null) throw new MissingMethodException (type.Name, methodName); return callMethod; } private static PropertyInfo GetPropertyRecursive (Type type, BindingFlags bindingFlags, string propertyName) { for (PropertyInfo property = null; type != null; type = type.BaseType) { property = type.GetProperty (propertyName, bindingFlags); if (property != null) return property; } return null; } private static FieldInfo GetFieldRecursive (Type type, BindingFlags bindingFlags, string fieldName) { for (FieldInfo field = null; type != null; type = type.BaseType) { field = type.GetField (fieldName, bindingFlags); if (field != null) return field; } return null; } #region InvokeMethod methods public static object InvokeNonPublicStaticMethod (Type type, string methodName, params object[] arguments) { ArgumentUtility.CheckNotNull ("type", type); ArgumentUtility.CheckNotNullOrEmpty ("methodName", methodName); return InvokeMethodInternal (null, type, BindingFlags.Static | BindingFlags.NonPublic, methodName, arguments); } public static object InvokePublicStaticMethod (Type type, string methodName, params object[] arguments) { ArgumentUtility.CheckNotNull ("type", type); ArgumentUtility.CheckNotNullOrEmpty ("methodName", methodName); return InvokeMethodInternal (null, type, BindingFlags.Static | BindingFlags.Public, methodName, arguments); } public static object InvokeNonPublicMethod (object target, string methodName, params object[] arguments) { ArgumentUtility.CheckNotNull ("target", target); return InvokeNonPublicMethod (target, target.GetType(), methodName, arguments); } public static object InvokeNonPublicMethod (object target, Type definingType, string methodName, params object[] arguments) { ArgumentUtility.CheckNotNull ("target", target); ArgumentUtility.CheckNotNull ("definingType", definingType); ArgumentUtility.CheckType ("target", target, definingType); ArgumentUtility.CheckNotNullOrEmpty ("methodName", methodName); return InvokeMethodInternal (target, definingType, BindingFlags.Instance | BindingFlags.NonPublic, methodName, arguments); } public static object InvokePublicMethod (object target, string methodName, params object[] arguments) { ArgumentUtility.CheckNotNull ("target", target); ArgumentUtility.CheckNotNullOrEmpty ("methodName", methodName); return InvokeMethodInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.Public, methodName, arguments); } private static object InvokeMethodInternal (object instance, Type type, BindingFlags bindingFlags, string methodName, object[] arguments) { if (arguments == null) arguments = new object[] { null }; MethodInfo callMethod = GetMethod (type, methodName, bindingFlags, arguments); try { return callMethod.Invoke (instance, bindingFlags, null, arguments, CultureInfo.InvariantCulture); } catch (TargetInvocationException e) { throw e.InnerException.PreserveStackTrace(); } } #endregion #region CreateInstance methods public static object CreateInstancePublicCtor (string assemblyString, string typeName, params object[] arguments) { return CreateInstancePublicCtor (Assembly.Load (assemblyString), typeName, arguments); } public static object CreateInstancePublicCtor (Assembly assembly, string typeName, params object[] arguments) { return CreateInstancePublicCtor (assembly.GetType (typeName, true, false), arguments); } public static object CreateInstancePublicCtor (Type type, params object[] arguments) { return CreateInstanceInternal (type, true, arguments); } public static object CreateInstanceNonPublicCtor (string assemblyString, string typeName, params object[] arguments) { return CreateInstanceNonPublicCtor (Assembly.Load (assemblyString), typeName, arguments); } public static object CreateInstanceNonPublicCtor (Assembly assembly, string typeName, params object[] arguments) { return CreateInstanceNonPublicCtor (assembly.GetType (typeName, true, false), arguments); } public static object CreateInstanceNonPublicCtor (Type type, params object[] arguments) { return CreateInstanceInternal (type, false, arguments); } private static object CreateInstanceInternal (Type type, bool isPublic, object[] arguments) { if (arguments == null) arguments = new object[] { null }; BindingFlags bindingFlags = BindingFlags.Instance; bindingFlags |= isPublic ? BindingFlags.Public : BindingFlags.NonPublic; ConstructorInfo ctor = GetConstructor (type, bindingFlags, arguments); try { return ctor.Invoke (BindingFlags.CreateInstance, null, arguments, CultureInfo.InvariantCulture); } catch (TargetInvocationException e) { throw e.InnerException.PreserveStackTrace (); } } #endregion #region GetProperty methods public static object GetPublicProperty (object target, string propertyName) { if (target == null) throw new ArgumentNullException ("target"); return GetPropertyInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.Public, propertyName); } public static object GetNonPublicProperty (object target, string propertyName) { if (target == null) throw new ArgumentNullException ("target"); return GetPropertyInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.NonPublic, propertyName); } public static object GetNonPublicProperty (object target, Type declaringType, string propertyName) { ArgumentUtility.CheckNotNull ("target", target); ArgumentUtility.CheckNotNull ("declaringType", declaringType); return GetPropertyInternal (target, declaringType, BindingFlags.Instance | BindingFlags.NonPublic, propertyName); } public static object GetPublicStaticProperty (Type type, string propertyName) { if (type == null) throw new ArgumentNullException ("type"); return GetPropertyInternal (null, type, BindingFlags.Static | BindingFlags.Public, propertyName); } public static object GetNonPublicStaticProperty (Type type, string propertyName) { if (type == null) throw new ArgumentNullException ("type"); return GetPropertyInternal (null, type, BindingFlags.Static | BindingFlags.NonPublic, propertyName); } private static object GetPropertyInternal (object instance, Type type, BindingFlags bindingFlags, string propertyName) { PropertyInfo property = GetPropertyRecursive (type, bindingFlags, propertyName); if (property == null) { throw new ArgumentException ("No property '" + propertyName + "' found on type '" + type.FullName + "' with binding flags '" + bindingFlags + "'.", "propertyName"); } try { return property.GetValue (instance, new object[] {}); } catch (TargetInvocationException e) { throw e.InnerException.PreserveStackTrace (); } } #endregion #region SetProperty methods public static void SetPublicProperty (object target, string propertyName, object value) { if (target == null) throw new ArgumentNullException ("target"); SetPropertyInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.Public, propertyName, value); } public static void SetNonPublicProperty (object target, string propertyName, object value) { if (target == null) throw new ArgumentNullException ("target"); SetPropertyInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.NonPublic, propertyName, value); } public static void SetNonPublicProperty (object target, Type declaringType, string propertyName, object value) { if (target == null) throw new ArgumentNullException ("target"); SetPropertyInternal (target, declaringType, BindingFlags.Instance | BindingFlags.NonPublic, propertyName, value); } public static void SetPublicStaticProperty (Type type, string propertyName, object value) { if (type == null) throw new ArgumentNullException ("type"); PropertyInfo property = type.GetProperty (propertyName, BindingFlags.Static | BindingFlags.Public); SetPropertyInternal (null, type, BindingFlags.Static | BindingFlags.Public, propertyName, value); } public static void SetNonPublicStaticProperty (Type type, string propertyName, object value) { if (type == null) throw new ArgumentNullException ("type"); SetPropertyInternal (null, type, BindingFlags.Static | BindingFlags.NonPublic, propertyName, value); } private static void SetPropertyInternal (object instance, Type type, BindingFlags bindingFlags, string propertyName, object value) { PropertyInfo property = GetPropertyRecursive (type, bindingFlags, propertyName); try { property.SetValue (instance, value, new object[] {}); } catch (TargetInvocationException e) { throw e.InnerException.PreserveStackTrace (); } } #endregion #region GetField methods public static object GetPublicField (object target, string fieldName) { if (target == null) throw new ArgumentNullException ("target"); return GetFieldInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.Public, fieldName); } public static object GetNonPublicField (object target, string fieldName) { if (target == null) throw new ArgumentNullException ("target"); var declaringType = target.GetType(); return GetNonPublicField(target, declaringType, fieldName); } public static object GetNonPublicField(object target, Type declaringType, string fieldName) { ArgumentUtility.CheckNotNull ("target", target); ArgumentUtility.CheckNotNull ("declaringType", declaringType); return GetFieldInternal (target, declaringType, BindingFlags.Instance | BindingFlags.NonPublic, fieldName); } public static object GetPublicStaticField (Type type, string fieldName) { if (type == null) throw new ArgumentNullException ("type"); return GetFieldInternal (null, type, BindingFlags.Static | BindingFlags.Public, fieldName); } public static object GetNonPublicStaticField (Type type, string fieldName) { if (type == null) throw new ArgumentNullException ("type"); return GetFieldInternal (null, type, BindingFlags.Static | BindingFlags.NonPublic, fieldName); } private static object GetFieldInternal (object instance, Type type, BindingFlags bindingFlags, string fieldName) { FieldInfo field = GetFieldRecursive (type, bindingFlags, fieldName); if (field == null) { throw new ArgumentException ("No field '" + fieldName + "' found on type '" + type.FullName + "' with binding flags '" + bindingFlags + "'.", "fieldName"); } try { return field.GetValue (instance); } catch (TargetInvocationException e) { throw e.InnerException.PreserveStackTrace (); } } #endregion #region SetField methods public static void SetPublicField (object target, string fieldName, object value) { if (target == null) throw new ArgumentNullException ("target"); SetFieldInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.Public, fieldName, value); } public static void SetNonPublicField (object target, string fieldName, object value) { if (target == null) throw new ArgumentNullException ("target"); SetFieldInternal (target, target.GetType(), BindingFlags.Instance | BindingFlags.NonPublic, fieldName, value); } public static void SetPublicStaticField (Type type, string fieldName, object value) { if (type == null) throw new ArgumentNullException ("type"); SetFieldInternal (null, type, BindingFlags.Static | BindingFlags.Public, fieldName, value); } public static void SetNonPublicStaticField (Type type, string fieldName, object value) { if (type == null) throw new ArgumentNullException ("type"); SetFieldInternal (null, type, BindingFlags.Static | BindingFlags.NonPublic, fieldName, value); } private static void SetFieldInternal (object instance, Type type, BindingFlags bindingFlags, string fieldName, object value) { FieldInfo field = GetFieldRecursive (type, bindingFlags, fieldName); try { field.SetValue (instance, value); } catch (TargetInvocationException e) { throw e.InnerException.PreserveStackTrace (); } } #endregion } }
37.852459
155
0.687867
[ "ECL-2.0", "Apache-2.0" ]
biohazard999/Relinq
UnitTests.Net_3_5/App_Packages/Remotion.Development.UnitTesting.PrivateInvoke.Sources.1.15.23.0/PrivateInvoke.cs
16,163
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Devices.Shared; using Microsoft.Azure.Devices.Client.Exceptions; using Microsoft.Azure.Devices.Client.Extensions; using Microsoft.Azure.Devices.Client.Transport.AmqpIoT; using System.Collections.Generic; namespace Microsoft.Azure.Devices.Client.Transport.Amqp { internal class AmqpConnectionHolder : IAmqpConnectionHolder, IAmqpUnitManager { private readonly DeviceIdentity _deviceIdentity; private readonly AmqpIoTConnector _amqpIoTConnector; private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1); private readonly HashSet<AmqpUnit> _amqpUnits = new HashSet<AmqpUnit>(); private readonly object _unitsLock = new object(); private AmqpIoTConnection _amqpIoTConnection; private IAmqpAuthenticationRefresher _amqpAuthenticationRefresher; private volatile bool _disposed; public AmqpConnectionHolder(DeviceIdentity deviceIdentity) { _deviceIdentity = deviceIdentity; _amqpIoTConnector = new AmqpIoTConnector(deviceIdentity.AmqpTransportSettings, deviceIdentity.IotHubConnectionString.HostName); if (Logging.IsEnabled) Logging.Associate(this, _deviceIdentity, $"{nameof(_deviceIdentity)}"); } public AmqpUnit CreateAmqpUnit( DeviceIdentity deviceIdentity, Func<MethodRequestInternal, Task> methodHandler, Action<Twin, string, TwinCollection> twinMessageListener, Func<string, Message, Task> eventListener, Action onUnitDisconnected) { if (Logging.IsEnabled) Logging.Enter(this, deviceIdentity, $"{nameof(CreateAmqpUnit)}"); AmqpUnit amqpUnit = new AmqpUnit( deviceIdentity, this, methodHandler, twinMessageListener, eventListener, onUnitDisconnected); lock(_unitsLock) { _amqpUnits.Add(amqpUnit); } if (Logging.IsEnabled) Logging.Exit(this, deviceIdentity, $"{nameof(CreateAmqpUnit)}"); return amqpUnit; } private void OnConnectionClosed(object o, EventArgs args) { if (Logging.IsEnabled) Logging.Enter(this, o, $"{nameof(OnConnectionClosed)}"); if (_amqpIoTConnection != null && ReferenceEquals(_amqpIoTConnection, o)) { _amqpAuthenticationRefresher?.StopLoop(); HashSet<AmqpUnit> amqpUnits; lock (_unitsLock) { amqpUnits = new HashSet<AmqpUnit>(_amqpUnits); } foreach (AmqpUnit unit in amqpUnits) { unit.OnConnectionDisconnected(); } } if (Logging.IsEnabled) Logging.Exit(this, o, $"{nameof(OnConnectionClosed)}"); } public void Shutdown() { if (Logging.IsEnabled) Logging.Enter(this, _amqpIoTConnection, $"{nameof(Shutdown)}"); _amqpAuthenticationRefresher?.StopLoop(); _amqpIoTConnection?.SafeClose(); if (Logging.IsEnabled) Logging.Exit(this, _amqpIoTConnection, $"{nameof(Shutdown)}"); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (_disposed) return; if (Logging.IsEnabled) Logging.Info(this, disposing, $"{nameof(Dispose)}"); if (disposing) { _amqpIoTConnection?.SafeClose(); _lock?.Dispose(); _amqpIoTConnector?.Dispose(); lock (_unitsLock) { _amqpUnits.Clear(); } _amqpAuthenticationRefresher?.Dispose(); } _disposed = true; } public async Task<IAmqpAuthenticationRefresher> CreateRefresherAsync(DeviceIdentity deviceIdentity, TimeSpan timeout) { if (Logging.IsEnabled) Logging.Enter(this, deviceIdentity, timeout, $"{nameof(CreateRefresherAsync)}"); AmqpIoTConnection amqpIoTConnection = await EnsureConnectionAsync(timeout).ConfigureAwait(false); IAmqpAuthenticationRefresher amqpAuthenticator = await amqpIoTConnection.CreateRefresherAsync(deviceIdentity, timeout).ConfigureAwait(false); if (Logging.IsEnabled) Logging.Exit(this, deviceIdentity, timeout, $"{nameof(CreateRefresherAsync)}"); return amqpAuthenticator; } public async Task<AmqpIoTSession> OpenSessionAsync(DeviceIdentity deviceIdentity, TimeSpan timeout) { if (Logging.IsEnabled) Logging.Enter(this, deviceIdentity, timeout, $"{nameof(OpenSessionAsync)}"); AmqpIoTConnection amqpIoTConnection = await EnsureConnectionAsync(timeout).ConfigureAwait(false); AmqpIoTSession amqpIoTSession = await amqpIoTConnection.OpenSessionAsync(timeout).ConfigureAwait(false); if (Logging.IsEnabled) Logging.Associate(amqpIoTConnection, amqpIoTSession, $"{nameof(OpenSessionAsync)}"); if (Logging.IsEnabled) Logging.Exit(this, deviceIdentity, timeout, $"{nameof(OpenSessionAsync)}"); return amqpIoTSession; } public async Task<AmqpIoTConnection> EnsureConnectionAsync(TimeSpan timeout) { if (Logging.IsEnabled) Logging.Enter(this, timeout, $"{nameof(EnsureConnectionAsync)}"); AmqpIoTConnection amqpIoTConnection = null; IAmqpAuthenticationRefresher amqpAuthenticationRefresher = null; bool gain = await _lock.WaitAsync(timeout).ConfigureAwait(false); if (!gain) { throw new TimeoutException(); } try { if (_amqpIoTConnection == null || _amqpIoTConnection.IsClosing()) { if (Logging.IsEnabled) Logging.Info(this, "Creating new AmqpConnection", $"{nameof(EnsureConnectionAsync)}"); // Create AmqpConnection amqpIoTConnection = await _amqpIoTConnector.OpenConnectionAsync(timeout).ConfigureAwait(false); if (_deviceIdentity.AuthenticationModel != AuthenticationModel.X509) { if (_deviceIdentity.AuthenticationModel == AuthenticationModel.SasGrouped) { if (Logging.IsEnabled) Logging.Info(this, "Creating connection width AmqpAuthenticationRefresher", $"{nameof(EnsureConnectionAsync)}"); amqpAuthenticationRefresher = new AmqpAuthenticationRefresher(_deviceIdentity, amqpIoTConnection.GetCbsLink()); await amqpAuthenticationRefresher.InitLoopAsync(timeout).ConfigureAwait(false); } } _amqpIoTConnection = amqpIoTConnection; _amqpAuthenticationRefresher = amqpAuthenticationRefresher; _amqpIoTConnection.Closed += OnConnectionClosed; if (Logging.IsEnabled) Logging.Associate(this, _amqpIoTConnection, $"{nameof(_amqpIoTConnection)}"); } else { amqpIoTConnection = _amqpIoTConnection; } } catch (Exception ex) when (!ex.IsFatal()) { amqpAuthenticationRefresher?.StopLoop(); amqpIoTConnection?.SafeClose(); throw; } finally { _lock.Release(); } if (Logging.IsEnabled) Logging.Exit(this, timeout, $"{nameof(EnsureConnectionAsync)}"); return amqpIoTConnection; } public void RemoveAmqpUnit(AmqpUnit amqpUnit) { if (Logging.IsEnabled) Logging.Enter(this, amqpUnit, $"{nameof(RemoveAmqpUnit)}"); lock (_unitsLock) { _amqpUnits.Remove(amqpUnit); if (_amqpUnits.Count == 0) { // TODO #887: handle gracefulDisconnect Shutdown(); } } if (Logging.IsEnabled) Logging.Exit(this, amqpUnit, $"{nameof(RemoveAmqpUnit)}"); } } }
44.280612
163
0.603987
[ "MIT" ]
CIPop/azure-iot-sdk-csharp
iothub/device/src/Transport/Amqp/AmqpConnectionHolder.cs
8,681
C#
using System; using System.Collections.Generic; using System.Text; namespace MxNet.GluonTS.Support { class Pandas { } }
12.181818
33
0.701493
[ "Apache-2.0" ]
AnshMittal1811/MxNet.Sharp
src/MxNet.GluonTS/Support/Pandas.cs
136
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Threading.Tasks; using CleanArchitecture.Razor.Application.Models; namespace CleanArchitecture.Razor.Application.Common.Interfaces { public interface IUploadService { Task<string> UploadAsync(UploadRequest request); } }
28
71
0.770408
[ "MIT" ]
urmatgit/RazorPageCleanArchitecture
src/Application/Common/Interfaces/IUploadService.cs
392
C#
using SimpleJsonLogger.Document; using SimpleJsonLogger.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; using DocumentDbClient.Context; using SimpleJsonLogger.DataContext; namespace SimpleJsonLogger.Util { public static class Bootstrap { public static void Init() { Unity.Instance.RegisterType<ILogDataService<LogDocument>, LogDataService>(); Unity.Instance.RegisterInstance<IDocumentDbContext>(new LogContext()); Unity.Instance.RegisterType<ILogBusinessService, LogBusinessService>(); } } }
27.12
88
0.741888
[ "MIT" ]
jlechowicz/SimpleJsonLogger
SimpleJsonLogger/Util/Bootstrap.cs
680
C#
using System; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using ManagedIrbis; using ManagedIrbis.Client; using ManagedIrbis.Infrastructure; using ManagedIrbis.Infrastructure.Transactions; namespace UnitTests.ManagedIrbis.Infrastructure.Transactions { [TestClass] public class IrbisTransactionEventArgsTest { [TestMethod] public void IrbisTransactionEventArgs_Construction_1() { IrbisProvider provider = new NullProvider(); IrbisTransactionContext context = new IrbisTransactionContext(); IrbisTransactionItem item = new IrbisTransactionItem(); IrbisTransactionEventArgs args = new IrbisTransactionEventArgs ( provider, context, item ); Assert.AreEqual(provider, args.Provider); Assert.AreEqual(context, args.Context); Assert.AreEqual(item, args.Item); } } }
29.735294
76
0.648863
[ "MIT" ]
amironov73/ManagedClient.45
Source/UnitTests/ManagedIrbis/Infrastructure/Transactions/IrbisTransactionEventArgsTest.cs
1,013
C#