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 Microsoft.Xna.Framework; using StardewValley; using Netcode; namespace ChildToNPC.Patches { /* Prefix for checkSchedule * This is a mix of code from the original method and my own. * I use reflection to access private methods in the NPC class. */ class NPCCheckSchedulePatch { public static bool Prefix(NPC __instance, int timeOfDay, ref Point ___previousEndPoint, ref string ___extraDialogueMessageToAddThisMorning, ref SchedulePathDescription ___directionsToNewLocation, ref Rectangle ___lastCrossroad, ref NetString ___endOfRouteBehaviorName) { if (!ModEntry.IsChildNPC(__instance)) return true; var scheduleTimeToTry = ModEntry.helper.Reflection.GetField<int>(__instance, "scheduleTimeToTry"); __instance.updatedDialogueYet = false; ___extraDialogueMessageToAddThisMorning = null; if (__instance.ignoreScheduleToday || __instance.Schedule == null) return false; __instance.Schedule.TryGetValue(scheduleTimeToTry.GetValue() == 9999999 ? timeOfDay : scheduleTimeToTry.GetValue(), out SchedulePathDescription schedulePathDescription); //If I have curfew, override the normal behavior if (ModEntry.Config.DoChildrenHaveCurfew && !__instance.currentLocation.Equals(Game1.getLocationFromName("FarmHouse"))) { //Send child home for curfew if(timeOfDay == ModEntry.Config.CurfewTime) { object[] pathfindParams = { __instance.currentLocation.Name, __instance.getTileX(), __instance.getTileY(), "BusStop", -1, 23, 3, null, null }; schedulePathDescription = ModEntry.helper.Reflection.GetMethod(__instance, "pathfindToNextScheduleLocation", true).Invoke<SchedulePathDescription>(pathfindParams); } //Ignore scheduled events after curfew else if(timeOfDay > ModEntry.Config.CurfewTime) { schedulePathDescription = null; } } if (schedulePathDescription == null) return false; //Normally I would see a IsMarried check here, but FarmHouse may be better? //(I think this section is meant for handling when the character is still walking) if (!__instance.currentLocation.Equals(Game1.getLocationFromName("FarmHouse")) || !__instance.IsWalkingInSquare || ___lastCrossroad.Center.X / 64 != ___previousEndPoint.X && ___lastCrossroad.Y / 64 != ___previousEndPoint.Y) { if (!___previousEndPoint.Equals(Point.Zero) && !___previousEndPoint.Equals(__instance.getTileLocationPoint())) { if (scheduleTimeToTry.GetValue() == 9999999) scheduleTimeToTry.SetValue(timeOfDay); return false; } } ___directionsToNewLocation = schedulePathDescription; //__instance.prepareToDisembarkOnNewSchedulePath(); ModEntry.helper.Reflection.GetMethod(__instance, "prepareToDisembarkOnNewSchedulePath", true).Invoke(null); if (__instance.Schedule == null) return false; if (___directionsToNewLocation != null && ___directionsToNewLocation.route != null && ___directionsToNewLocation.route.Count > 0 && (Math.Abs(__instance.getTileLocationPoint().X - ___directionsToNewLocation.route.Peek().X) > 1 || Math.Abs(__instance.getTileLocationPoint().Y - ___directionsToNewLocation.route.Peek().Y) > 1) && __instance.temporaryController == null) { scheduleTimeToTry.SetValue(9999999); return false; } __instance.controller = new PathFindController(___directionsToNewLocation.route, __instance, Utility.getGameLocationOfCharacter(__instance)) { finalFacingDirection = ___directionsToNewLocation.facingDirection, //endBehaviorFunction = this.getRouteEndBehaviorFunction(this.directionsToNewLocation.endOfRouteBehavior, this.directionsToNewLocation.endOfRouteMessage) endBehaviorFunction = ModEntry.helper.Reflection.GetMethod(__instance, "getRouteEndBehaviorFunction", true).Invoke<PathFindController.endBehavior>(new object[] { __instance.DirectionsToNewLocation.endOfRouteBehavior, __instance.DirectionsToNewLocation.endOfRouteMessage }) }; scheduleTimeToTry.SetValue(9999999); if (___directionsToNewLocation != null && ___directionsToNewLocation.route != null) ___previousEndPoint = ___directionsToNewLocation.route.Count > 0 ? ___directionsToNewLocation.route.Last() : Point.Zero; return false; } } }
55.842697
380
0.657948
[ "MIT" ]
Pathoschild/ChildToNPC
ChildToNPC/Patches/NPCCheckSchedulePatch.cs
4,972
C#
// Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet) // // Dirk Lemstra licenses this file to you under the Apache License, // version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at: // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Line.Tests { [TestClass] public class UserProfileTests { [TestMethod] public async Task GetProfile_UserIsNulll_ThrowsException() { ILineBot bot = TestConfiguration.CreateBot(); await ExceptionAssert.ThrowsArgumentNullExceptionAsync("user", async () => { IUserProfile profile = await bot.GetProfile((IUser)null); }); } [TestMethod] public async Task GetProfile_UserIdIsNull_ThrowsException() { ILineBot bot = TestConfiguration.CreateBot(); await ExceptionAssert.ThrowsArgumentNullExceptionAsync("userId", async () => { IUserProfile profile = await bot.GetProfile((string)null); }); } [TestMethod] public async Task GetProfile_UserIdIsEmpty_ThrowsException() { ILineBot bot = TestConfiguration.CreateBot(); await ExceptionAssert.ThrowsArgumentEmptyExceptionAsync("userId", async () => { IUserProfile profile = await bot.GetProfile(string.Empty); }); } [TestMethod] public async Task GetProfile_ErrorResponse_ThrowsException() { TestHttpClient httpClient = TestHttpClient.ThatReturnsAnError(); ILineBot bot = TestConfiguration.CreateBot(httpClient); await ExceptionAssert.ThrowsUnknownError(async () => { await bot.GetProfile("test"); }); } [TestMethod] [DeploymentItem(JsonDocuments.UserProfile)] public async Task GetProfile_CorrectResponse_ReturnsUserProfile() { TestHttpClient httpClient = TestHttpClient.Create(JsonDocuments.UserProfile); ILineBot bot = TestConfiguration.CreateBot(httpClient); IUserProfile profile = await bot.GetProfile("test"); Assert.AreEqual(HttpMethod.Get, httpClient.RequestMethod); Assert.AreEqual("/profile/test", httpClient.RequestPath); Assert.IsNotNull(profile); Assert.AreEqual("LINE taro", profile.DisplayName); Assert.AreEqual(new Uri("http://obs.line-apps.com/..."), profile.PictureUrl); Assert.AreEqual("Hello, LINE!", profile.StatusMessage); Assert.AreEqual("Uxxxxxxxxxxxxxx...", profile.UserId); } [TestMethod] [DeploymentItem(JsonDocuments.UserProfile)] public async Task GetProfile_WithUser_ReturnsUserProfile() { TestHttpClient httpClient = TestHttpClient.Create(JsonDocuments.UserProfile); ILineBot bot = TestConfiguration.CreateBot(httpClient); IUserProfile profile = await bot.GetProfile(new TestUser()); Assert.AreEqual("/profile/testUser", httpClient.RequestPath); Assert.IsNotNull(profile); } } }
36.970297
89
0.64917
[ "Apache-2.0" ]
charliedua/line-bot-sdk-dotnet
tests/LineBot.Tests/UserProfile/UserProfileTests.cs
3,736
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.Extensions.Logging; using Xunit; // ReSharper disable MemberHidesStaticFromOuterClass // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.ModelBuilding { public abstract partial class ModelBuilderTest { public abstract class InheritanceTestBase : ModelBuilderTestBase { [Fact] public virtual void Can_map_derived_types_first() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<AnotherBookLabel>(); modelBuilder.Ignore<Book>(); modelBuilder.Entity<ExtraSpecialBookLabel>() .HasBaseType(null) .Property(b => b.BookId); modelBuilder.Entity<SpecialBookLabel>() .HasBaseType(null) .Ignore(b => b.BookLabel) .Ignore(b => b.BookId); modelBuilder.Entity<BookLabel>(); modelBuilder.Entity<ExtraSpecialBookLabel>().HasBaseType<SpecialBookLabel>(); modelBuilder.Entity<SpecialBookLabel>().HasBaseType<BookLabel>(); modelBuilder.Entity<SpecialBookLabel>().Property(b => b.BookId); modelBuilder.Validate(); var model = modelBuilder.Model; Assert.Equal(0, model.FindEntityType(typeof(ExtraSpecialBookLabel)).GetDeclaredProperties().Count()); Assert.Equal(0, model.FindEntityType(typeof(SpecialBookLabel)).GetDeclaredProperties().Count()); Assert.NotNull(model.FindEntityType(typeof(SpecialBookLabel)).FindProperty(nameof(BookLabel.BookId))); } [Fact] public virtual void Base_types_are_mapped_correctly_if_discovered_last() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<AnotherBookLabel>(); modelBuilder.Ignore<Book>(); modelBuilder.Entity<ExtraSpecialBookLabel>(); modelBuilder.Entity<SpecialBookLabel>().Ignore(b => b.BookLabel); modelBuilder.Validate(); var model = modelBuilder.Model; var moreDerived = model.FindEntityType(typeof(ExtraSpecialBookLabel)); var derived = model.FindEntityType(typeof(SpecialBookLabel)); var baseType = model.FindEntityType(typeof(BookLabel)); Assert.Same(baseType, derived.BaseType); Assert.Same(derived, moreDerived.BaseType); } [Fact] public virtual void Can_map_derived_self_ref_many_to_one() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity<SelfRefManyToOneDerived>().HasData(new SelfRefManyToOneDerived { Id = 1, SelfRefId = 1 }); modelBuilder.Entity<SelfRefManyToOne>(); modelBuilder.Validate(); var model = modelBuilder.Model; Assert.Equal(0, model.FindEntityType(typeof(SelfRefManyToOneDerived)).GetDeclaredProperties().Count()); Assert.NotNull(model.FindEntityType(typeof(SelfRefManyToOne)).FindNavigation(nameof(SelfRefManyToOne.SelfRef1))); Assert.NotNull(model.FindEntityType(typeof(SelfRefManyToOne)).FindNavigation(nameof(SelfRefManyToOne.SelfRef2))); } [Fact] public virtual void Can_set_and_remove_base_type() { var modelBuilder = CreateModelBuilder(); var pickleBuilder = modelBuilder.Entity<Pickle>(); pickleBuilder.HasOne(e => e.BigMak).WithMany(e => e.Pickles); var pickle = pickleBuilder.Metadata; modelBuilder.Entity<BigMak>().Ignore(b => b.Bun); Assert.Null(pickle.BaseType); var pickleClone = modelBuilder.Model.Clone().FindEntityType(pickle.Name); var initialProperties = pickleClone.GetProperties().ToList(); var initialKeys = pickleClone.GetKeys().ToList(); var initialIndexes = pickleClone.GetIndexes().ToList(); var initialForeignKeys = pickleClone.GetForeignKeys().ToList(); var initialReferencingForeignKeys = pickleClone.GetReferencingForeignKeys().ToList(); pickleBuilder.HasBaseType<Ingredient>(); var ingredientBuilder = modelBuilder.Entity<Ingredient>(); var ingredient = ingredientBuilder.Metadata; Assert.Same(typeof(Ingredient), pickle.BaseType.ClrType); AssertEqual(initialProperties, pickle.GetProperties().Where(p => p.Name != "Discriminator"), new PropertyComparer(compareAnnotations: false)); AssertEqual(initialKeys, pickle.GetKeys()); AssertEqual(initialIndexes, pickle.GetIndexes()); AssertEqual(initialForeignKeys, pickle.GetForeignKeys()); AssertEqual(initialReferencingForeignKeys, pickle.GetReferencingForeignKeys()); pickleBuilder.HasBaseType(null); Assert.Null(pickle.BaseType); AssertEqual(initialProperties, pickle.GetProperties(), new PropertyComparer(compareAnnotations: false)); AssertEqual(initialKeys, pickle.GetKeys()); AssertEqual(initialIndexes, pickle.GetIndexes()); AssertEqual(initialForeignKeys, pickle.GetForeignKeys()); AssertEqual(initialReferencingForeignKeys, pickle.GetReferencingForeignKeys()); AssertEqual(initialProperties, ingredient.GetProperties().Where(p => p.Name != "Discriminator"), new PropertyComparer(compareAnnotations: false)); AssertEqual(initialKeys, ingredient.GetKeys()); AssertEqual(initialIndexes, ingredient.GetIndexes()); Assert.Equal(initialForeignKeys.Count(), ingredient.GetForeignKeys().Count()); Assert.Equal(initialReferencingForeignKeys.Count(), ingredient.GetReferencingForeignKeys().Count()); } [Fact] public virtual void Setting_base_type_to_null_fixes_relationships() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); modelBuilder.Ignore<BackOrder>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); principalEntityBuilder.Ignore(nameof(Customer.Orders)); var derivedPrincipalEntityBuilder = modelBuilder.Entity<SpecialCustomer>(); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.SpecialCustomer)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.ShippingAddress)); Assert.Same(principalEntityBuilder.Metadata, derivedPrincipalEntityBuilder.Metadata.BaseType); Assert.Same(dependentEntityBuilder.Metadata, derivedDependentEntityBuilder.Metadata.BaseType); var fk = dependentEntityBuilder.Metadata.GetNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), fk.DependentToPrincipal.Name); Assert.Null(fk.PrincipalToDependent); Assert.Same(principalEntityBuilder.Metadata, fk.PrincipalEntityType); var derivedFk = derivedPrincipalEntityBuilder.Metadata.GetNavigations().Single().ForeignKey; Assert.Null(derivedFk.DependentToPrincipal); Assert.Equal(nameof(SpecialCustomer.SpecialOrders), derivedFk.PrincipalToDependent.Name); Assert.Empty(derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations()); Assert.Empty(principalEntityBuilder.Metadata.GetNavigations()); derivedDependentEntityBuilder.HasBaseType(null); fk = dependentEntityBuilder.Metadata.GetNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), fk.DependentToPrincipal.Name); Assert.Null(fk.PrincipalToDependent); Assert.Same(principalEntityBuilder.Metadata, fk.PrincipalEntityType); derivedFk = derivedPrincipalEntityBuilder.Metadata.GetNavigations().Single().ForeignKey; var anotherDerivedFk = derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.NotSame(derivedFk, anotherDerivedFk); Assert.Null(derivedFk.DependentToPrincipal); Assert.Equal(nameof(SpecialCustomer.SpecialOrders), derivedFk.PrincipalToDependent.Name); Assert.Equal(nameof(Order.Customer), anotherDerivedFk.DependentToPrincipal.Name); Assert.Null(anotherDerivedFk.PrincipalToDependent); Assert.Same(principalEntityBuilder.Metadata, anotherDerivedFk.PrincipalEntityType); Assert.Empty(principalEntityBuilder.Metadata.GetNavigations()); } [Fact] public virtual void Pulling_relationship_to_a_derived_type_creates_relationships_on_other_derived_types() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); principalEntityBuilder.Ignore(nameof(Customer.Orders)); var derivedPrincipalEntityBuilder = modelBuilder.Entity<SpecialCustomer>(); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.BackOrder)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.SpecialCustomer)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.ShippingAddress)); var otherDerivedDependentEntityBuilder = modelBuilder.Entity<BackOrder>(); otherDerivedDependentEntityBuilder.Ignore(nameof(BackOrder.SpecialOrder)); Assert.Same(principalEntityBuilder.Metadata, derivedPrincipalEntityBuilder.Metadata.BaseType); Assert.Same(dependentEntityBuilder.Metadata, derivedDependentEntityBuilder.Metadata.BaseType); Assert.Same(dependentEntityBuilder.Metadata, otherDerivedDependentEntityBuilder.Metadata.BaseType); var fk = dependentEntityBuilder.Metadata.GetNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), fk.DependentToPrincipal.Name); Assert.Null(fk.PrincipalToDependent); Assert.Same(principalEntityBuilder.Metadata, fk.PrincipalEntityType); var derivedFk = derivedPrincipalEntityBuilder.Metadata.GetNavigations().Single().ForeignKey; Assert.Null(derivedFk.DependentToPrincipal); Assert.Equal(nameof(SpecialCustomer.SpecialOrders), derivedFk.PrincipalToDependent.Name); Assert.Empty(derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations()); Assert.Empty(otherDerivedDependentEntityBuilder.Metadata.GetDeclaredNavigations()); Assert.Empty(principalEntityBuilder.Metadata.GetNavigations()); derivedPrincipalEntityBuilder .HasMany(e => e.SpecialOrders) .WithOne(e => (SpecialCustomer)e.Customer); Assert.Empty(dependentEntityBuilder.Metadata.GetForeignKeys()); Assert.Empty(dependentEntityBuilder.Metadata.GetNavigations()); var newFk = derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), newFk.DependentToPrincipal.Name); Assert.Equal(nameof(SpecialCustomer.SpecialOrders), newFk.PrincipalToDependent.Name); Assert.Same(derivedPrincipalEntityBuilder.Metadata, newFk.PrincipalEntityType); var otherDerivedFk = otherDerivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), otherDerivedFk.DependentToPrincipal.Name); Assert.Null(otherDerivedFk.PrincipalToDependent); Assert.Equal(nameof(Order.CustomerId), otherDerivedFk.Properties.Single().Name); } [Fact] public virtual void Pulling_relationship_to_a_derived_type_reverted_creates_relationships_on_other_derived_types() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); principalEntityBuilder.Ignore(nameof(Customer.Orders)); var derivedPrincipalEntityBuilder = modelBuilder.Entity<SpecialCustomer>(); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.BackOrder)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.SpecialCustomer)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.ShippingAddress)); var otherDerivedDependentEntityBuilder = modelBuilder.Entity<BackOrder>(); otherDerivedDependentEntityBuilder.Ignore(nameof(BackOrder.SpecialOrder)); derivedDependentEntityBuilder .HasOne(e => (SpecialCustomer)e.Customer) .WithMany(e => e.SpecialOrders); Assert.Empty(dependentEntityBuilder.Metadata.GetForeignKeys()); Assert.Empty(dependentEntityBuilder.Metadata.GetNavigations()); var newFk = derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), newFk.DependentToPrincipal.Name); Assert.Equal(nameof(SpecialCustomer.SpecialOrders), newFk.PrincipalToDependent.Name); Assert.Same(derivedPrincipalEntityBuilder.Metadata, newFk.PrincipalEntityType); var otherDerivedFk = otherDerivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), otherDerivedFk.DependentToPrincipal.Name); Assert.Null(otherDerivedFk.PrincipalToDependent); Assert.Equal(nameof(Order.CustomerId), otherDerivedFk.Properties.Single().Name); } [Fact] public virtual void Pulling_relationship_to_a_derived_type_many_to_one_creates_relationships_on_other_derived_types() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); var derivedPrincipalEntityBuilder = modelBuilder.Entity<SpecialCustomer>(); var dependentEntityBuilder = modelBuilder.Entity<Order>(); dependentEntityBuilder.Ignore(nameof(Order.Customer)); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.BackOrder)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.ShippingAddress)); var otherDerivedPrincipalEntityBuilder = modelBuilder.Entity<OtherCustomer>(); derivedPrincipalEntityBuilder .HasMany(e => (IEnumerable<SpecialOrder>)e.Orders) .WithOne(e => e.SpecialCustomer); Assert.Empty(principalEntityBuilder.Metadata.GetNavigations()); var newFk = derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(SpecialOrder.SpecialCustomer), newFk.DependentToPrincipal.Name); Assert.Equal(nameof(SpecialCustomer.Orders), newFk.PrincipalToDependent.Name); Assert.Same(derivedPrincipalEntityBuilder.Metadata, newFk.PrincipalEntityType); var otherDerivedFk = otherDerivedPrincipalEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Null(otherDerivedFk.DependentToPrincipal); Assert.Equal(nameof(OtherCustomer.Orders), otherDerivedFk.PrincipalToDependent.Name); } [Fact] public virtual void Pulling_relationship_to_a_derived_type_one_to_one_creates_relationship_on_base() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<Customer>(); modelBuilder.Ignore<OrderDetails>(); var principalEntityBuilder = modelBuilder.Entity<OrderCombination>(); principalEntityBuilder.Ignore(nameof(OrderCombination.SpecialOrder)); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.BackOrder)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.SpecialCustomer)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.ShippingAddress)); principalEntityBuilder .HasOne(e => (SpecialOrder)e.Order) .WithOne(e => e.SpecialOrderCombination) .HasPrincipalKey<OrderCombination>(e => e.Id); Assert.Null(dependentEntityBuilder.Metadata.GetNavigations().Single().FindInverse()); var newFk = derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(SpecialOrder.SpecialOrderCombination), newFk.DependentToPrincipal.Name); Assert.Equal(nameof(OrderCombination.Order), newFk.PrincipalToDependent.Name); Assert.Same(derivedDependentEntityBuilder.Metadata, newFk.DeclaringEntityType); } [Fact] public virtual void Pulling_relationship_to_a_derived_type_one_to_one_with_fk_creates_relationship_on_base() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<Customer>(); modelBuilder.Ignore<OrderDetails>(); var principalEntityBuilder = modelBuilder.Entity<OrderCombination>(); principalEntityBuilder.Ignore(nameof(OrderCombination.SpecialOrder)); principalEntityBuilder.Ignore(nameof(OrderCombination.Details)); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.BackOrder)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.SpecialCustomer)); principalEntityBuilder .HasOne(e => (SpecialOrder)e.Order) .WithOne() .HasForeignKey<SpecialOrder>(e => e.SpecialCustomerId); Assert.Null(dependentEntityBuilder.Metadata.GetNavigations().Single().FindInverse()); var newFk = principalEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Null(newFk.DependentToPrincipal); Assert.Equal(nameof(OrderCombination.Order), newFk.PrincipalToDependent.Name); Assert.Same(derivedDependentEntityBuilder.Metadata, newFk.DeclaringEntityType); } [Fact] public virtual void Pulling_relationship_to_a_derived_type_with_fk_creates_relationships_on_other_derived_types() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); principalEntityBuilder.Ignore(nameof(Customer.Orders)); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.BackOrder)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.SpecialCustomer)); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.ShippingAddress)); var otherDerivedDependentEntityBuilder = modelBuilder.Entity<BackOrder>(); otherDerivedDependentEntityBuilder.Ignore(nameof(BackOrder.SpecialOrder)); derivedDependentEntityBuilder .HasOne(e => (SpecialCustomer)e.Customer) .WithMany() .HasForeignKey(e => e.SpecialCustomerId); Assert.Empty(dependentEntityBuilder.Metadata.GetForeignKeys()); Assert.Empty(dependentEntityBuilder.Metadata.GetNavigations()); var newFk = derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), newFk.DependentToPrincipal.Name); Assert.Null(newFk.PrincipalToDependent); var otherDerivedFk = otherDerivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(Order.Customer), otherDerivedFk.DependentToPrincipal.Name); Assert.Null(otherDerivedFk.PrincipalToDependent); Assert.Equal(nameof(Order.CustomerId), otherDerivedFk.Properties.Single().Name); } [Fact] public virtual void Can_promote_shadow_fk_to_the_base_type() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); modelBuilder.Ignore<BackOrder>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); principalEntityBuilder.Ignore(nameof(Customer.Orders)); var dependentEntityBuilder = modelBuilder.Entity<Order>(); dependentEntityBuilder.Ignore(e => e.Customer); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(e => e.SpecialCustomerId); derivedDependentEntityBuilder.Ignore(e => e.ShippingAddress); dependentEntityBuilder .HasOne<SpecialCustomer>() .WithMany() .HasForeignKey(nameof(SpecialOrder.SpecialCustomerId)); var newFk = dependentEntityBuilder.Metadata.GetDeclaredForeignKeys().Single(); Assert.NotEqual(newFk, derivedDependentEntityBuilder.Metadata.GetDeclaredForeignKeys().Single()); Assert.Null(newFk.DependentToPrincipal); Assert.Null(newFk.PrincipalToDependent); Assert.Equal(nameof(SpecialOrder.SpecialCustomerId), newFk.Properties.Single().Name); } [Fact] public virtual void Removing_a_key_triggers_fk_discovery_on_derived_types() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); modelBuilder.Ignore<BackOrder>(); modelBuilder.Ignore<OtherCustomer>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); var derivedPrincipalEntityBuilder = modelBuilder.Entity<SpecialCustomer>(); var dependentEntityBuilder = modelBuilder.Entity<Order>(); dependentEntityBuilder.Ignore(nameof(Order.Customer)); var derivedDependentEntityBuilder = modelBuilder.Entity<SpecialOrder>(); derivedDependentEntityBuilder.Ignore(nameof(SpecialOrder.ShippingAddress)); dependentEntityBuilder.Property<int?>("SpecialCustomerId"); derivedPrincipalEntityBuilder .HasMany(e => (IEnumerable<SpecialOrder>)e.Orders) .WithOne(e => e.SpecialCustomer); dependentEntityBuilder.HasKey("SpecialCustomerId"); dependentEntityBuilder.HasKey(o => o.OrderId); dependentEntityBuilder.Ignore("SpecialCustomerId"); derivedDependentEntityBuilder.Property(e => e.SpecialCustomerId); Assert.Null(dependentEntityBuilder.Metadata.FindProperty("SpecialCustomerId")); Assert.NotNull(derivedDependentEntityBuilder.Metadata.FindProperty("SpecialCustomerId")); Assert.Empty(principalEntityBuilder.Metadata.GetNavigations()); var newFk = derivedDependentEntityBuilder.Metadata.GetDeclaredNavigations().Single().ForeignKey; Assert.Equal(nameof(SpecialOrder.SpecialCustomer), newFk.DependentToPrincipal.Name); Assert.Equal(nameof(SpecialCustomer.Orders), newFk.PrincipalToDependent.Name); Assert.Same(derivedPrincipalEntityBuilder.Metadata, newFk.PrincipalEntityType); } [Fact] public virtual void Index_removed_when_covered_by_an_inherited_foreign_key() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); modelBuilder.Ignore<BackOrder>(); modelBuilder.Ignore<SpecialCustomer>(); var principalEntityBuilder = modelBuilder.Entity<Customer>(); var derivedPrincipalEntityBuilder = modelBuilder.Entity<OtherCustomer>(); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<BackOrder>(); principalEntityBuilder.HasMany(c => c.Orders).WithOne(o => o.Customer) .HasForeignKey(o => new { o.CustomerId, o.AnotherCustomerId }) .HasPrincipalKey(c => new { c.Id, c.AlternateKey }); derivedPrincipalEntityBuilder.HasMany<BackOrder>().WithOne() .HasForeignKey(o => new { o.CustomerId }) .HasPrincipalKey(c => new { c.Id }); var dependentEntityType = dependentEntityBuilder.Metadata; var derivedDependentEntityType = derivedDependentEntityBuilder.Metadata; var fk = dependentEntityType.GetForeignKeys().Single(); Assert.Equal(1, dependentEntityType.GetIndexes().Count()); Assert.False(dependentEntityType.FindIndex(fk.Properties).IsUnique); Assert.False(derivedDependentEntityType.GetDeclaredForeignKeys().Single().IsUnique); Assert.Empty(derivedDependentEntityType.GetDeclaredIndexes()); var backOrderClone = modelBuilder.Model.Clone().FindEntityType(derivedDependentEntityType.Name); var initialProperties = backOrderClone.GetProperties().ToList(); var initialKeys = backOrderClone.GetKeys().ToList(); var initialIndexes = backOrderClone.GetIndexes().ToList(); var initialForeignKeys = backOrderClone.GetForeignKeys().ToList(); derivedDependentEntityBuilder.HasBaseType(null); var derivedFk = derivedDependentEntityType.GetForeignKeys() .Single(foreignKey => foreignKey.PrincipalEntityType == derivedPrincipalEntityBuilder.Metadata); Assert.Equal(2, derivedDependentEntityType.GetIndexes().Count()); Assert.False(derivedDependentEntityType.FindIndex(derivedFk.Properties).IsUnique); derivedDependentEntityBuilder.HasBaseType<Order>(); fk = dependentEntityType.GetForeignKeys().Single(); Assert.Equal(1, dependentEntityType.GetIndexes().Count()); Assert.False(dependentEntityType.FindIndex(fk.Properties).IsUnique); Assert.False(derivedDependentEntityType.GetDeclaredForeignKeys().Single().IsUnique); Assert.Empty(derivedDependentEntityType.GetDeclaredIndexes()); AssertEqual(initialProperties, derivedDependentEntityType.GetProperties()); AssertEqual(initialKeys, derivedDependentEntityType.GetKeys()); AssertEqual(initialIndexes, derivedDependentEntityType.GetIndexes()); AssertEqual(initialForeignKeys, derivedDependentEntityType.GetForeignKeys()); Assert.Equal(1, modelBuilder.Log.Count); Assert.Equal(LogLevel.Debug, modelBuilder.Log[0].Level); Assert.Equal(CoreStrings.LogRedundantIndexRemoved.GenerateMessage("{'CustomerId'}", "{'CustomerId', 'AnotherCustomerId'}"), modelBuilder.Log[0].Message); principalEntityBuilder.HasOne<Order>().WithOne() .HasPrincipalKey<Customer>(c => new { c.Id }) .HasForeignKey<Order>(o => new { o.CustomerId }); fk = dependentEntityType.GetForeignKeys().Single(foreignKey => foreignKey.DependentToPrincipal == null); Assert.Equal(2, dependentEntityType.GetIndexes().Count()); Assert.True(dependentEntityType.FindIndex(fk.Properties).IsUnique); Assert.Empty(derivedDependentEntityType.GetDeclaredIndexes()); } [Fact] public virtual void Index_removed_when_covered_by_an_inherited_index() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<CustomerDetails>(); modelBuilder.Ignore<OrderDetails>(); modelBuilder.Ignore<BackOrder>(); modelBuilder.Ignore<SpecialCustomer>(); modelBuilder.Entity<Customer>(); var derivedPrincipalEntityBuilder = modelBuilder.Entity<OtherCustomer>(); var dependentEntityBuilder = modelBuilder.Entity<Order>(); var derivedDependentEntityBuilder = modelBuilder.Entity<BackOrder>(); dependentEntityBuilder.HasIndex(o => new { o.CustomerId, o.AnotherCustomerId }) .IsUnique(); derivedPrincipalEntityBuilder.HasMany<BackOrder>().WithOne() .HasPrincipalKey(c => new { c.Id }) .HasForeignKey(o => new { o.CustomerId }); modelBuilder.Validate(); var dependentEntityType = dependentEntityBuilder.Metadata; var derivedDependentEntityType = derivedDependentEntityBuilder.Metadata; var index = dependentEntityType.FindIndex(dependentEntityType.GetForeignKeys().Single().Properties); Assert.False(index.IsUnique); Assert.True(dependentEntityType.GetIndexes().Single(i => i != index).IsUnique); Assert.False(derivedDependentEntityType.GetDeclaredForeignKeys().Single().IsUnique); Assert.Empty(derivedDependentEntityType.GetDeclaredIndexes()); var backOrderClone = modelBuilder.Model.Clone().FindEntityType(derivedDependentEntityType.Name); var initialProperties = backOrderClone.GetProperties().ToList(); var initialKeys = backOrderClone.GetKeys().ToList(); var initialIndexes = backOrderClone.GetIndexes().ToList(); var initialForeignKeys = backOrderClone.GetForeignKeys().ToList(); var indexRemoveMessage = CoreStrings.LogRedundantIndexRemoved.GenerateMessage("{'CustomerId'}", "{'CustomerId', 'AnotherCustomerId'}"); Assert.Equal(1, modelBuilder.Log.Count(l => l.Message == indexRemoveMessage)); derivedDependentEntityBuilder.HasBaseType(null); var derivedFk = derivedDependentEntityType.GetForeignKeys() .Single(foreignKey => foreignKey.PrincipalEntityType == derivedPrincipalEntityBuilder.Metadata); Assert.Equal(2, derivedDependentEntityType.GetIndexes().Count()); Assert.False(derivedDependentEntityType.FindIndex(derivedFk.Properties).IsUnique); derivedDependentEntityBuilder.HasBaseType<Order>(); modelBuilder.Validate(); var baseFK = dependentEntityType.GetForeignKeys().Single(); var baseIndex = dependentEntityType.FindIndex(baseFK.Properties); Assert.False(baseIndex.IsUnique); Assert.True(dependentEntityType.GetIndexes().Single(i => i != baseIndex).IsUnique); Assert.False(derivedDependentEntityType.GetDeclaredForeignKeys().Single().IsUnique); Assert.Empty(derivedDependentEntityType.GetDeclaredIndexes()); AssertEqual(initialProperties, derivedDependentEntityType.GetProperties()); AssertEqual(initialKeys, derivedDependentEntityType.GetKeys()); AssertEqual(initialIndexes, derivedDependentEntityType.GetIndexes()); AssertEqual(initialForeignKeys, derivedDependentEntityType.GetForeignKeys()); Assert.Equal(2, modelBuilder.Log.Count(l => l.Message == indexRemoveMessage)); dependentEntityBuilder.HasIndex(o => new { o.CustomerId, o.AnotherCustomerId }) .IsUnique(false); Assert.True(dependentEntityType.GetIndexes().All(i => !i.IsUnique)); Assert.Empty(derivedDependentEntityType.GetDeclaredIndexes()); } [Fact] public virtual void Setting_base_type_handles_require_value_generator_properly() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<Customer>(); modelBuilder.Entity<OrderDetails>(); modelBuilder.Entity<SpecialOrder>(); var fkProperty = modelBuilder.Model.FindEntityType(typeof(OrderDetails)).FindProperty(OrderDetails.OrderIdProperty); Assert.Equal(ValueGenerated.Never, fkProperty.ValueGenerated); } [Fact] public virtual void Can_create_relationship_between_base_type_and_derived_type() { var modelBuilder = CreateModelBuilder(); var relationshipBuilder = modelBuilder.Entity<BookLabel>() .HasOne(e => e.SpecialBookLabel) .WithOne(e => e.BookLabel) .HasPrincipalKey<SpecialBookLabel>(e => e.Id); Assert.NotNull(relationshipBuilder); Assert.Equal(typeof(BookLabel), relationshipBuilder.Metadata.DeclaringEntityType.ClrType); Assert.Equal(typeof(SpecialBookLabel), relationshipBuilder.Metadata.PrincipalEntityType.ClrType); Assert.Equal(nameof(BookLabel.SpecialBookLabel), relationshipBuilder.Metadata.DependentToPrincipal.Name); Assert.Equal(nameof(SpecialBookLabel.BookLabel), relationshipBuilder.Metadata.PrincipalToDependent.Name); Assert.Equal(nameof(SpecialBookLabel.Id), relationshipBuilder.Metadata.PrincipalKey.Properties.Single().Name); } [Fact] public virtual void Removing_derived_type_make_sure_that_entity_type_is_removed_from_directly_derived_type() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity<Book>(); modelBuilder.Ignore<SpecialBookLabel>(); modelBuilder.Ignore<AnotherBookLabel>(); Assert.Empty(modelBuilder.Model.FindEntityType(typeof(BookLabel).FullName).GetDirectlyDerivedTypes()); } [Fact] public virtual void Can_ignore_base_entity_type() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity<SpecialBookLabel>(); modelBuilder.Entity<AnotherBookLabel>(); modelBuilder.Entity<Book>().HasOne<SpecialBookLabel>().WithOne().HasForeignKey<Book>(); modelBuilder.Ignore<BookLabel>(); var model = modelBuilder.Model; Assert.Null(model.FindEntityType(typeof(BookLabel).FullName)); foreach (var entityType in model.GetEntityTypes()) { Assert.Empty(entityType.GetForeignKeys() .Where(fk => fk.PrincipalEntityType.ClrType == typeof(BookLabel))); Assert.Empty(entityType.GetForeignKeys() .Where(fk => fk.PrincipalKey.DeclaringEntityType.ClrType == typeof(BookLabel))); } } [Fact] public virtual void Relationships_are_discovered_on_the_base_entity_type() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity<SpecialBookLabel>(); modelBuilder.Entity<AnotherBookLabel>(); var bookLabel = modelBuilder.Model.FindEntityType(typeof(BookLabel)); var specialNavigation = bookLabel.GetDeclaredNavigations().Single(n => n.Name == nameof(BookLabel.SpecialBookLabel)); Assert.Equal(typeof(SpecialBookLabel), specialNavigation.GetTargetType().ClrType); Assert.Equal(nameof(SpecialBookLabel.BookLabel), specialNavigation.FindInverse().Name); var anotherNavigation = bookLabel.GetDeclaredNavigations().Single(n => n.Name == nameof(BookLabel.AnotherBookLabel)); Assert.Equal(typeof(AnotherBookLabel), anotherNavigation.GetTargetType().ClrType); Assert.Null(anotherNavigation.FindInverse()); } [Fact] public virtual void Can_reconfigure_inherited_intraHierarchical_relationship() { var modelBuilder = CreateModelBuilder(); modelBuilder.Ignore<Book>(); var bookLabelEntityBuilder = modelBuilder.Entity<BookLabel>(); bookLabelEntityBuilder.Ignore(e => e.AnotherBookLabel); bookLabelEntityBuilder.HasOne(e => e.SpecialBookLabel) .WithOne(e => e.BookLabel) .HasPrincipalKey<BookLabel>(e => e.Id); var extraSpecialBookLabelEntityBuilder = modelBuilder.Entity<ExtraSpecialBookLabel>(); modelBuilder.Entity<SpecialBookLabel>() .HasOne(e => (ExtraSpecialBookLabel)e.SpecialBookLabel) .WithOne(e => (SpecialBookLabel)e.BookLabel); var fk = bookLabelEntityBuilder.Metadata.FindNavigation(nameof(BookLabel.SpecialBookLabel)).ForeignKey; Assert.Equal(nameof(SpecialBookLabel.BookLabel), fk.DependentToPrincipal.Name); Assert.Equal(new[] { fk }, extraSpecialBookLabelEntityBuilder.Metadata.GetForeignKeys()); } [Fact] public virtual void Relationships_on_derived_types_are_discovered_first_if_base_is_one_sided() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity<PersonBaseViewModel>(); Assert.Empty(modelBuilder.Model.FindEntityType(typeof(PersonBaseViewModel)).GetForeignKeys()); var citizen = modelBuilder.Model.FindEntityType(typeof(CitizenViewModel)); var citizenNavigation = citizen.GetDeclaredNavigations().Single(n => n.Name == nameof(CitizenViewModel.CityVM)); Assert.Equal(nameof(CityViewModel.People), citizenNavigation.FindInverse().Name); var doctor = modelBuilder.Model.FindEntityType(typeof(DoctorViewModel)); var doctorNavigation = doctor.GetDeclaredNavigations().Single(n => n.Name == nameof(CitizenViewModel.CityVM)); Assert.Equal(nameof(CityViewModel.Medics), doctorNavigation.FindInverse().Name); var police = modelBuilder.Model.FindEntityType(typeof(PoliceViewModel)); var policeNavigation = police.GetDeclaredNavigations().Single(n => n.Name == nameof(CitizenViewModel.CityVM)); Assert.Equal(nameof(CityViewModel.Police), policeNavigation.FindInverse().Name); Assert.Empty(modelBuilder.Model.FindEntityType(typeof(CityViewModel)).GetForeignKeys()); modelBuilder.Entity<CityViewModel>(); modelBuilder.Validate(); } [Fact] public virtual void Can_remove_objects_in_derived_type_which_was_set_using_data_annotation_while_setting_base_type_by_convention() { var modelBuilder = CreateModelBuilder(); var derivedEntityType = (EntityType)modelBuilder.Entity<DerivedTypeWithKeyAnnotation>().Metadata; var baseEntityType = (EntityType)modelBuilder.Entity<BaseTypeWithKeyAnnotation>().Metadata; Assert.Equal(baseEntityType, derivedEntityType.BaseType); Assert.Equal(ConfigurationSource.DataAnnotation, baseEntityType.GetPrimaryKeyConfigurationSource()); Assert.Equal(ConfigurationSource.DataAnnotation, baseEntityType.FindNavigation(nameof(BaseTypeWithKeyAnnotation.Navigation)).ForeignKey.GetConfigurationSource()); Assert.Equal(ConfigurationSource.Convention, derivedEntityType.GetBaseTypeConfigurationSource()); } [Fact] public virtual void Cannot_remove_objects_in_derived_type_which_was_set_using_explicit_while_setting_base_type_by_convention() { var modelBuilder = CreateModelBuilder(); var derivedEntityTypeBuilder = modelBuilder.Entity<DerivedTypeWithKeyAnnotation>(); derivedEntityTypeBuilder.HasKey(e => e.MyPrimaryKey); derivedEntityTypeBuilder.HasOne(e => e.Navigation).WithOne().HasForeignKey<DerivedTypeWithKeyAnnotation>(e => e.MyPrimaryKey); var derivedEntityType = (EntityType)derivedEntityTypeBuilder.Metadata; var baseEntityType = (EntityType)modelBuilder.Entity<BaseTypeWithKeyAnnotation>().Metadata; Assert.Null(derivedEntityType.BaseType); Assert.Equal(ConfigurationSource.DataAnnotation, baseEntityType.GetPrimaryKeyConfigurationSource()); Assert.Equal(ConfigurationSource.DataAnnotation, baseEntityType.FindNavigation(nameof(BaseTypeWithKeyAnnotation.Navigation)).ForeignKey.GetConfigurationSource()); Assert.Equal(ConfigurationSource.Explicit, derivedEntityType.FindNavigation(nameof(DerivedTypeWithKeyAnnotation.Navigation)).ForeignKey.GetConfigurationSource()); Assert.Equal(ConfigurationSource.Explicit, derivedEntityType.GetPrimaryKeyConfigurationSource()); } [Fact] public virtual void Ordering_of_entityType_discovery_does_not_affect_key_convention() { var modelBuilder = CreateModelBuilder(); var baseEntity = modelBuilder.Entity<StringIdBase>().Metadata; var derivedEntity = modelBuilder.Entity<StringIdDerived>().Metadata; Assert.Equal(baseEntity, derivedEntity.BaseType); Assert.NotNull(baseEntity.FindPrimaryKey()); var modelBuilder2 = CreateModelBuilder(); var derivedEntity2 = modelBuilder2.Entity<StringIdDerived>().Metadata; var baseEntity2 = modelBuilder2.Entity<StringIdBase>().Metadata; Assert.Equal(baseEntity2, derivedEntity2.BaseType); Assert.NotNull(baseEntity2.FindPrimaryKey()); } [Fact] // #7049 public void Base_type_can_be_discovered_after_creating_foreign_keys_on_derived() { var mb = CreateModelBuilder(); mb.Entity<AL>(); mb.Entity<L>(); Assert.Equal(ValueGenerated.OnAdd, mb.Model.FindEntityType(typeof(Q)).FindProperty(nameof(Q.ID)).ValueGenerated); } public class L { public int Id { get; set; } public IList<T> Ts { get; set; } } public class T : P { public Q D { get; set; } public P P { get; set; } public Q F { get; set; } } public class P : PBase { } public class Q : PBase { } public abstract class PBase { public int ID { get; set; } public string Stuff { get; set; } } public class AL { public int Id { get; set; } public PBase L { get; set; } } } } }
57.107407
178
0.649437
[ "Apache-2.0" ]
chrisblock/EntityFramework
test/EFCore.Tests/ModelBuilding/InheritanceTestBase.cs
46,257
C#
using System; namespace TodoWeb.web.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
17.5
70
0.661905
[ "MIT" ]
Dera9q/TodoWeb
src/TodoWeb.web/Models/ErrorViewModel.cs
210
C#
using System; using System.Diagnostics; using System.Resources; using System.Windows; using System.Windows.Markup; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using XamlSamples.WinPhone.Resources; namespace XamlSamples.WinPhone { public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Application. /// </summary> /// <returns>The root frame of the Phone Application.</returns> public static PhoneApplicationFrame RootFrame { get; private set; } /// <summary> /// Constructor for the Application object. /// </summary> public App() { // Global handler for uncaught exceptions. UnhandledException += Application_UnhandledException; // Standard XAML initialization InitializeComponent(); // Phone-specific initialization InitializePhoneApplication(); // Language display initialization InitializeLanguage(); // Show graphics profiling information while debugging. if (Debugger.IsAttached) { // Display the current frame rate counters. Application.Current.Host.Settings.EnableFrameRateCounter = true; // Show the areas of the app that are being redrawn in each frame. //Application.Current.Host.Settings.EnableRedrawRegions = true; // Enable non-production analysis visualization mode, // which shows areas of a page that are handed off to GPU with a colored overlay. //Application.Current.Host.Settings.EnableCacheVisualization = true; // Prevent the screen from turning off while under the debugger by disabling // the application's idle detection. // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run // and consume battery power when the user is not using the phone. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } } // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { } // Code to execute when the application is activated (brought to foreground) // This code will not execute when the application is first launched private void Application_Activated(object sender, ActivatedEventArgs e) { } // Code to execute when the application is deactivated (sent to background) // This code will not execute when the application is closing private void Application_Deactivated(object sender, DeactivatedEventArgs e) { } // Code to execute when the application is closing (eg, user hit Back) // This code will not execute when the application is deactivated private void Application_Closing(object sender, ClosingEventArgs e) { } // Code to execute if a navigation fails private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e) { if (Debugger.IsAttached) { // A navigation has failed; break into the debugger Debugger.Break(); } } // Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger Debugger.Break(); } } #region Phone application initialization // Avoid double-initialization private bool phoneApplicationInitialized = false; // Do not add any additional code to this method private void InitializePhoneApplication() { if (phoneApplicationInitialized) return; // Create the frame but don't set it as RootVisual yet; this allows the splash // screen to remain active until the application is ready to render. RootFrame = new PhoneApplicationFrame(); RootFrame.Navigated += CompleteInitializePhoneApplication; // Handle navigation failures RootFrame.NavigationFailed += RootFrame_NavigationFailed; // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; // Ensure we don't initialize again phoneApplicationInitialized = true; } // Do not add any additional code to this method private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e) { // Set the root visual to allow the application to render if (RootVisual != RootFrame) RootVisual = RootFrame; // Remove this handler since it is no longer needed RootFrame.Navigated -= CompleteInitializePhoneApplication; } private void CheckForResetNavigation(object sender, NavigationEventArgs e) { // If the app has received a 'reset' navigation, then we need to check // on the next navigation to see if the page stack should be reset if (e.NavigationMode == NavigationMode.Reset) RootFrame.Navigated += ClearBackStackAfterReset; } private void ClearBackStackAfterReset(object sender, NavigationEventArgs e) { // Unregister the event so it doesn't get called again RootFrame.Navigated -= ClearBackStackAfterReset; // Only clear the stack for 'new' (forward) and 'refresh' navigations if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh) return; // For UI consistency, clear the entire page stack while (RootFrame.RemoveBackEntry() != null) { ; // do nothing } } #endregion // Initialize the app's font and flow direction as defined in its localized resource strings. // // To ensure that the font of your application is aligned with its supported languages and that the // FlowDirection for each of those languages follows its traditional direction, ResourceLanguage // and ResourceFlowDirection should be initialized in each resx file to match these values with that // file's culture. For example: // // AppResources.es-ES.resx // ResourceLanguage's value should be "es-ES" // ResourceFlowDirection's value should be "LeftToRight" // // AppResources.ar-SA.resx // ResourceLanguage's value should be "ar-SA" // ResourceFlowDirection's value should be "RightToLeft" // // For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072. // private void InitializeLanguage() { try { // Set the font to match the display language defined by the // ResourceLanguage resource string for each supported language. // // Fall back to the font of the neutral language if the Display // language of the phone is not supported. // // If a compiler error is hit then ResourceLanguage is missing from // the resource file. RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage); // Set the FlowDirection of all elements under the root frame based // on the ResourceFlowDirection resource string for each // supported language. // // If a compiler error is hit then ResourceFlowDirection is missing from // the resource file. FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection); RootFrame.FlowDirection = flow; } catch { // If an exception is caught here it is most likely due to either // ResourceLangauge not being correctly set to a supported language // code or ResourceFlowDirection is set to a value other than LeftToRight // or RightToLeft. if (Debugger.IsAttached) { Debugger.Break(); } throw; } } } }
41.397321
128
0.599806
[ "Apache-2.0" ]
Arlenxiao/xamarin-forms-samples
XAMLSamples/xamlsamples/xamlsamples.winphone/App.xaml.cs
9,275
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Ocelot.IntegrationTests")] [assembly: AssemblyTrademark("")] // 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("d4575572-99ca-4530-8737-c296eda326f8")]
42.684211
85
0.763255
[ "MIT" ]
520xchly/Ocelot
test/Ocelot.IntegrationTests/Properties/AssemblyInfo.cs
813
C#
using System; using System.Collections.Generic; using System.Text; using System.Data; using GDC.PH.AIDE.BusinessLayer.DataLayer; namespace GDC.PH.AIDE.BusinessLayer { public class clsProblemFactory { #region data Members clsProblemSql _dataObject = null; #endregion #region Constructor public clsProblemFactory() { _dataObject = new clsProblemSql(); } #endregion #region Public Methods - Problems public bool InsertProblem(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.InsertProblem(businessObject); } public bool UpdateProblem(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.UpdateProblem(businessObject); } public List<clsProblem> GetAllProblems(int empID) { return _dataObject.GetAllProblems(empID); } #endregion #region Public Methods - Problem Cause public bool InsertProblemCause(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.InsertProblemCause(businessObject); } public bool UpdateProblemCause(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.UpdateProblemCause(businessObject); } public List<clsProblem> GetAllProblemCause() { return _dataObject.GetAllProblemCause(); } #endregion #region Public Methods - Problem Option public bool InsertProblemOption(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.InsertProblemOption(businessObject); } public bool UpdateProblemOption(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.UpdateProblemOption(businessObject); } public List<clsProblem> GetAllProblemOption() { return _dataObject.GetAllProblemOption(); } #endregion #region Public Methods - Problem Solution public bool InsertProblemSolution(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.InsertProblemSolution(businessObject); } public bool UpdateProblemSolution(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.UpdateProblemSolution(businessObject); } public List<clsProblem> GetAllProblemSolution() { return _dataObject.GetAllProblemSolution(); } #endregion #region Public Methods - Problem Implement public bool InsertProblemImplement(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.InsertProblemImplement(businessObject); } public bool UpdateProblemImplement(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.UpdateProblemImplement(businessObject); } public List<clsProblem> GetAllProblemImplement() { return _dataObject.GetAllProblemImplement(); } #endregion #region Public Methods - Problem Result public bool InsertProblemResult(clsProblem businessObject) { if (!businessObject.IsValid) { throw new InvalidBusinessObjectException(businessObject.BrokenRulesList.ToString()); } return _dataObject.InsertProblemResult(businessObject); } public List<clsProblem> GetAllProblemResult(int problemID, int optionID) { return _dataObject.GetAllProblemResult(problemID, optionID); } #endregion } }
30.038462
101
0.593378
[ "BSD-3-Clause" ]
rsx-labs/aide-backend
AIDEBackendMaster/GDC.PH.AIDE.BusinessLayer/clsProblemFactory.cs
5,469
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.Collections; using System.Text; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Build.UnitTests { /// <summary> /// Most of the common ResolveNonMSBuildOutput/AssignProjectConfiguration functionality is tested /// in ResolveNonMSBuildProjectOutput_Tests. /// Here, only test the AssignProjectConfiguration specific code /// </summary> [TestClass] sealed public class AssignProjectConfiguration_Tests { private void TestResolveHelper(string itemSpec, string projectGuid, string package, string name, Hashtable pregenConfigurations, bool expectedResult, string expectedFullConfiguration, string expectedConfiguration, string expectedPlatform) { ITaskItem reference = ResolveNonMSBuildProjectOutput_Tests.CreateReferenceItem(itemSpec, projectGuid, package, name); // Use the XML string generation method from our sister class - XML element names will be different, // but they are ignored anyway, and the rest is identical string xmlString = ResolveNonMSBuildProjectOutput_Tests.CreatePregeneratedPathDoc(pregenConfigurations); ITaskItem resolvedProjectWithConfiguration; AssignProjectConfiguration rpc = new AssignProjectConfiguration(); rpc.SolutionConfigurationContents = xmlString; rpc.CacheProjectElementsFromXml(xmlString); bool result = rpc.ResolveProject(reference, out resolvedProjectWithConfiguration); string message = string.Format("Reference \"{0}\" [project \"{1}\", package \"{2}\", name \"{3}\"] Pregen Xml string : \"{4}\"" + "expected result \"{5}\", actual result \"{6}\", expected configuration \"{7}\", actual configuration \"{8}\".", itemSpec, projectGuid, package, name, xmlString, expectedResult, result, expectedFullConfiguration, (resolvedProjectWithConfiguration == null) ? string.Empty : resolvedProjectWithConfiguration.GetMetadata("FullConfiguration")); Assert.AreEqual(expectedResult, result, message); if (result == true) { Assert.AreEqual(expectedFullConfiguration, resolvedProjectWithConfiguration.GetMetadata("FullConfiguration")); Assert.AreEqual(expectedConfiguration, resolvedProjectWithConfiguration.GetMetadata("Configuration")); Assert.AreEqual(expectedPlatform, resolvedProjectWithConfiguration.GetMetadata("Platform")); Assert.AreEqual("Configuration=" + expectedConfiguration, resolvedProjectWithConfiguration.GetMetadata("SetConfiguration")); Assert.AreEqual("Platform=" + expectedPlatform, resolvedProjectWithConfiguration.GetMetadata("SetPlatform")); Assert.AreEqual(reference.ItemSpec, resolvedProjectWithConfiguration.ItemSpec); } else { Assert.AreEqual(null, resolvedProjectWithConfiguration); } } [TestMethod] public void TestResolve() { // empty pre-generated string Hashtable projectOutputs = new Hashtable(); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null, null, null); // non matching project in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"Debug|Win32"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null, null, null); // matching projects in string projectOutputs = new Hashtable(); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"Debug|Win32"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-666666666666}", @"Debug"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, @"Debug|Win32", "Debug", "Win32"); TestResolveHelper("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-666666666666}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, @"Debug", "Debug", string.Empty); // multiple non matching projects in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"Config1|Win32"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"Config2|AnyCPU"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"Config3|AnyCPU"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null, null, null); // multiple non matching projects in string, two matching projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"Config1|Win32"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"Config2|AnyCPU"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"Config3|AnyCPU"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"CorrectProjectConfig|Platform"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-666666666666}", @"JustConfig"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, @"CorrectProjectConfig|Platform", "CorrectProjectConfig", "Platform"); TestResolveHelper("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-666666666666}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, @"JustConfig", "JustConfig", string.Empty); } /// <summary> /// Test the case where the project reference does not have either of the metadata set on it. /// /// We would expect the following case: /// /// 1) The xml element does not have the BuildProjectInSolution attribute set /// Expect none of the metadata to be set /// </summary> [TestMethod] public void TestReferenceWithNoMetadataBadBuildInProjectAttribute() { // Test the case where the metadata is missing and we are not supposed to build the reference ITaskItem referenceItem = new TaskItem("TestItem"); XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("TestElement"); element.SetAttribute("BuildProjectInSolution", "IAmReallyABadOne"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(true, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Length == 0); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Length == 0); } /// <summary> /// Test the case where the project reference does not have either of the metadata set on it. /// /// We would expect the following case: /// /// 1) The xml element does not have the BuildProjectInSolution attribute set /// Expect none of the metadata to be set /// </summary> [TestMethod] public void TestReferenceWithNoMetadataNoBuildInProjectAttribute() { // Test the case where the metadata is missing and we are not supposed to build the reference ITaskItem referenceItem = new TaskItem("TestItem"); XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("TestElement"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(true, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Length == 0); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Length == 0); } /// <summary> /// Test the case where the project reference does not have either of the metadata set on it. /// /// We would expect the following case: /// 1) The xml element has BuildProjectInSolution set to true /// Expect none of the metadata to be set /// </summary> [TestMethod] public void TestReferenceWithNoMetadataBuildInProjectAttributeTrue() { // Test the case where the metadata is missing and we are not supposed to build the reference ITaskItem referenceItem = new TaskItem("TestItem"); XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("TestElement"); element.SetAttribute("BuildProjectInSolution", "true"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(true, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Length == 0); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Length == 0); } /// <summary> /// Test the case where the project reference does not have either of the metadata set on it. /// /// We would expect the following case: /// ReferenceAndBuildProjectsDisabledInProjectConfiguration is set to true meaning we want to build disabled projects. /// /// 1) The xml element has BuildProjectInSolution set to false /// Expect no pieces of metadata to be set on the reference item /// </summary> [TestMethod] public void TestReferenceWithNoMetadataBuildInProjectAttributeFalseReferenceAndBuildProjectsDisabledInProjectConfiguration() { // Test the case where the metadata is missing and we are not supposed to build the reference ITaskItem referenceItem = new TaskItem("TestItem"); XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("TestElement"); element.SetAttribute("BuildProjectInSolution", "false"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(false, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Length == 0); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Length == 0); } /// <summary> /// Test the case where the project reference does not have either of the metadata set on it. /// /// We would expect the following case: /// 1) The xml element has BuildProjectInSolution set to false /// Expect two pieces of metadata to be put on the item and be set to false (BuildReference, and ReferenceOutputAssembly) /// </summary> [TestMethod] public void TestReferenceWithNoMetadataBuildInProjectAttributeFalse() { // Test the case where the metadata is missing and we are not supposed to build the reference ITaskItem referenceItem = new TaskItem("TestItem"); XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("TestElement"); element.SetAttribute("BuildProjectInSolution", "false"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(true, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Equals("false", StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Equals("false", StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Test the case where the project reference does has one or more of the metadata set on it. /// /// We would expect the following case: /// 1) The xml element has BuildProjectInSolution set to false /// Expect two pieces of metadata to be put on the item and be set to true since they were already set (BuildReference, and ReferenceOutputAssembly) /// </summary> [TestMethod] public void TestReferenceWithMetadataAlreadySetBuildInProjectAttributeFalse() { // Test the case where the metadata is missing and we are not supposed to build the reference ITaskItem referenceItem = new TaskItem("TestItem"); referenceItem.SetMetadata("BuildReference", "true"); referenceItem.SetMetadata("ReferenceOutputAssembly", "true"); XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("TestElement"); element.SetAttribute("BuildProjectInSolution", "false"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(true, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Equals("true", StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Equals("true", StringComparison.OrdinalIgnoreCase)); // Test the case where only ReferenceOutputAssembly is not set referenceItem = new TaskItem("TestItem"); referenceItem.SetMetadata("BuildReference", "true"); doc = new XmlDocument(); element = doc.CreateElement("TestElement"); element.SetAttribute("BuildProjectInSolution", "false"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(true, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Equals("true", StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Equals("false", StringComparison.OrdinalIgnoreCase)); // Test the case where only BuildReference is not set referenceItem = new TaskItem("TestItem"); referenceItem.SetMetadata("ReferenceOutputAssembly", "true"); doc = new XmlDocument(); element = doc.CreateElement("TestElement"); element.SetAttribute("BuildProjectInSolution", "false"); AssignProjectConfiguration.SetBuildInProjectAndReferenceOutputAssemblyMetadata(true, referenceItem, element); Assert.IsTrue(referenceItem.GetMetadata("BuildReference").Equals("false", StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(referenceItem.GetMetadata("ReferenceOutputAssembly").Equals("true", StringComparison.OrdinalIgnoreCase)); } private void TestUnresolvedReferencesHelper(ArrayList projectRefs, Hashtable pregenConfigurations, out Hashtable unresolvedProjects, out Hashtable resolvedProjects) { // Use the XML string generation method from our sister class - XML element names will be different, // but they are ignored anyway, and the rest is identical string xmlString = ResolveNonMSBuildProjectOutput_Tests.CreatePregeneratedPathDoc(pregenConfigurations); MockEngine engine = new MockEngine(); AssignProjectConfiguration rpc = new AssignProjectConfiguration(); rpc.BuildEngine = engine; rpc.SolutionConfigurationContents = xmlString; rpc.ProjectReferences = (ITaskItem[])projectRefs.ToArray(typeof(ITaskItem)); bool result = rpc.Execute(); unresolvedProjects = new Hashtable(); for (int i = 0; i < rpc.UnassignedProjects.Length; i++) { unresolvedProjects[rpc.UnassignedProjects[i].ItemSpec] = rpc.UnassignedProjects[i]; } resolvedProjects = new Hashtable(); for (int i = 0; i < rpc.AssignedProjects.Length; i++) { resolvedProjects[rpc.AssignedProjects[i].GetMetadata("FullConfiguration")] = rpc.AssignedProjects[i]; } } /// <summary> /// Verifies that the UnresolvedProjectReferences output parameter is populated correctly. /// </summary> [TestMethod] public void TestUnresolvedReferences() { Hashtable unresolvedProjects = null; Hashtable resolvedProjects = null; Hashtable projectConfigurations = null; ArrayList projectRefs = null; projectRefs = new ArrayList(); projectRefs.Add(ResolveNonMSBuildProjectOutput_Tests.CreateReferenceItem("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-000000000000}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1")); projectRefs.Add(ResolveNonMSBuildProjectOutput_Tests.CreateReferenceItem("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep2")); // 1. multiple projects, none resolvable projectConfigurations = new Hashtable(); projectConfigurations.Add("{11111111-1111-1111-1111-111111111111}", @"Config1|Win32"); projectConfigurations.Add("{11111111-1111-1111-1111-111111111112}", @"Config2|AnyCPU"); projectConfigurations.Add("{11111111-1111-1111-1111-111111111113}", @"Config3|AnyCPU"); TestUnresolvedReferencesHelper(projectRefs, projectConfigurations, out unresolvedProjects, out resolvedProjects); Assert.IsTrue(resolvedProjects.Count == 0, "No resolved refs expected for case 1"); Assert.IsTrue(unresolvedProjects.Count == 2, "Two unresolved refs expected for case 1"); Assert.IsTrue(unresolvedProjects["MCDep1.vcproj"] == projectRefs[0]); Assert.IsTrue(unresolvedProjects["MCDep2.vcproj"] == projectRefs[1]); // 2. multiple projects, one resolvable projectConfigurations = new Hashtable(); projectConfigurations.Add("{11111111-1111-1111-1111-111111111111}", @"Config1|Win32"); projectConfigurations.Add("{11111111-1111-1111-1111-111111111112}", @"Config2|AnyCPU"); projectConfigurations.Add("{11111111-1111-1111-1111-111111111113}", @"Config3|AnyCPU"); projectConfigurations.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"CorrectProjectConfig|Platform"); TestUnresolvedReferencesHelper(projectRefs, projectConfigurations, out unresolvedProjects, out resolvedProjects); Assert.IsTrue(resolvedProjects.Count == 1, "One resolved ref expected for case 2"); Assert.IsTrue(resolvedProjects.ContainsKey(@"CorrectProjectConfig|Platform")); Assert.IsTrue(unresolvedProjects.Count == 1, "One unresolved ref expected for case 2"); Assert.IsTrue(unresolvedProjects["MCDep1.vcproj"] == projectRefs[0]); // 3. multiple projects, all resolvable projectConfigurations = new Hashtable(); projectConfigurations.Add("{11111111-1111-1111-1111-111111111111}", @"Config1|Win32"); projectConfigurations.Add("{11111111-1111-1111-1111-111111111112}", @"Config2|AnyCPU"); projectConfigurations.Add("{11111111-1111-1111-1111-111111111113}", @"Config3|AnyCPU"); projectConfigurations.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"CorrectProjectConfig|Platform"); projectConfigurations.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @"CorrectProjectConfig2|Platform"); TestUnresolvedReferencesHelper(projectRefs, projectConfigurations, out unresolvedProjects, out resolvedProjects); Assert.IsTrue(resolvedProjects.Count == 2, "Two resolved refs expected for case 3"); Assert.IsTrue(resolvedProjects.ContainsKey(@"CorrectProjectConfig|Platform")); Assert.IsTrue(resolvedProjects.ContainsKey(@"CorrectProjectConfig2|Platform")); Assert.IsTrue(unresolvedProjects.Count == 0, "No unresolved refs expected for case 3"); } #region Test Defaults /// <summary> /// Verify if no values are passed in for certain properties that their default values are used. /// </summary> [TestMethod] public void VerifyDefaultValueDefaultToVcxPlatformMappings() { string expectedDefaultToVcxPlatformMapping = "AnyCPU=Win32;X86=Win32;X64=X64;Itanium=Itanium"; AssignProjectConfiguration assignProjectConfiguration = new AssignProjectConfiguration(); /// Test defaults with nothign set string actualDefaultToVcxPlatformMapping = assignProjectConfiguration.DefaultToVcxPlatformMapping; Assert.IsTrue(expectedDefaultToVcxPlatformMapping.Equals(actualDefaultToVcxPlatformMapping, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedDefaultToVcxPlatformMapping, actualDefaultToVcxPlatformMapping)); assignProjectConfiguration.DefaultToVcxPlatformMapping = String.Empty; actualDefaultToVcxPlatformMapping = assignProjectConfiguration.DefaultToVcxPlatformMapping; Assert.IsTrue(expectedDefaultToVcxPlatformMapping.Equals(actualDefaultToVcxPlatformMapping, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedDefaultToVcxPlatformMapping, actualDefaultToVcxPlatformMapping)); assignProjectConfiguration.DefaultToVcxPlatformMapping = null; actualDefaultToVcxPlatformMapping = assignProjectConfiguration.DefaultToVcxPlatformMapping; Assert.IsTrue(expectedDefaultToVcxPlatformMapping.Equals(actualDefaultToVcxPlatformMapping, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedDefaultToVcxPlatformMapping, actualDefaultToVcxPlatformMapping)); } /// <summary> /// Verify if no values are passed in for certain properties that their default values are used. /// </summary> [TestMethod] public void VerifyDefaultValuesVcxToDefaultPlatformMappingNoOutput() { string expectedVcxToDefaultPlatformMappingNoOutput = "Win32=X86;X64=X64;Itanium=Itanium"; AssignProjectConfiguration assignProjectConfiguration = new AssignProjectConfiguration(); // Test the case for VcxToDefaultPlatformMapping when the outputType is not library string actualVcxToDefaultPlatformMappingNoOutput = assignProjectConfiguration.VcxToDefaultPlatformMapping; Assert.IsTrue(expectedVcxToDefaultPlatformMappingNoOutput.Equals(actualVcxToDefaultPlatformMappingNoOutput, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedVcxToDefaultPlatformMappingNoOutput, actualVcxToDefaultPlatformMappingNoOutput)); assignProjectConfiguration.VcxToDefaultPlatformMapping = String.Empty; actualVcxToDefaultPlatformMappingNoOutput = assignProjectConfiguration.VcxToDefaultPlatformMapping; Assert.IsTrue(expectedVcxToDefaultPlatformMappingNoOutput.Equals(actualVcxToDefaultPlatformMappingNoOutput, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedVcxToDefaultPlatformMappingNoOutput, actualVcxToDefaultPlatformMappingNoOutput)); assignProjectConfiguration.VcxToDefaultPlatformMapping = null; actualVcxToDefaultPlatformMappingNoOutput = assignProjectConfiguration.VcxToDefaultPlatformMapping; Assert.IsTrue(expectedVcxToDefaultPlatformMappingNoOutput.Equals(actualVcxToDefaultPlatformMappingNoOutput, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedVcxToDefaultPlatformMappingNoOutput, actualVcxToDefaultPlatformMappingNoOutput)); } /// <summary> /// Verify if no values are passed in for certain properties that their default values are used. /// </summary> [TestMethod] public void VerifyDefaultValuesVcxToDefaultPlatformMappingLibraryOutput() { string expectedVcxToDefaultPlatformMappingLibraryOutput = "Win32=AnyCPU;X64=X64;Itanium=Itanium"; AssignProjectConfiguration assignProjectConfiguration = new AssignProjectConfiguration(); // Test the case for VcxToDefaultPlatformMapping when the outputType is library assignProjectConfiguration.OutputType = "Library"; string actualVcxToDefaultPlatformMappingNoOutput = assignProjectConfiguration.VcxToDefaultPlatformMapping; Assert.IsTrue(expectedVcxToDefaultPlatformMappingLibraryOutput.Equals(actualVcxToDefaultPlatformMappingNoOutput, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedVcxToDefaultPlatformMappingLibraryOutput, actualVcxToDefaultPlatformMappingNoOutput)); assignProjectConfiguration.VcxToDefaultPlatformMapping = String.Empty; actualVcxToDefaultPlatformMappingNoOutput = assignProjectConfiguration.VcxToDefaultPlatformMapping; Assert.IsTrue(expectedVcxToDefaultPlatformMappingLibraryOutput.Equals(actualVcxToDefaultPlatformMappingNoOutput, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedVcxToDefaultPlatformMappingLibraryOutput, actualVcxToDefaultPlatformMappingNoOutput)); assignProjectConfiguration.VcxToDefaultPlatformMapping = null; actualVcxToDefaultPlatformMappingNoOutput = assignProjectConfiguration.VcxToDefaultPlatformMapping; Assert.IsTrue(expectedVcxToDefaultPlatformMappingLibraryOutput.Equals(actualVcxToDefaultPlatformMappingNoOutput, StringComparison.OrdinalIgnoreCase), String.Format("Expected '{0}' but found '{1}'", expectedVcxToDefaultPlatformMappingLibraryOutput, actualVcxToDefaultPlatformMappingNoOutput)); } #endregion } }
64.956416
305
0.688187
[ "MIT" ]
OmniSharp/msbuild
src/XMakeTasks/UnitTests/AssignProjectConfiguration_Tests.cs
26,417
C#
namespace NewPlatform.Flexberry.Caching { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; public partial class MemoryCacheService { /// <inheritdoc cref="ICacheService" /> public string CacheName => _cache?.Name; /// <inheritdoc cref="ICacheService" /> /// <remarks> /// Information about each tag is also stored in cache. /// So total number of cached items will include corresponding count of items with information about tags. /// </remarks> public long GetCount() { return _cache.GetCount(); } /// <inheritdoc cref="ICacheService" /> /// <remarks> /// Information about tags deleted from cache only when cahce is totally clearing. /// So cache will store infromation about ever added tags until chache is totally cleared. /// </remarks> public long GetTagsCount() { return _cache.Count(item => item.Value is TagItem); } /// <inheritdoc cref="ICacheService" /> public IEnumerable<string> GetTagsForItem(string key) { var cacheItem = (CacheItem)_cache.Get(key); if (cacheItem == null || !IsCacheItemValidated(cacheItem)) { throw new KeyNotFoundException($"Key \"{key}\" is not found in cache."); } return cacheItem.Tags.Select(tags => tags.Key).ToList(); } /// <inheritdoc cref="ICacheService" /> public bool DeleteFromCache(string key) { return _cache.Remove(key) != null; } /// <inheritdoc cref="ICacheService" /> public bool DeleteFromCacheByTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } var tagKeyForCache = GetKeyForTag(tag); if (_cache.Contains(tagKeyForCache)) { // Increasing tag's version means invalidation of var currentTagVersion = ((TagItem)_cache.Get(tagKeyForCache)).Version; var newTagVersion = currentTagVersion + 1; _cache.Set(tagKeyForCache, new TagItem { Version = newTagVersion }, ObjectCache.InfiniteAbsoluteExpiration); // Flush cached items associated with tag's change monitors. SignaledChangeMonitor.Signal(_cache.Name, tag); return true; } return false; } /// <inheritdoc cref="ICacheService" /> public bool DeleteFromCacheByTags(IList<string> tags) { if (tags == null) { throw new ArgumentNullException(nameof(tags)); } var anythingHasBeenDeletedFromCache = false; foreach (var tag in tags) { if (DeleteFromCacheByTag(tag)) { anythingHasBeenDeletedFromCache = true; } } return anythingHasBeenDeletedFromCache; } /// <inheritdoc cref="ICacheService" /> public void ClearCache() { // Flush all cached items. SignaledChangeMonitor.Signal(_cache.Name); } /// <inheritdoc cref="ICacheService" /> public long Trim(int percent = 1) { return _cache.Trim(percent); } /// <inheritdoc cref="ICacheService" /> public bool Exists(string key) { object cacheItem; return TryGetFromCache(key, out cacheItem) && _cache.Contains(key); } /// <inheritdoc cref="ICacheService" /> public bool ExistsByTag(string tag) { var cacheItems = GetCacheItemsByTags(tag == null ? new List<string>() : new List<string> { tag }); var cacheItemsList = cacheItems as IList<CacheItem> ?? cacheItems.ToList(); if (!cacheItemsList.Any()) { return false; } var exists = false; foreach (var cacheItem in cacheItemsList) { // If any item in cache was invalidated by some tag then it will be actually removed from cache. if (Exists(cacheItem.Key)) { exists = true; } } return exists; } } }
32.214286
124
0.54235
[ "MIT" ]
Flexberry/NewPlatform.Flexberry.Caching
NewPlatform.Flexberry.Caching/MemoryCacheService/MemoryCacheService.Common.cs
4,512
C#
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Android.Support.Wearable.Views; using Android.Support.V4.App; using Android.Support.V4.View; using Java.Interop; using Android.Views.Animations; namespace SnakeWear { [Activity(Label = "Snake", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { private int speed = 1; private int highscore; TextView txtSpeed; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); ShowMainMenu(0); } public void ShowMainMenu(int score) { // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); var v = FindViewById<WatchViewStub>(Resource.Id.watch_view_stub); v.LayoutInflated += delegate { txtSpeed = FindViewById<TextView>(Resource.Id.level); UpdateHighscore(score); Button button = FindViewById<Button>(Resource.Id.btnPlay); ImageView decrease = FindViewById<ImageView>(Resource.Id.decrease); ImageView increase = FindViewById<ImageView>(Resource.Id.increase); decrease.Click += delegate { if (speed > 1) speed--; UpdateSpeed(); }; increase.Click += delegate { if (speed < 50) speed++; UpdateSpeed(); }; button.Click += delegate { Android.Graphics.Point size = new Android.Graphics.Point(); WindowManager.DefaultDisplay.GetRealSize(size); var game = new Game(this, size.X, size.Y, speed, highscore); SetContentView(game); Toast.MakeText(this, "Hold for 2 seconds to go back", ToastLength.Long).Show(); }; }; } private void UpdateSpeed() { txtSpeed.Text = $"{speed}"; } private void UpdateHighscore(int score) { var prefs = GetPreferences(FileCreationMode.Private); TextView txtHighscore = FindViewById<TextView>(Resource.Id.highscore); highscore = Math.Max(prefs.GetInt("highscore", 0), score); txtHighscore.Text = $"Highscore: {highscore}"; var edit = prefs.Edit(); edit.PutInt("highscore", highscore); edit.Commit(); } } }
31.95
99
0.57903
[ "Apache-2.0" ]
pontusstjerna/SnakeWear
SnakeWear/MainActivity.cs
2,558
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 chime-2018-05-01.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.Chime.Model { /// <summary> /// This is the response object from the TagMeeting operation. /// </summary> public partial class TagMeetingResponse : AmazonWebServiceResponse { } }
29.184211
103
0.730388
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/TagMeetingResponse.cs
1,109
C#
#if UNITY_EDITOR using UnityEngine; namespace Myy { public partial class SetupWindow { public class MyyLogger { public static void Log(string message) { Debug.Log(message); } public static void Log(object o) { Debug.Log(o); } public static void Log(string format, params object[] o) { Debug.LogFormat(format, o); } public static void LogError(string message) { Debug.LogError(message); } public static void LogError(string message, params object[] o) { Debug.LogErrorFormat(message, o); } } } } #endif
21.157895
74
0.468905
[ "MIT" ]
vr-voyage/vrchat-worldlock-autosetup
MyyLogger.cs
806
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; namespace DataLogicLayer { public class LoggerContextFactory { public LoggerContext Create(DbContextFactoryOptions options) { var optionsBuilder = new DbContextOptionsBuilder<LoggerContext>(); optionsBuilder.UseSqlServer("Server=localhost;Database=logs;Trusted_Connection=True;MultipleActiveResultSets=true"); return new LoggerContext(optionsBuilder.Options); } public LoggerContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<LoggerContext>(); optionsBuilder.UseSqlServer("Server=localhost;Database=logs;Trusted_Connection=True;MultipleActiveResultSets=true"); return new LoggerContext(optionsBuilder.Options); } } }
32.758621
128
0.728421
[ "MIT" ]
Krakaz/GymWebApi
DataLogicLayer/LoggerContextFactory.cs
952
C#
namespace PlexRequests.DataAccess.Enums { public enum AgentTypes { TheMovieDb = 1, TheTvDb, Imdb } }
13.8
40
0.565217
[ "MIT" ]
Jbond312/PlexRequestsApi
src/PlexRequests.DataAccess/Enums/AgentTypes.cs
140
C#
#region Copyright // //======================================================================================= // // Microsoft Azure Customer Advisory Team // // // // This sample is supplemental to the technical guidance published on the community // // blog at http://blogs.msdn.com/b/paolos/. // // // // Author: Paolo Salvatori // //======================================================================================= // // Copyright © 2016 Microsoft Corporation. All rights reserved. // // // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER // // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF // // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. YOU BEAR THE RISK OF USING IT. // //======================================================================================= #endregion namespace Microsoft.AzureCat.Samples.ObserverPattern.Interfaces { #region Using Directives using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AzureCat.Samples.ObserverPattern.Entities; #endregion public interface IClientObserverActor : IEntityIdActor { /// <summary> /// Registers an observer actor. /// This method is called by a client component. /// </summary> /// <param name="topic">The topic.</param> /// <param name="filterExpressions">Specifies filter expressions.</param> /// <param name="entityId">The entity id of the observable.</param> /// <returns>The asynchronous result of the operation.</returns> Task RegisterObserverActorAsync(string topic, IEnumerable<string> filterExpressions, EntityId entityId); /// <summary> /// Unregisters an observer actor. /// This method is called by a client component. /// </summary> /// <param name="topic">The topic.</param> /// <param name="entityId">The entity id of the observable.</param> /// <returns>The asynchronous result of the operation.</returns> Task UnregisterObserverActorAsync(string topic, EntityId entityId); /// <summary> /// Unregisters an observer actor from all observables on all topics. /// </summary> /// <returns>The asynchronous result of the operation.</returns> Task ClearSubscriptionsAsync(); /// <summary> /// Reads the messages for the observer actor from its messagebox. /// </summary> /// <returns>The messages for the current observer actor.</returns> Task<IEnumerable<Message>> ReadMessagesFromMessageBoxAsync(); } }
42.603175
112
0.591654
[ "MIT" ]
paolosalvatori/servicefabricobserver
Interfaces/IClientObserverActor.cs
2,687
C#
using Microsoft.VisualStudio.Setup.Configuration; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Vim.EditorHost { /// <summary> /// Utility for locating instances of Visual Studio on the machine. /// </summary> internal static class EditorLocatorUtil { /// <summary> /// A list of key names for versions of Visual Studio which have the editor components /// necessary to create an EditorHost instance. Listed in preference order /// </summary> internal static readonly string[] VisualStudioSkuKeyNames = new[] { "VisualStudio", "WDExpress", "VCSExpress", "VCExpress", "VBExpress", }; internal static bool TryGetEditorInfo(out EditorVersion editorVersion, out Version vsVersion, out string vsvsInstallDirectory) { foreach (var e in EditorVersionUtil.All) { if (TryGetEditorInfo(e, out vsVersion, out vsvsInstallDirectory)) { editorVersion = e; return true; } } vsVersion = default(Version); vsvsInstallDirectory = null; editorVersion = default(EditorVersion); return false; } internal static bool TryGetEditorInfo(EditorVersion editorVersion, out Version vsVersion, out string vsInstallDirectory) { var majorVersion = EditorVersionUtil.GetMajorVersionNumber(editorVersion); return majorVersion < 15 ? TryGetEditorInfoLegacy(majorVersion, out vsVersion, out vsInstallDirectory) : TryGetEditorInfoWillow(majorVersion, out vsVersion, out vsInstallDirectory); } private static bool TryGetEditorInfoLegacy(int majorVersion, out Version vsVersion, out string vsInstallDirectory) { if (TryGetVsInstallDirectoryLegacy(majorVersion, out vsInstallDirectory)) { vsVersion = new Version(majorVersion, 0); return true; } vsVersion = default(Version); vsInstallDirectory = null; return false; } /// <summary> /// Try and get the installation directory for the specified SKU of Visual Studio. This /// will fail if the specified vsVersion of Visual Studio isn't installed. Only works on /// pre-willow VS installations (< 15.0). /// </summary> private static bool TryGetVsInstallDirectoryLegacy(int majorVersion, out string vsInstallDirectory) { foreach (var skuKeyName in VisualStudioSkuKeyNames) { if (TryGetvsInstallDirectoryLegacy(majorVersion, skuKeyName, out vsInstallDirectory)) { return true; } } vsInstallDirectory = null; return false; } private static bool TryGetvsInstallDirectoryLegacy(int majorVersion, string skuKeyName,out string vsInstallDirectory) { try { var subKeyPath = String.Format(@"Software\Microsoft\{0}\{1}.0", skuKeyName, majorVersion); using (var key = Registry.LocalMachine.OpenSubKey(subKeyPath, writable: false)) { if (key != null) { vsInstallDirectory = key.GetValue("InstallDir", null) as string; if (!String.IsNullOrEmpty(vsInstallDirectory)) { return true; } } } } catch (Exception) { // Ignore and try the next vsVersion } vsInstallDirectory = null; return false; } /// <summary> /// Get the first Willow VS installation with the specified major vsVersion. /// </summary> private static bool TryGetEditorInfoWillow(int majorVersion, out Version vsVersion, out string directory) { Debug.Assert(majorVersion >= 15); var setup = new SetupConfiguration(); var e = setup.EnumAllInstances(); var array = new ISetupInstance[] { null }; do { var found = 0; e.Next(array.Length, array, out found); if (found == 0) { break; } var instance = array[0]; if (Version.TryParse(instance.GetInstallationVersion(), out vsVersion) && vsVersion.Major == majorVersion) { directory = Path.Combine(instance.GetInstallationPath(), @"Common7\IDE"); return true; } } while (true); directory = null; vsVersion = default(Version); return false; } } }
36.192053
135
0.531382
[ "Apache-2.0" ]
agocke/VsVim
Src/VimEditorHost/EditorLocatorUtil.cs
5,467
C#
using DinkToPdf.Contracts; namespace DinkToPdf { public class FooterSettings : ISettings { /// <summary> /// The font size to use for the footer. Default = 12 /// </summary> [WkHtml("footer.fontSize")] public int? FontSize { get; set; } /// <summary> /// The name of the font to use for the footer. Default = "Ariel" /// </summary> [WkHtml("footer.fontName")] public string FontName { get; set; } /// <summary> /// The string to print in the left part of the footer, note that some sequences are replaced in this string, see the /// wkhtmltopdf manual. Default = "" /// </summary> [WkHtml("footer.left")] public string Left { get; set; } /// <summary> /// The text to print in the right part of the footer, note that some sequences are replaced in this string, see the /// wkhtmltopdf manual. Default = "" /// </summary> [WkHtml("footer.center")] public string Center { get; set; } /// <summary> /// The text to print in the right part of the footer, note that some sequences are replaced in this string, see the /// wkhtmltopdf manual. Default = "" /// </summary> [WkHtml("footer.right")] public string Right { get; set; } /// <summary> /// Whether a line should be printed above the footer. Default = false /// </summary> [WkHtml("footer.line")] public bool? Line { get; set; } /// <summary> /// The amount of space to put between the footer and the content, e.g. "1.8". Be aware that if this is too large the /// footer will be printed outside the pdf document. This can be corrected with the margin.bottom setting. Default = /// 0.00 /// </summary> [WkHtml("footer.spacing")] public double? Spacing { get; set; } /// <summary> /// Url for a HTML document to use for the footer. Default = "" /// </summary> [WkHtml("footer.htmlUrl")] public string HtmUrl { get; set; } } }
36.8
129
0.550272
[ "MIT" ]
nathan-c/DinkToPdf
src/DinkToPdf/Settings/FooterSettings.cs
2,210
C#
using MvvmCross.Platforms.Android.Presenters; namespace XamarinNativeExamples.Droid { public class CustomPresenter : MvxAndroidViewPresenter { public CustomPresenter() : base(null) { } } }
20.545455
58
0.676991
[ "MIT" ]
jeromemanzano/XamarinNativeExamples
XamarinNativeExamples.Droid/CustomPresenter.cs
228
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; #nullable enable // ReSharper disable ArgumentsStyleOther // ReSharper disable ArgumentsStyleNamedExpression namespace Microsoft.EntityFrameworkCore.Metadata.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static class EntityTypeExtensions { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static MemberInfo GetNavigationMemberInfo( [NotNull] this IEntityType entityType, [NotNull] string navigationName) { var memberInfo = entityType.ClrType.GetMembersInHierarchy(navigationName).FirstOrDefault(); if (memberInfo == null) { throw new InvalidOperationException( CoreStrings.NoClrNavigation(navigationName, entityType.DisplayName())); } return memberInfo; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IForeignKey? FindDeclaredOwnership([NotNull] this IEntityType entityType) => ((EntityType)entityType).FindDeclaredOwnership(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IEntityType? FindInOwnershipPath([NotNull] this IEntityType entityType, [NotNull] Type targetType) { if (entityType.ClrType == targetType) { return entityType; } var owner = entityType; while (true) { var ownership = owner.FindOwnership(); if (ownership == null) { return null; } owner = ownership.PrincipalEntityType; if (owner.ClrType.IsAssignableFrom(targetType)) { return owner; } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static bool IsInOwnershipPath([NotNull] this IEntityType entityType, [NotNull] Type targetType) => entityType.FindInOwnershipPath(targetType) != null; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] public static string GetOwnedName([NotNull] this ITypeBase type, [NotNull] string simpleName, [NotNull] string ownershipNavigation) => type.Name + "." + ownershipNavigation + "#" + simpleName; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static bool UseEagerSnapshots([NotNull] this IEntityType entityType) { var changeTrackingStrategy = entityType.GetChangeTrackingStrategy(); return changeTrackingStrategy == ChangeTrackingStrategy.Snapshot || changeTrackingStrategy == ChangeTrackingStrategy.ChangedNotifications; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static int StoreGeneratedCount([NotNull] this IEntityType entityType) => GetCounts(entityType).StoreGeneratedCount; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static int RelationshipPropertyCount([NotNull] this IEntityType entityType) => GetCounts(entityType).RelationshipCount; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static int OriginalValueCount([NotNull] this IEntityType entityType) => GetCounts(entityType).OriginalValueCount; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static int ShadowPropertyCount([NotNull] this IEntityType entityType) => GetCounts(entityType).ShadowCount; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static int NavigationCount([NotNull] this IEntityType entityType) => GetCounts(entityType).NavigationCount; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static int PropertyCount([NotNull] this IEntityType entityType) => GetCounts(entityType).PropertyCount; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static PropertyCounts GetCounts([NotNull] this IEntityType entityType) => ((EntityType)entityType).Counts; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static PropertyCounts CalculateCounts([NotNull] this EntityType entityType) { var index = 0; var navigationIndex = 0; var originalValueIndex = 0; var shadowIndex = 0; var relationshipIndex = 0; var storeGenerationIndex = 0; var baseCounts = entityType.BaseType?.GetCounts(); if (baseCounts != null) { index = baseCounts.PropertyCount; navigationIndex = baseCounts.NavigationCount; originalValueIndex = baseCounts.OriginalValueCount; shadowIndex = baseCounts.ShadowCount; relationshipIndex = baseCounts.RelationshipCount; storeGenerationIndex = baseCounts.StoreGeneratedCount; } foreach (var property in entityType.GetDeclaredProperties()) { var indexes = new PropertyIndexes( index: index++, originalValueIndex: property.RequiresOriginalValue() ? originalValueIndex++ : -1, shadowIndex: property.IsShadowProperty() ? shadowIndex++ : -1, relationshipIndex: property.IsKey() || property.IsForeignKey() ? relationshipIndex++ : -1, storeGenerationIndex: property.MayBeStoreGenerated() ? storeGenerationIndex++ : -1); property.PropertyIndexes = indexes; } var isNotifying = entityType.GetChangeTrackingStrategy() != ChangeTrackingStrategy.Snapshot; foreach (var navigation in entityType.GetDeclaredNavigations() .Union<PropertyBase>(entityType.GetDeclaredSkipNavigations())) { var indexes = new PropertyIndexes( index: navigationIndex++, originalValueIndex: -1, shadowIndex: navigation.IsShadowProperty() ? shadowIndex++ : -1, relationshipIndex: ((INavigationBase)navigation).IsCollection && isNotifying ? -1 : relationshipIndex++, storeGenerationIndex: -1); navigation.PropertyIndexes = indexes; } foreach (var serviceProperty in entityType.GetDeclaredServiceProperties()) { var indexes = new PropertyIndexes( index: -1, originalValueIndex: -1, shadowIndex: -1, relationshipIndex: -1, storeGenerationIndex: -1); serviceProperty.PropertyIndexes = indexes; } return new PropertyCounts( index, navigationIndex, originalValueIndex, shadowIndex, relationshipIndex, storeGenerationIndex); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static Func<MaterializationContext, object> GetInstanceFactory([NotNull] this IEntityType entityType) => entityType.AsEntityType().InstanceFactory; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static Func<ISnapshot> GetEmptyShadowValuesFactory([NotNull] this IEntityType entityType) => entityType.AsEntityType().EmptyShadowValuesFactory; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IReadOnlyList<IProperty> GetPropagatingProperties([NotNull] this IEntityType entityType) => entityType.AsEntityType().PropagatingProperties; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IReadOnlyList<IProperty> GetGeneratingProperties([NotNull] this IEntityType entityType) => entityType.AsEntityType().GeneratingProperties; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static EntityType? LeastDerivedType([NotNull] this EntityType entityType, [NotNull] EntityType otherEntityType) => (EntityType?)((IEntityType)entityType).LeastDerivedType(otherEntityType); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IKey? FindDeclaredPrimaryKey([NotNull] this IEntityType entityType) => entityType.BaseType == null ? entityType.FindPrimaryKey() : null; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IEnumerable<INavigation> FindDerivedNavigations( [NotNull] this IEntityType entityType, [NotNull] string navigationName) => entityType.GetDerivedTypes().SelectMany( et => et.GetDeclaredNavigations().Where(navigation => navigationName == navigation.Name)); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IEnumerable<Navigation> GetDerivedNavigations([NotNull] this IEntityType entityType) => entityType.AsEntityType().GetDerivedNavigations(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IEnumerable<SkipNavigation> GetDerivedSkipNavigations([NotNull] this IEntityType entityType) => entityType.AsEntityType().GetDerivedSkipNavigations(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IEnumerable<IPropertyBase> GetPropertiesAndNavigations( [NotNull] this IEntityType entityType) => entityType.GetProperties().Concat<IPropertyBase>(entityType.GetNavigations()); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IEnumerable<IPropertyBase> GetNotificationProperties( [NotNull] this IEntityType entityType, [CanBeNull] string? propertyName) { if (string.IsNullOrEmpty(propertyName)) { foreach (var property in entityType.GetProperties() .Where(p => p.GetAfterSaveBehavior() == PropertySaveBehavior.Save)) { yield return property; } foreach (var navigation in entityType.GetNavigations()) { yield return navigation; } foreach (var navigation in entityType.GetSkipNavigations()) { yield return navigation; } } else { // ReSharper disable once AssignNullToNotNullAttribute var property = entityType.FindProperty(propertyName) ?? entityType.FindNavigation(propertyName) ?? (IPropertyBase?)entityType.FindSkipNavigation(propertyName); if (property != null) { yield return property; } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static IProperty CheckPropertyBelongsToType([NotNull] this IEntityType entityType, [NotNull] IProperty property) { Check.NotNull(property, nameof(property)); if (!property.DeclaringEntityType.IsAssignableFrom(entityType)) { throw new InvalidOperationException( CoreStrings.PropertyDoesNotBelong(property.Name, property.DeclaringEntityType.DisplayName(), entityType.DisplayName())); } return property; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static EntityType AsEntityType([NotNull] this IEntityType entityType, [NotNull] [CallerMemberName] string methodName = "") => MetadataExtensions.AsConcreteMetadataType<IEntityType, EntityType>(entityType, methodName); } }
58.209412
140
0.653745
[ "Apache-2.0" ]
eiriktsarpalis/efcore
src/EFCore/Metadata/Internal/EntityTypeExtensions.cs
24,739
C#
namespace MusicHub.DataProcessor { using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using Data; using MusicHub.DataProcessor.ExportDtos; using Newtonsoft.Json; public class Serializer { public static string ExportAlbumsInfo(MusicHubDbContext context, int producerId) { var albums = context .Albums .Where(a => a.ProducerId == producerId) .OrderByDescending(a => a.Songs.Sum(s => s.Price)) .Select(a => new { AlbumName = a.Name, ReleaseDate = a.ReleaseDate.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), ProducerName = a.Producer.Name, Songs = a.Songs.Select(s => new { SongName = s.Name, Price = s.Price.ToString("F2"), Writer = s.Writer.Name }) .OrderByDescending(s => s.SongName) .ThenBy(s => s.Writer) .ToArray(), AlbumPrice = a.Songs.Sum(s => s.Price).ToString("F2") }) .ToArray(); string json = JsonConvert.SerializeObject(albums, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Newtonsoft.Json.Formatting.Indented }); return json; } public static string ExportSongsAboveDuration(MusicHubDbContext context, int duration) { var songs = context .Songs .Where(s => s.Duration.TotalSeconds > duration) .Select(s => new ExportSongDto { SongName = s.Name, Writer = s.Writer.Name, Performer = s.SongPerformers.Select(sp => $"{sp.Performer.FirstName} {sp.Performer.LastName}").FirstOrDefault(), AlbumProducer = s.Album.Producer.Name, Duration = s.Duration.ToString("c", CultureInfo.InvariantCulture) }) .OrderBy(s => s.SongName) .ThenBy(s => s.Writer) .ThenBy(s => s.Performer) .ToArray(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(ExportSongDto[]), new XmlRootAttribute("Songs")); var sb = new StringBuilder(); var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); xmlSerializer.Serialize(new StringWriter(sb), songs, namespaces); var result = sb.ToString().TrimEnd(); return result; } } }
36.202381
140
0.491615
[ "MIT" ]
PhilShishov/Software-University
Databases Advanced - Entity Framework/Exams/DB-Adv-Exam_18Apr2019/MusicHub/DataProcessor/Serializer.cs
3,043
C#
using System; using System.Collections.Generic; namespace RestEaseClientGeneratorConsoleApp.Examples.FormRecognizer.V2.Models { public class DataTable { public int Rows { get; set; } public int Columns { get; set; } public DataTableCell[] Cells { get; set; } } }
21.066667
78
0.642405
[ "MIT" ]
StefH/RestEase-Client-Generator
examples/RestEaseClientGeneratorConsoleApp/Examples/FormRecognizerV2/Models/DataTable.cs
316
C#
using System; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace opendata_nhi.Controllers { public class MyServiceURL { public readonly string GET_DATASET_DOWNLOAD = "/Datasets/Download.ashx"; public readonly string GET_LATLNG = "/maps/api/geocode/json"; } }
25.4
116
0.698163
[ "MIT" ]
abowwang/opendata_nhi
Controllers/MyServiceURL.cs
381
C#
using System; using Ayehu.Sdk.ActivityCreation.Interfaces; using Ayehu.Sdk.ActivityCreation.Extension; using Ayehu.Sdk.ActivityCreation.Helpers; using System.Net; using System.Net.Http; using System.Text; using System.Collections.Generic; namespace Ayehu.Github { public class GH_Delete_a_discussion_comment : IActivityAsync { public string Jsonkeypath = ""; public string Accept = ""; public string password1 = ""; public string Username = ""; public string org = ""; public string team_slug = ""; public string discussion_number = ""; public string comment_number = ""; private bool omitJsonEmptyorNull = true; private string contentType = "application/json"; private string endPoint = "https://api.github.com"; private string httpMethod = "DELETE"; private string _uriBuilderPath; private string _postData; private System.Collections.Generic.Dictionary<string, string> _headers; private System.Collections.Generic.Dictionary<string, string> _queryStringArray; private string uriBuilderPath { get { if (string.IsNullOrEmpty(_uriBuilderPath)) { _uriBuilderPath = string.Format("/orgs/{0}/teams/{1}/discussions/{2}/comments/{3}",org,team_slug,discussion_number,comment_number); } return _uriBuilderPath; } set { this._uriBuilderPath = value; } } private string postData { get { if (string.IsNullOrEmpty(_postData)) { _postData = ""; } return _postData; } set { this._postData = value; } } private System.Collections.Generic.Dictionary<string, string> headers { get { if (_headers == null) { _headers = new Dictionary<string, string>() { {"User-Agent","" + Username},{"Accept",Accept},{"authorization","token " + password1} }; } return _headers; } set { this._headers = value; } } private System.Collections.Generic.Dictionary<string, string> queryStringArray { get { if (_queryStringArray == null) { _queryStringArray = new Dictionary<string, string>() { }; } return _queryStringArray; } set { this._queryStringArray = value; } } public GH_Delete_a_discussion_comment() { } public GH_Delete_a_discussion_comment(string Jsonkeypath, string Accept, string password1, string Username, string org, string team_slug, string discussion_number, string comment_number) { this.Jsonkeypath = Jsonkeypath; this.Accept = Accept; this.password1 = password1; this.Username = Username; this.org = org; this.team_slug = team_slug; this.discussion_number = discussion_number; this.comment_number = comment_number; } public async System.Threading.Tasks.Task<ICustomActivityResult> Execute() { HttpClient client = new HttpClient(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); UriBuilder UriBuilder = new UriBuilder(endPoint); UriBuilder.Path = uriBuilderPath; UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray); HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString()); if (contentType == "application/x-www-form-urlencoded") myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData); else if (string.IsNullOrEmpty(postData) == false) if (omitJsonEmptyorNull) myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json"); else myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType); foreach (KeyValuePair<string, string> headeritem in headers) client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value); HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result; switch (response.StatusCode) { case HttpStatusCode.NoContent: case HttpStatusCode.Created: case HttpStatusCode.Accepted: case HttpStatusCode.OK: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) return this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath); else return this.GenerateActivityResult("Success"); } default: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) throw new Exception(response.Content.ReadAsStringAsync().Result); else if (string.IsNullOrEmpty(response.ReasonPhrase) == false) throw new Exception(response.ReasonPhrase); else throw new Exception(response.StatusCode.ToString()); } } } public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } } }
35.803571
251
0.62128
[ "MIT" ]
Ayehu/custom-activities
Github/teams/GH Delete a discussion comment/GH Delete a discussion comment.cs
6,015
C#
using Buildalyzer; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Logging; using Stryker.Core.Exceptions; using Stryker.Core.Logging; using Stryker.Core.Testing; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Stryker.Core.Initialisation { public interface IAssemblyReferenceResolver { IEnumerable<PortableExecutableReference> LoadProjectReferences(string[] projectReferencePaths); } /// <summary> /// Resolving the MetadataReferences for compiling later /// This has to be done using msbuild because currently msbuild is the only reliable way of resolving all referenced assembly locations /// </summary> public class AssemblyReferenceResolver : IAssemblyReferenceResolver { private ILogger _logger { get; set; } public AssemblyReferenceResolver() { _logger = ApplicationLogging.LoggerFactory.CreateLogger<AssemblyReferenceResolver>(); } /// <summary> /// Uses Buildalyzer to resolve all references for the given test project /// </summary> /// <param name="projectFile">The test project file location</param> /// <returns>References</returns> public IEnumerable<PortableExecutableReference> LoadProjectReferences(string[] projectReferencePaths) { foreach (var path in projectReferencePaths) { _logger.LogTrace("Resolved depedency {0}", path); yield return MetadataReference.CreateFromFile(path); } } } }
33.851064
139
0.692018
[ "Apache-2.0" ]
MadsPB/stryker-net
src/Stryker.Core/Stryker.Core/Initialisation/AssemblyReferenceResolver.cs
1,593
C#
using Orchard.ContentManagement.Records; namespace Orchard.Users.Models { public class UserSecurityConfigurationPartRecord : ContentPartRecord { // We are creating a record for this rather than making do with the infoset // because this will allow us to explicitly query for those users that must // (or not) be saved from suspension. public virtual bool SaveFromSuspension { get; set; } public virtual bool PreventPasswordExpiration { get; set; } } }
45.545455
83
0.718563
[ "BSD-3-Clause" ]
OrchardCMS/orchard
src/Orchard.Web/Modules/Orchard.Users/Models/UserSecurityConfigurationPartRecord.cs
503
C#
using System; using QueueWithStacks.Classes; namespace QueueWithStacks { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); PseudoQueue testQueue = new PseudoQueue(); testQueue.Enqueue(10); testQueue.Enqueue(15); testQueue.Enqueue(20); Console.WriteLine(testQueue.Dequeue()); Console.WriteLine(testQueue.Dequeue()); Console.WriteLine(testQueue.Dequeue()); } } }
23.73913
54
0.586081
[ "MIT" ]
jeremymaya/data-structures-and-algorithms
challenges/QueueWithStacks/QueueWithStacks/Program.cs
548
C#
//----------------------------------------------------------------------- // <copyright file="MainPage.xaml.cs" company="Microsoft Corporation"> // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace BountyTestApp { using System; using System.Linq; using System.Threading.Tasks; using Windows.Data.Json; using Windows.Services.Store; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; /// <summary> /// Show the bounty indicator based on the capaign ID used in this conversion. /// </summary> public sealed partial class MainPage : Page { public enum AttestationState { Eligible, NonEligible, Unknown }; /// <summary> /// Main page constructor /// </summary> public MainPage() { this.InitializeComponent(); } /// <summary> /// Retrieve the campaign ID for the /// </summary> /// <returns>The campaign ID associated with this acquisition</returns> private async Task<string> GetCampaignId() { string campaignID = string.Empty; // Use APIs in the Windows.Services.Store namespace if they are available // (the app is running on a device with Windows 10, version 1607, or later). if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent( "Windows.Services.Store.StoreContext")) { StoreContext context = StoreContext.GetDefault(); // Try to get the campaign ID for users with a recognized Microsoft account. StoreProductResult result = await context.GetStoreProductForCurrentAppAsync(); if (result.Product != null) { StoreSku sku = result.Product.Skus.FirstOrDefault(s => s.IsInUserCollection); if (sku != null) { campaignID = sku.CollectionData.CampaignId; } } if (string.IsNullOrEmpty(campaignID)) { // Try to get the campaign ID from the license data for users without a // recognized Microsoft account. StoreAppLicense license = await context.GetAppLicenseAsync(); JsonObject json = JsonObject.Parse(license.ExtendedJsonData); if (json.ContainsKey("customPolicyField1")) { campaignID = json["customPolicyField1"].GetString(); } } } // Fall back to using APIs in the Windows.ApplicationModel.Store namespace instead // (the app is running on a device with Windows 10, version 1577, or earlier). else { #if DEBUG campaignID = await Windows.ApplicationModel.Store.CurrentAppSimulator.GetAppPurchaseCampaignIdAsync(); #else campaignID = await Windows.ApplicationModel.Store.CurrentApp.GetAppPurchaseCampaignIdAsync() ; #endif } return campaignID; } /// <summary> /// Get the bounty eligability for this acquisition and return a string either Yes or No /// </summary> /// <returns>a string of either yes or no</returns> private async Task<string> GetBountyEligible() { string bountyEligible = string.Empty; try { if (await IsMicrosoftBounty()) { bountyEligible = "Yes"; } else { bountyEligible = "No"; } } catch (Exception ex) { bountyEligible = string.Format("No - Error requesting: {0}", ex.Message); } return bountyEligible; } /// <summary> /// Check and return if this acquisition is bounty Eligible /// </summary> /// <returns>true if the event is bounty Eligible, false otherwise</returns> private async Task<bool> IsMicrosoftBounty() { uint userContext = 27; uint deviceContext = 28; // First check if the user (MSA) has acquired the app through a bounty Eligible source // If the call for the user returns ERROR_NO_SUCH_USER then the machine can be checked var isUserContextAccrued = await IsMicrosoftAccrued(userContext); bool isDeviceContextAccrued = false; if (isUserContextAccrued == AttestationState.Unknown) { isDeviceContextAccrued = (await IsMicrosoftAccrued(deviceContext)) == AttestationState.Eligible; } return isDeviceContextAccrued || isUserContextAccrued == AttestationState.Eligible; } /// <summary> /// Check and return if this acquisition is related to a Microsoft sponsired source /// </summary> /// <param name="requestId">the request ID. This is usually either the user or machine ID</param> /// <returns>true if the acquisition is Microsoft sponsored, false otherwise</returns> private async Task<AttestationState> IsMicrosoftAccrued(uint requestId) { AttestationState isAccrued = AttestationState.Unknown; try { StoreContext ctx = StoreContext.GetDefault(); var result = await StoreRequestHelper.SendRequestAsync(ctx, requestId, "{}"); if (result.HttpStatusCode == Windows.Web.Http.HttpStatusCode.None && string.IsNullOrEmpty(result.Response) && result.ExtendedError.HResult == unchecked((int)0x80070525)) { // the user doesnt exist isAccrued = AttestationState.Unknown; } else { JsonObject jsonObject = JsonObject.Parse(result.Response); isAccrued = jsonObject.GetNamedBoolean("IsMicrosoftAccrued") ? AttestationState.Eligible : AttestationState.NonEligible; } } catch (System.Exception ex) { // TODO: log the exception and possibly handle here. // For this example the exception text will be used to show on the app screen, // so rethrow the exception so its exposed in the caller throw ex; } return isAccrued; } /// <summary> /// Handle the page loaded event /// </summary> /// <param name="sender">sender object</param> /// <param name="e">event parameters</param> private async void Page_Loaded(object sender, RoutedEventArgs e) { var id = await GetCampaignId(); if (string.IsNullOrEmpty(id)) { CampaignID.Text = "No Campaign ID Found"; } else { CampaignID.Text = id; } var message = await GetBountyEligible(); BountyEligible.Text = message; } } }
38.341709
141
0.526868
[ "MIT" ]
marcpems/StoreBountyDemo
BountyTestApp/MainPage.xaml.cs
7,632
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Management.ServiceBus.Models; using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.Azure.Commands.ServiceBus.Models { public class ListKeysAttributes { public const string DefaultClaimType = "SharedAccessKey"; public const string DefaultClaimValue = "None"; internal const string DefaultNamespaceAuthorizationRule = "RootManageSharedAccessKey"; public ListKeysAttributes(AccessKeys listKeysResource) { if (listKeysResource != null) { PrimaryConnectionString = listKeysResource.PrimaryConnectionString; SecondaryConnectionString = listKeysResource.SecondaryConnectionString; PrimaryKey = listKeysResource.PrimaryKey; SecondaryKey = listKeysResource.SecondaryKey; KeyName = listKeysResource.KeyName; }; } /// <summary> /// PrimaryConnectionString of the created Namespace AuthorizationRule. /// </summary> public string PrimaryConnectionString { get; set; } /// <summary> /// SecondaryConnectionString of the created Namespace /// AuthorizationRule /// </summary> public string SecondaryConnectionString { get; set; } /// <summary> /// A base64-encoded 256-bit primary key for signing and validating /// the SAS token /// </summary> public string PrimaryKey { get; set; } /// <summary> /// A base64-encoded 256-bit primary key for signing and validating /// the SAS token /// </summary> public string SecondaryKey { get; set; } /// <summary> /// A string that describes the authorization rule /// </summary> public string KeyName { get; set; } } }
38
95
0.600074
[ "MIT" ]
SpillChek2/azure-powershell
src/ResourceManager/ServiceBus/Commands.ServiceBus/Models/ListKeysAttributes.cs
2,630
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.3053 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace umbraco.presentation.translation { public partial class _default { /// <summary> /// Panel2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.UmbracoPanel Panel2; /// <summary> /// feedback control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Feedback feedback; /// <summary> /// pane_uploadFile control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane pane_uploadFile; /// <summary> /// translationFile control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlInputFile translationFile; /// <summary> /// uploadFile 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.Button uploadFile; /// <summary> /// pane_tasks control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane pane_tasks; /// <summary> /// lt_tasksHelp 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.Literal lt_tasksHelp; /// <summary> /// taskList 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.GridView taskList; } }
35.348315
85
0.518436
[ "MIT" ]
Abhith/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/translation/default.aspx.designer.cs
3,146
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Web.Outputs { /// <summary> /// Azure API management (APIM) configuration linked to the app. /// </summary> [OutputType] public sealed class ApiManagementConfigResponse { /// <summary> /// APIM-Api Identifier. /// </summary> public readonly string? Id; [OutputConstructor] private ApiManagementConfigResponse(string? id) { Id = id; } } }
24.903226
81
0.639896
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/Outputs/ApiManagementConfigResponse.cs
772
C#
using System.Diagnostics.Contracts; using CssUI.CSS.BoxTree; namespace CssUI.CSS.Formatting { public class BlockFormattingContext : IFormattingContext { public void Flow(CssBoxTreeNode Node) { if (Node is null) { throw new System.ArgumentNullException(nameof(Node)); } Contract.EndContractBlock(); CssBoxTreeNode Current = Node.firstChild; while (Current is object) { if (Current.previousSibling is null) { Current.Position = Point2f.Zero; } else { var prev = Current.previousSibling; var prev_pos = prev.Position; var prev_size = prev.Size; Current.Position = new Point2f(prev_pos.X + prev_size.Width, prev_pos.Y + prev_size.Height); } Current = Current.nextSibling; } } } }
28.916667
112
0.505283
[ "MIT" ]
dsisco11/CssUI
CssUI/CSS/Formatting/BlockFormattingContext.cs
1,043
C#
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using DotSpatial.Data; namespace DotSpatial.Modeling.Forms { /// <summary> /// This class is used to enable linking of tools that work with File parameters. /// </summary> public class TextFile : DataSet { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TextFile"/> class. /// </summary> public TextFile() { } /// <summary> /// Initializes a new instance of the <see cref="TextFile"/> class. /// </summary> /// <param name="fileName">the associated file name</param> public TextFile(string fileName) { Filename = fileName; } #endregion #region Methods /// <summary> /// Returns the file name. /// </summary> /// <returns>The file name</returns> public override string ToString() { return Filename; } #endregion } }
26.217391
106
0.54063
[ "MIT" ]
AlexanderSemenyak/DotSpatial
Source/DotSpatial.Modeling.Forms/TextFile.cs
1,208
C#
using System; using System.Threading.Tasks; using MongoDB.Driver; using SCNDISC.Server.Domain.Aggregates.Parameters; using SCNDISC.Server.Domain.Commands.Parameters; using SCNDISC.Server.Infrastructure.Persistence.Providers; using SCNDISC.Server.Infrastructure.Persistence.Queries; namespace SCNDISC.Server.Infrastructure.Persistence.Commands.Parameters { public class DeleteParameterCommand: MongoCommandQueryBase<Parameter>, IDeleteParameterCommand { public DeleteParameterCommand(IMongoCollectionProvider provider) : base(provider) { } public async Task DeleteParameterAsync(string parameterKey) { await Collection.DeleteOneAsync(b => String.Compare(b.Key, parameterKey, StringComparison.CurrentCultureIgnoreCase) == 0); } } }
37.571429
134
0.78327
[ "MIT" ]
Dima2022/DiscountsApp
SCNDISC.Server/SCNDISC.Server.Infrastructure/Persistence/Commands/Parameters/DeleteParameterCommand.cs
791
C#
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DirkBremen : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Dirk"; public string LastName => "Bremen"; public string ShortBioOrTagLine => "Automation lover"; public string StateOrRegion => "Ireland"; public string EmailAddress => "rescueme@planetpowershell.com"; public string TwitterHandle => "powershellone"; public string GravatarHash => "fc95464388c9f41d7da43a6618fb04bd"; public string GitHubHandle => "dbremen"; public GeoPosition Position => new GeoPosition(53.338389, -6.258877); public Uri WebSite => new Uri("https://powershellone.wordpress.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://powershellone.wordpress.com/rss"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
41.566667
117
0.688853
[ "MIT" ]
ChrisLGardner/planetpowershell
src/Firehose.Web/Authors/DirkBremen.cs
1,247
C#
 namespace BigML { /// <summary> /// An anomaly detector is a predictive model that can help identify the /// instances within a dataset that do not conform to a regular pattern. /// It can be useful for tasks like data cleansing, identifying unusual /// instances, or, given a new data point, deciding whether a model is /// competent to make a prediction or not. /// The complete and updated reference with all available parameters is in /// our <a href="https://bigml.com/api/anomalies">documentation</a> /// website. /// </summary> public partial class Anomaly : Response { /// <summary> /// The name of the anomaly detection as your provided or based on the name /// of the dataset by default. /// </summary> public string Name { get { return Object.name; } } /// <summary> /// The dataset/id that was used to build the dataset. /// </summary> public string DataSet { get { return Object.dataset; } } /// <summary> /// Whether the dataset is still available or has been deleted. /// </summary> public bool DataSetStatus { get { return Object.dataset_status; } } /// <summary> /// A description of the status of the anomaly detector. /// It includes a code, a message, and some extra information. /// </summary> public Status StatusMessage { get { return new Status(Object.status); } } } }
28.767857
83
0.572936
[ "Apache-2.0" ]
bigmlcom/bigml-csharp
BigML/Anomaly/Anomaly.cs
1,613
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Gamma.Entities { using System; using System.Collections.Generic; public partial class ProductionTaskDowntimes { public System.Guid ProductionTaskDowntimeID { get; set; } public System.Guid ProductionTaskID { get; set; } public System.DateTime Date { get; set; } public int ShiftID { get; set; } public System.Guid C1CDowntimeTypeID { get; set; } public Nullable<System.Guid> C1CDowntimeTypeDetailID { get; set; } public System.DateTime DateBegin { get; set; } public System.DateTime DateEnd { get; set; } public int Duration { get; set; } public string Comment { get; set; } public Nullable<System.Guid> C1CEquipmentNodeID { get; set; } public Nullable<System.Guid> C1CEquipmentNodeDetailID { get; set; } public virtual C1CDowntimeTypeDetails C1CDowntimeTypeDetails { get; set; } public virtual C1CDowntimeTypes C1CDowntimeTypes { get; set; } public virtual ProductionTasks ProductionTasks { get; set; } public virtual C1CEquipmentNodeDetails C1CEquipmentNodeDetails { get; set; } public virtual C1CEquipmentNodes C1CEquipmentNodes { get; set; } } }
44.594595
85
0.616364
[ "Unlicense" ]
Polimat/Gamma
Entities/ProductionTaskDowntimes.cs
1,650
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 08.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete2__objs.NullableInt64.NullableDecimal{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Int64>; using T_DATA2 =System.Nullable<System.Decimal>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__02__VN public static class TestSet_504__param__02__VN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=null; var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2))); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__02__VN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete2__objs.NullableInt64.NullableDecimal
26.656934
149
0.533133
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Equal/Complete2__objs/NullableInt64/NullableDecimal/TestSet_504__param__02__VN.cs
3,654
C#
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information. namespace Aqua { using System.Collections.Generic; using System.Linq; using BindingFlags = System.Reflection.BindingFlags; using MethodInfo = System.Reflection.MethodInfo; internal static class MethodInfos { internal static class Enumerable { internal static readonly MethodInfo Cast = typeof(System.Linq.Enumerable) .GetMethod(nameof(System.Linq.Enumerable.Cast), BindingFlags.Public | BindingFlags.Static); internal static readonly MethodInfo OfType = typeof(System.Linq.Enumerable) .GetMethod(nameof(System.Linq.Enumerable.OfType), BindingFlags.Public | BindingFlags.Static); internal static readonly MethodInfo ToArray = typeof(System.Linq.Enumerable) .GetMethod(nameof(System.Linq.Enumerable.ToArray), BindingFlags.Public | BindingFlags.Static); internal static readonly MethodInfo ToList = typeof(System.Linq.Enumerable) .GetMethod(nameof(System.Linq.Enumerable.ToList), BindingFlags.Public | BindingFlags.Static); internal static readonly MethodInfo Contains = typeof(System.Linq.Enumerable) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == nameof(System.Linq.Enumerable.Contains) && m.GetParameters().Length == 2); internal static readonly MethodInfo Single = typeof(System.Linq.Enumerable) .GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(x => x.Name == nameof(System.Linq.Enumerable.Single)) .Where(x => { var parameters = x.GetParameters(); return parameters.Length == 1 && parameters[0].ParameterType.IsGenericType && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>); }) .Single(); internal static readonly MethodInfo SingleOrDefault = typeof(System.Linq.Enumerable) .GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(x => x.Name == nameof(System.Linq.Enumerable.SingleOrDefault)) .Where(x => { var parameters = x.GetParameters(); return parameters.Length == 1 && parameters[0].ParameterType.IsGenericType && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>); }) .Single(); } internal static class Expression { internal static readonly MethodInfo Lambda = typeof(System.Linq.Expressions.Expression) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == nameof(System.Linq.Expressions.Expression.Lambda) && m.IsGenericMethod && m.GetParameters().Length == 2 && m.GetParameters()[1].ParameterType == typeof(System.Linq.Expressions.ParameterExpression[])); } internal static class Queryable { internal static readonly MethodInfo AsQueryable = typeof(System.Linq.Queryable) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == nameof(System.Linq.Queryable.AsQueryable) && m.IsGenericMethod && m.GetParameters().Length == 1); internal static readonly MethodInfo OrderBy = typeof(System.Linq.Queryable) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == nameof(System.Linq.Queryable.OrderBy) && m.IsGenericMethod && m.GetParameters().Length == 2); internal static readonly MethodInfo OrderByDescending = typeof(System.Linq.Queryable) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == nameof(System.Linq.Queryable.OrderByDescending) && m.IsGenericMethod && m.GetParameters().Length == 2); internal static readonly MethodInfo ThenBy = typeof(System.Linq.Queryable) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == nameof(System.Linq.Queryable.ThenBy) && m.IsGenericMethod && m.GetParameters().Length == 2); internal static readonly MethodInfo ThenByDescending = typeof(System.Linq.Queryable) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == nameof(System.Linq.Queryable.ThenByDescending) && m.IsGenericMethod && m.GetParameters().Length == 2); internal static readonly MethodInfo Select = typeof(System.Linq.Queryable) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(i => i.Name == nameof(System.Linq.Queryable.Select)) .Where(i => i.IsGenericMethod) .Single(i => { var parameters = i.GetParameters(); if (parameters.Length != 2) { return false; } var expressionParamType = parameters[1].ParameterType; if (!expressionParamType.IsGenericType) { return false; } var genericArguments = expressionParamType.GetGenericArguments().ToArray(); if (genericArguments.Count() != 1) { return false; } if (!genericArguments.Single().IsGenericType) { return false; } if (genericArguments.Single().GetGenericArguments().Count() != 2) { return false; } return true; }); } internal static class String { internal static readonly MethodInfo StartsWith = typeof(string) .GetMethod(nameof(string.StartsWith), new[] { typeof(string) }); internal static readonly MethodInfo EndsWith = typeof(string) .GetMethod(nameof(string.EndsWith), new[] { typeof(string) }); internal static readonly MethodInfo Contains = typeof(string) .GetMethod(nameof(string.Contains), new[] { typeof(string) }); } } }
45.538961
114
0.554542
[ "MIT" ]
640774n6/aqua-core
src/Aqua/MethodInfos.cs
7,015
C#
 /*********************************************************************************************************** * Produced by App Advisory - http://app-advisory.com * * Facebook: https://facebook.com/appadvisory * * Contact us: https://appadvisory.zendesk.com/hc/en-us/requests/new * * App Advisory Unity Asset Store catalog: http://u3d.as/9cs * * Developed by Gilbert Anthony Barouch - https://www.linkedin.com/in/ganbarouch * ***********************************************************************************************************/ #pragma warning disable 0168 // variable declared but not used. #pragma warning disable 0219 // variable assigned but not used. #pragma warning disable 0414 // private field assigned but not used. #pragma warning disable 0618 // obslolete #pragma warning disable 0108 #pragma warning disable 0162 using UnityEngine; using System.Collections; namespace AppAdvisory.social { public class LEADERBOARDIDS : ScriptableObject { public bool FIRST_TIME = true; public bool ENABLE_IOS = false; public bool ENABLE_ANDROID = false; public string LEADERBOARDID_IOS = "fr.appadvisory.amazingbrick"; public string LEADERBOARDID_ANDROID = "fr.appadvisory.amazingbrick"; public string LEADERBOARDID { get { #if UNITY_IOS return LEADERBOARDID_IOS; #endif #if UNITY_ANDROID return LEADERBOARDID_ANDROID; #endif #if !UNITY_IOS && !UNITY_ANDROID return ""; #endif } } public void Init() {} } }
28.690909
109
0.587452
[ "MIT" ]
RavArty/RollocoBall
Assets/Very_Simple_Leaderboard/Scripts/LEADERBOARDIDS.cs
1,580
C#
// // AzureLogExporter // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the ""Software""), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace AzureLogExporter { public class TransmissionFaultMessage { public string id { get; set; } public string type { get; set; } } public class Utils { static string ExpectedRemoteCertThumbprint { get; set; } public Utils() { ExpectedRemoteCertThumbprint = Config.GetValue(ConfigSettings.DestinationCertThumbprint); } public class SingleHttpClientInstance { private static readonly HttpClient HttpClient; static SingleHttpClientInstance() { HttpClient = new HttpClient(); } public static async Task<HttpResponseMessage> SendRequest(HttpRequestMessage req) { HttpResponseMessage response = await HttpClient.SendAsync(req); return response; } } private static bool ValidateMyCert(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslErr) { // if user has not configured a cert, anything goes if (String.IsNullOrWhiteSpace(ExpectedRemoteCertThumbprint)) return true; // if user has configured a cert, must match string thumbprint = cert.GetCertHashString(); if (thumbprint == ExpectedRemoteCertThumbprint) return true; return false; } public static async Task SendEvents(List<string> standardizedEvents, ILogger log) { string destinationAddress = Config.GetValue(ConfigSettings.DestinationAddress); if (String.IsNullOrWhiteSpace(destinationAddress)) { log.LogError("destinationAddress config setting is required and not set."); return; } string destinationToken = Config.GetValue(ConfigSettings.DestinationToken); if (String.IsNullOrWhiteSpace(destinationToken)) { log.LogInformation("destinationToken config setting is not set; proceeding with anonymous call."); } ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateMyCert); // HACK: Build the list of events into a JSON array because that is the format the Azure Event Grid Viewer expects StringBuilder newClientContent = new StringBuilder(); newClientContent.Append("["); for (int iEvent = 0; iEvent < standardizedEvents.Count; iEvent++) { newClientContent.Append(standardizedEvents[iEvent]); if (iEvent != standardizedEvents.Count - 1) { newClientContent.Append(","); } } newClientContent.Append("]"); if (Config.GetBool(ConfigSettings.LogRawData)) { log.LogInformation($"Sending:\r\n{newClientContent.ToString()}"); } SingleHttpClientInstance client = new SingleHttpClientInstance(); try { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, destinationAddress); req.Headers.Accept.Clear(); req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (!String.IsNullOrWhiteSpace(destinationToken)) { req.Headers.Add("Authorization", "Bearer " + destinationToken); } // WebHook stuff req.Headers.Add("aeg-event-type", "Notification"); req.Content = new StringContent(newClientContent.ToString(), Encoding.UTF8, "application/json"); HttpResponseMessage response = await SingleHttpClientInstance.SendRequest(req); if (response.StatusCode == HttpStatusCode.OK) { log.LogInformation("Send successful"); } else { throw new System.Net.Http.HttpRequestException($"Request failed. StatusCode: {response.StatusCode}, and reason: {response.ReasonPhrase}"); } } catch (System.Net.Http.HttpRequestException hrex) { log.LogError($"Http error while sending: {hrex}"); throw; } catch (Exception ex) { log.LogError($"Unexpected error while sending: {ex}"); throw; } } } }
32.168675
144
0.7397
[ "MIT" ]
chrisbro-MSFT/AzureFunctionforSplunkVS
AzureLogExporter/Utils.cs
5,342
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SolidCubeClick : MonoBehaviour { // Start is called before the first frame update void Start() { } public GameObject solideCubeElement; private void OnMouseDown() { var element = solideCubeElement.GetComponent<SolideCubeElement>(); element.IsClickedSelf = true; } // Update is called once per frame void Update() { } }
17.851852
74
0.670124
[ "MIT" ]
catcat0921/lindexi_gd
unity/SolidGeometry/Assets/03.Script/SolidCubeClick.cs
484
C#
using gpayments_core.Model; using gpayments_core.Utils; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RestSharp; using System; using System.Collections.Generic; using System.Net; namespace gpayments_core { public class FourGeeksPayments { public Token Token { get; } private static string BaseUrl = "https://api.payments.4geeks.io/"; private static string AuthUrl = $"{BaseUrl}authentication/token/"; private static string MeUrl = $"{BaseUrl}v1/accounts/me/"; private static string CustomersUrl = $"{BaseUrl}v1/accounts/customers/"; private static string CustomerUrl = $"{BaseUrl}v1/accounts/customer/"; private static string ChargeUrl = $"{BaseUrl}v1/charges/create/"; private static string SimpleChargeUrl = $"{BaseUrl}v1/charges/simple/create/"; private static string LogsUrl = $"{BaseUrl}v1/charges/logs/"; private static string PlanCreateUrl = $"{BaseUrl}v1/plans/create/"; private static string PlansUrl = $"{BaseUrl}v1/plans/mine/"; private static string SubscribeUrl = $"{BaseUrl}v1/plans/subscribe/"; private static string SubscriptionsUrl = $"{BaseUrl}v1/plans/subscriptions/"; private static string SubscriptionUrl = $"{BaseUrl}v1/plans/subscription/"; private static string SubscriptionDeleteUrl = $"{BaseUrl}v1/plans/un-subscribe/"; private static string RefundUrl = $"{BaseUrl}v1/refunds/"; /// <summary> /// This constructor expects client_id and client_secret generated by 4Geeks /// </summary> /// <param name="client_id">ClientId</param> /// <param name="client_secret">ClientSecret</param> public FourGeeksPayments(string client_id, string client_secret) { Guard.NotNullOrEmpty(client_id); Guard.NotNullOrEmpty(client_secret); this.Token = GenerateToken(client_id, client_secret); } /// <summary> /// This constructor use the environment variables for ClientId and ClientSecret /// </summary> public FourGeeksPayments() { string client_id = Environment.GetEnvironmentVariable("client_id", EnvironmentVariableTarget.User); string client_secret = Environment.GetEnvironmentVariable("client_secret", EnvironmentVariableTarget.User); Guard.NotNullOrEmpty(client_id); Guard.NotNullOrEmpty(client_secret); this.Token = GenerateToken(client_id, client_secret); } /// <summary> /// This method requests a token to 4Geeks.io /// </summary> /// <param name="client_id">ClientId</param> /// <param name="client_secret">ClientSecret</param> /// <returns><see cref="Token"/></returns> private Token GenerateToken(string client_id, string client_secret) { try { var client = new RestClient(AuthUrl); var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); dynamic jsonObject = new JObject(); jsonObject.grant_type = "client_credentials"; jsonObject.client_id = client_id; jsonObject.client_secret = client_secret; request.AddParameter("application/json", jsonObject, ParameterType.RequestBody); return ProcessResponse.Process<Token>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Me GetMyDevInfo() { try { var client = new RestClient(MeUrl); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<Me>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Me UpdateMyDevInfo(Me newMe) { try { var client = new RestClient(MeUrl); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); request.AddParameter("application/json", JsonConvert.SerializeObject(newMe), ParameterType.RequestBody); return ProcessResponse.Process<Me>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public IEnumerable<Customer> GetCustomers() { try { var client = new RestClient(CustomersUrl); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<IEnumerable<Customer>>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Customer CreateCustomer(Customer customer) { try { var client = new RestClient(CustomersUrl); var request = new RestRequest(Method.POST); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); dynamic customerJSON = new JObject(); customerJSON.name = customer.Name; customerJSON.email = customer.Email; customerJSON.currency = customer.Currency; customerJSON.credit_card_number = customer.Card.CardNumber; customerJSON.credit_card_security_code_number = customer.Card.CVC; customerJSON.exp_month = customer.Card.ExpirationMonth; customerJSON.exp_year = customer.Card.ExpirationYear; request.AddParameter("application/json", customerJSON, ParameterType.RequestBody); return ProcessResponse.Process<Customer>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Customer GetCustomer(string customerKey) { try { var client = new RestClient($"{CustomerUrl}{customerKey}/"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<Customer>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Customer UpdateCustomer(Customer customer) { try { var client = new RestClient($"{CustomerUrl}{customer.Key}/"); var request = new RestRequest(Method.PUT); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); dynamic customerJSON = new JObject(); customerJSON.name = customer.Name; customerJSON.email = customer.Email; customerJSON.currency = customer.Currency; customerJSON.credit_card_number = customer.Card.CardNumber; customerJSON.credit_card_security_code_number = customer.Card.CVC; customerJSON.exp_month = customer.Card.ExpirationMonth; customerJSON.exp_year = customer.Card.ExpirationYear; request.AddParameter("application/json", customerJSON, ParameterType.RequestBody); return ProcessResponse.Process<Customer>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public bool DeleteCustomer(string key) { try { var client = new RestClient($"{CustomerUrl}{key}/"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process(client.Execute(request), HttpStatusCode.NoContent); } catch (Exception ex) { throw ex; } } public bool CreateCharge(Charge charge) { try { var client = new RestClient(ChargeUrl); var request = new RestRequest(Method.POST); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); request.AddParameter("application/json", JsonConvert.SerializeObject(charge), ParameterType.RequestBody); return ProcessResponse.Process(client.Execute(request), HttpStatusCode.Created); } catch (Exception ex) { throw ex; } } public bool CreateSimpleCharge(SimpleCharge simpleCharge) { try { var client = new RestClient(SimpleChargeUrl); var request = new RestRequest(Method.POST); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); request.AddParameter("application/json", JsonConvert.SerializeObject(simpleCharge), ParameterType.RequestBody); return ProcessResponse.Process(client.Execute(request), HttpStatusCode.Created); } catch (Exception ex) { throw ex; } } public IEnumerable<Log> GetLogs() { try { var client = new RestClient(LogsUrl); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<IEnumerable<Log>>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Log GetLog(string logId) { try { var client = new RestClient($"{LogsUrl}{logId}/"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<Log>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public bool CreatePlan(Plan plan) { try { var client = new RestClient(PlanCreateUrl); var request = new RestRequest(Method.POST); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); dynamic planJSON = new JObject(); planJSON.name = plan.Name; planJSON.amount = 10.50;// plan.Amount.ToString(); planJSON.trial_period_days = plan.TrialPeriodDays; planJSON.interval = plan.Interval.ToString(); planJSON.interval_count = plan.IntervalCount.ToString(); planJSON.credit_card_description = plan.CreditCardDescription; planJSON.currency = plan.Currency; request.AddParameter("application/json", planJSON, ParameterType.RequestBody); return ProcessResponse.Process(client.Execute(request), HttpStatusCode.Created); } catch (Exception ex) { throw ex; } } public IEnumerable<ListPlan> GetPlans() { try { var client = new RestClient(PlansUrl); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<IEnumerable<ListPlan>>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public ListPlan GetPlan(string planKey) { try { var client = new RestClient($"{PlansUrl}{planKey}/"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<ListPlan>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public bool DeletePlan(string planKey) { try { var client = new RestClient($"{PlansUrl}{planKey}/"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process(client.Execute(request), HttpStatusCode.NoContent); } catch (Exception ex) { throw ex; } } public bool CreateSubscription(string customerKey, string planKey) { try { var client = new RestClient(SubscribeUrl); var request = new RestRequest(Method.POST); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); request.AddParameter("application/json", JsonConvert.SerializeObject(new { customer_key = customerKey, plan_key = planKey }), ParameterType.RequestBody); return ProcessResponse.Process(client.Execute(request), HttpStatusCode.Created); } catch (Exception ex) { throw ex; } } public IEnumerable<Subscription> GetSubscriptions() { try { var client = new RestClient(SubscriptionsUrl); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<IEnumerable<Subscription>>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Subscription GetSubscription(string subscriptionKey) { try { var client = new RestClient($"{SubscriptionUrl}{subscriptionKey}/"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<Subscription>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public bool DeleteSubscription(string subscriptionKey) { try { var client = new RestClient($"{SubscriptionDeleteUrl}{subscriptionKey}/"); var request = new RestRequest(Method.DELETE); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process(client.Execute(request), HttpStatusCode.NoContent); } catch (Exception ex) { throw ex; } } public Refund CreateRefund(double amount, string chargeId, string reason) { try { var client = new RestClient(RefundUrl); var request = new RestRequest(Method.POST); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); request.AddParameter("application/json", JsonConvert.SerializeObject(new { amount, charge_id = chargeId, reason }), ParameterType.RequestBody); return ProcessResponse.Process<Refund>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public IEnumerable<Refund> GetRefunds() { try { var client = new RestClient(RefundUrl); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<IEnumerable<Refund>>(client.Execute(request)); } catch (Exception ex) { throw ex; } } public Refund GetRefund(string refundKey) { try { var client = new RestClient($"{RefundUrl}{refundKey}/"); var request = new RestRequest(Method.GET); request.AddHeader("authorization", $"bearer {this.Token.Access_Token}"); return ProcessResponse.Process<Refund>(client.Execute(request)); } catch (Exception ex) { throw ex; } } } }
35.915984
127
0.544246
[ "MIT" ]
djhvscf/gpayments-dotnet-core
gpayments-dotnet-core/FourGeeksPayments.cs
17,529
C#
using System; using System.Collections.Generic; using System.Text; namespace NetCDF { public enum NcResult : int { NC_NOERR = 0, /* No Error */ NC2_ERR = -1, /* Returned for all errors in the v2 API. */ NC_EBADID = -33, /* Not a netcdf id */ NC_ENFILE = -34, /* Too many netcdfs open */ NC_EEXIST = -35, /* netcdf file exists && NC_NOCLOBBER */ NC_EINVAL = -36, /* Invalid Argument */ NC_EPERM = -37, /* Write to read only */ NC_ENOTINDEFINE = -38, /* Operation not allowed in data mode */ NC_EINDEFINE = -39, /* Operation not allowed in define mode */ NC_EINVALCOORDS = -40, /* Index exceeds dimension bound */ NC_EMAXDIMS = -41, /* NC_MAX_DIMS exceeded */ NC_ENAMEINUSE = -42, /* String match to name in use */ NC_ENOTATT = -43, /* Attribute not found */ NC_EMAXATTS = -44, /* NC_MAX_ATTRS exceeded */ NC_EBADTYPE = -45, /* Not a netcdf data type */ NC_EBADDIM = -46, /* Invalid dimension id or name */ NC_EUNLIMPOS = -47, /* NC_UNLIMITED in the wrong index */ NC_EMAXVARS = -48, /* NC_MAX_VARS exceeded */ NC_ENOTVAR = -49, /* Variable not found */ NC_EGLOBAL = -50, /* Action prohibited on NC_GLOBAL varid */ NC_ENOTNC = -51, /* Not a netcdf file */ NC_ESTS = -52, /* In Fortran, string too short */ NC_EMAXNAME = -53, /* NC_MAX_NAME exceeded */ NC_EUNLIMIT = -54, /* NC_UNLIMITED size already in use */ NC_ENORECVARS = -55, /* nc_rec op when there are no record vars */ NC_ECHAR = -56, /* Attempt to convert between text & numbers */ NC_EEDGE = -57, /* Start+count exceeds dimension bound */ NC_ESTRIDE = -58, /* Illegal stride */ NC_EBADNAME = -59, /* Attribute or variable name contains illegal characters */ /* N.B. following must match value in ncx.h */ NC_ERANGE = -60, /* Math result not representable */ NC_ENOMEM = -61, /* Memory allocation malloc, failure */ NC_EVARSIZE = -62, /* One or more variable sizes violate format constraints */ NC_EDIMSIZE = -63, /* Invalid dimension size */ NC_ETRUNC = -64, /* File likely truncated or possibly corrupted */ } }
51.375
92
0.551906
[ "MPL-2.0" ]
AuditoryBiophysicsLab/ESME-Workbench
Libraries/NetCDF/NcResult.cs
2,466
C#
namespace TestProject.Roles.Dto { public class GetRolesInput { public string Permission { get; set; } } }
15.875
46
0.629921
[ "MIT" ]
VictorIzosimov/TestProject
aspnet-core/src/TestProject.Application/Roles/Dto/GetRolesInput.cs
129
C#
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using BeautifulRestApi.Infrastructure; using BeautifulRestApi.Models; using BeautifulRestApi.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace BeautifulRestApi.Controllers { [Route("/[controller]")] public class CommentsController : Controller { private readonly ICommentService _commentService; private readonly PagingOptions _defaultPagingOptions; public CommentsController( ICommentService commentService, IOptions<PagingOptions> defaultPagingOptionsAccessor) { _commentService = commentService; _defaultPagingOptions = defaultPagingOptionsAccessor.Value; } [HttpGet(Name = nameof(GetCommentsAsync))] [ValidateModel] public async Task<IActionResult> GetCommentsAsync( [FromQuery] PagingOptions pagingOptions, CancellationToken ct) { pagingOptions.Offset = pagingOptions.Offset ?? _defaultPagingOptions.Offset; pagingOptions.Limit = pagingOptions.Limit ?? _defaultPagingOptions.Limit; var conversations = await _commentService.GetCommentsAsync(null, pagingOptions, ct); var collection = CollectionWithPaging<CommentResource>.Create( Link.ToCollection(nameof(GetCommentsAsync)), conversations.Items.ToArray(), conversations.TotalSize, pagingOptions); return Ok(collection); } [HttpGet("{CommentId}", Name = nameof(GetCommentByIdAsync))] [ValidateModel] public async Task<IActionResult> GetCommentByIdAsync(GetCommentByIdParameters parameters, CancellationToken ct) { if (parameters.CommentId == Guid.Empty) return NotFound(); var conversation = await _commentService.GetCommentAsync(parameters.CommentId, ct); if (conversation == null) return NotFound(); return Ok(conversation); } } }
35.033333
119
0.678402
[ "Apache-2.0" ]
hieumoscow/ConversationCore
src/Controllers/CommentsController.cs
2,104
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Specification.Tests; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; // ReSharper disable InconsistentNaming // ReSharper disable AccessToDisposedClosure // ReSharper disable ReturnValueOfPureMethodIsNotUsed // ReSharper disable StringStartsWithIsCultureSpecific namespace Microsoft.EntityFrameworkCore.InMemory.FunctionalTests { public class DatabaseErrorLogStateTest { [Fact] public async Task SaveChanges_logs_DatabaseErrorLogState_nonasync() { await SaveChanges_logs_DatabaseErrorLogState(async: false); } [Fact] public async Task SaveChanges_logs_DatabaseErrorLogState_async() { await SaveChanges_logs_DatabaseErrorLogState(async: true); } public async Task SaveChanges_logs_DatabaseErrorLogState(bool async) { var loggerFactory = new TestLoggerFactory(); var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .AddSingleton<ILoggerFactory>(loggerFactory) .BuildServiceProvider(); using (var context = new BloggingContext(serviceProvider)) { context.Blogs.Add(new BloggingContext.Blog(jimSaysThrow: false) { Url = "http://sample.com" }); context.SaveChanges(); context.ChangeTracker.Entries().Single().State = EntityState.Added; Exception ex; if (async) { ex = await Assert.ThrowsAsync<ArgumentException>(() => context.SaveChangesAsync()); } else { ex = Assert.Throws<ArgumentException>(() => context.SaveChanges()); } Assert.Same(ex, loggerFactory.Logger.LastDatabaseErrorException); Assert.Same(typeof(BloggingContext), loggerFactory.Logger.LastDatabaseErrorState.ContextType); Assert.EndsWith(ex.ToString(), loggerFactory.Logger.LastDatabaseErrorFormatter(loggerFactory.Logger.LastDatabaseErrorState, ex)); } } [Fact] public void Query_logs_DatabaseErrorLogState_during_DbSet_enumeration() { Query_logs_DatabaseErrorLogState(c => c.Blogs.ToList()); } [Fact] public void Query_logs_DatabaseErrorLogState_during_DbSet_enumeration_async() { Query_logs_DatabaseErrorLogState(c => c.Blogs.ToListAsync().Wait()); } [Fact] public void Query_logs_DatabaseErrorLogState_during_LINQ_enumeration() { Query_logs_DatabaseErrorLogState(c => c.Blogs .OrderBy(b => b.Name) .Where(b => b.Url.StartsWith("http://")) .ToList()); } [Fact] public void Query_logs_DatabaseErrorLogState_during_LINQ_enumeration_async() { Query_logs_DatabaseErrorLogState(c => c.Blogs .OrderBy(b => b.Name) .Where(b => b.Url.StartsWith("http://")) .ToListAsync() .Wait()); } [Fact] public void Query_logs_DatabaseErrorLogState_during_single() { Query_logs_DatabaseErrorLogState(c => c.Blogs.FirstOrDefault()); } [Fact] public void Query_logs_DatabaseErrorLogState_during_single_async() { Query_logs_DatabaseErrorLogState(c => c.Blogs.FirstOrDefaultAsync().Wait()); } public void Query_logs_DatabaseErrorLogState(Action<BloggingContext> test) { var loggerFactory = new TestLoggerFactory(); var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .AddSingleton<ILoggerFactory>(loggerFactory) .BuildServiceProvider(); using (var context = new BloggingContext(serviceProvider)) { context.Blogs.Add(new BloggingContext.Blog(false) { Url = "http://sample.com" }); context.SaveChanges(); var entry = context.ChangeTracker.Entries().Single().GetInfrastructure(); context.ChangeTracker.GetInfrastructure().StopTracking(entry); var ex = Assert.ThrowsAny<Exception>(() => test(context)); while (ex.InnerException != null) { ex = ex.InnerException; } Assert.Equal("Jim said to throw from ctor!", ex.Message); Assert.Same(ex, loggerFactory.Logger.LastDatabaseErrorException); Assert.Same(typeof(BloggingContext), loggerFactory.Logger.LastDatabaseErrorState.ContextType); Assert.EndsWith(ex.ToString(), loggerFactory.Logger.LastDatabaseErrorFormatter(loggerFactory.Logger.LastDatabaseErrorState, ex)); } } [Fact] public async Task SaveChanges_logs_concurrent_access_nonasync() { await SaveChanges_logs_concurrent_access(async: false); } [Fact] public async Task SaveChanges_logs_concurrent_access_async() { await SaveChanges_logs_concurrent_access(async: true); } public async Task SaveChanges_logs_concurrent_access(bool async) { var loggerFactory = new TestLoggerFactory(); var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .AddSingleton<ILoggerFactory>(loggerFactory) .BuildServiceProvider(); using (var context = new BloggingContext(serviceProvider)) { context.Blogs.Add(new BloggingContext.Blog(false) { Url = "http://sample.com" }); context.GetService<IConcurrencyDetector>().EnterCriticalSection(); Exception ex; if (async) { ex = await Assert.ThrowsAsync<InvalidOperationException>(() => context.SaveChangesAsync()); } else { ex = Assert.Throws<InvalidOperationException>(() => context.SaveChanges()); } Assert.Equal(CoreStrings.ConcurrentMethodInvocation, ex.Message); } } public class BloggingContext : DbContext { private readonly IServiceProvider _serviceProvider; public BloggingContext(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public DbSet<Blog> Blogs { get; set; } public class Blog { public Blog() : this(true) { } public Blog(bool jimSaysThrow) { if (jimSaysThrow) { throw new ArgumentException("Jim said to throw from ctor!"); } } public string Url { get; set; } public string Name { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Blog>().HasKey(b => b.Url); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseTransientInMemoryDatabase() .UseInternalServiceProvider(_serviceProvider); } private class TestLoggerFactory : ILoggerFactory { public readonly TestLogger Logger = new TestLogger(); public void AddProvider(ILoggerProvider provider) { } public ILogger CreateLogger(string name) => Logger; public void Dispose() { } public class TestLogger : ILogger { public IDisposable BeginScope<TState>(TState state) => NullScope.Instance; public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { var error = state as DatabaseErrorLogState; if (error != null) { LastDatabaseErrorState = error; LastDatabaseErrorException = exception; LastDatabaseErrorFormatter = (s, e) => formatter((TState)s, e); } } public bool IsEnabled(LogLevel logLevel) => true; public DatabaseErrorLogState LastDatabaseErrorState { get; private set; } public Exception LastDatabaseErrorException { get; private set; } public Func<object, Exception, string> LastDatabaseErrorFormatter { get; private set; } } } } }
37.431373
153
0.585228
[ "Apache-2.0" ]
pmiddleton/EntityFramework
test/EFCore.InMemory.FunctionalTests/DatabaseErrorLogStateTest.cs
9,545
C#
using System; namespace CodingChallenge { class Program { static void Main(string[] args) { // first initialize the variables for counting each scenario int sweetCount = 0; int saltyCount = 0; int sweetSaltyCount = 0; // create a for loop to iterate from 1 - 100 for (int num = 1; num < 101; num++) { // first check if the number is divisible by 3 & 5 if ((num % 3) == 0 && (num % 5) == 0) { Console.WriteLine("sweet'nSalty"); sweetSaltyCount++; // add one to the multiple of 3 & 5 secanario } else if (num % 3 == 0) // then check if divisible by 3 { Console.WriteLine("sweet"); sweetCount++; // add one to the multiple of 3 scenario } else if (num % 5 == 0) // then check if divisible by 5 { Console.WriteLine("salty"); saltyCount++; // add one to the multiple of 5 scenario } else { Console.WriteLine(num); // prints out the number if none of the scenarios happened } } // finally print out the total number of each scenario Console.WriteLine($"There were {sweetCount} sweet's, {saltyCount} salty's," + $" and {sweetSaltyCount} sweet'nSalty's!"); } } }
34.977778
102
0.463151
[ "MIT" ]
042020-dotnet-uta/michaelHall-repo0
CodingChallenge/Program.cs
1,576
C#
// Generated by gencs from sensor_msgs/PointCloud2.msg // DO NOT EDIT THIS FILE BY HAND! using System; using System.Collections; using System.Collections.Generic; using SIGVerse.RosBridge; using UnityEngine; using SIGVerse.RosBridge.std_msgs; using SIGVerse.RosBridge.sensor_msgs; namespace SIGVerse.RosBridge { namespace sensor_msgs { [System.Serializable] public class PointCloud2 : RosMessage { public std_msgs.Header header; public System.UInt32 height; public System.UInt32 width; public System.Collections.Generic.List<sensor_msgs.PointField> fields; public bool is_bigendian; public System.UInt32 point_step; public System.UInt32 row_step; public System.Collections.Generic.List<byte> data; public bool is_dense; public PointCloud2() { this.header = new std_msgs.Header(); this.height = 0; this.width = 0; this.fields = new System.Collections.Generic.List<sensor_msgs.PointField>(); this.is_bigendian = false; this.point_step = 0; this.row_step = 0; this.data = new System.Collections.Generic.List<byte>(); this.is_dense = false; } public PointCloud2(std_msgs.Header header, System.UInt32 height, System.UInt32 width, System.Collections.Generic.List<sensor_msgs.PointField> fields, bool is_bigendian, System.UInt32 point_step, System.UInt32 row_step, System.Collections.Generic.List<byte> data, bool is_dense) { this.header = header; this.height = height; this.width = width; this.fields = fields; this.is_bigendian = is_bigendian; this.point_step = point_step; this.row_step = row_step; this.data = data; this.is_dense = is_dense; } new public static string GetMessageType() { return "sensor_msgs/PointCloud2"; } new public static string GetMD5Hash() { return "1158d486dd51d683ce2f1be655c3c181"; } } // class PointCloud2 } // namespace sensor_msgs } // namespace SIGVerse.ROSBridge
27.985714
282
0.727922
[ "MIT" ]
Ohara124c41/TUB-MSc_Thesis
SEK_01_MkI/Assets/SIGVerse/Common/ROSBridge/messaging/sensor_msgs/PointCloud2.cs
1,959
C#
using CefSharp; using Playnite; using Playnite.API; using Playnite.Common.System; using Playnite.Database; using Playnite.Plugins; using Playnite.SDK; using Playnite.SDK.Plugins; using Playnite.Settings; using PlayniteUI.Commands; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace PlayniteUI.ViewModels { public class SelectablePlugin : ObservableObject { public IPlugin Plugin { get; set; } public ExtensionDescription Description { get; set; } public string PluginIcon { get; set; } = string.Empty; private bool selected; public bool Selected { get => selected; set { selected = value; OnPropertyChanged(); } } public SelectablePlugin() { } public SelectablePlugin(bool selected, IPlugin plugin, ExtensionDescription description) { Selected = selected; Plugin = plugin; Description = description; if (!string.IsNullOrEmpty(description.Icon)) { PluginIcon = Path.Combine(Path.GetDirectoryName(description.DescriptionPath), description.Icon); } else if (description.Type == ExtensionType.Script && description.Module.EndsWith("ps1", StringComparison.OrdinalIgnoreCase)) { PluginIcon = @"/Images/powershell.ico"; } else if (description.Type == ExtensionType.Script && description.Module.EndsWith("py", StringComparison.OrdinalIgnoreCase)) { PluginIcon = @"/Images/python.ico"; } else { PluginIcon = @"/Images/csharp.ico"; } } } public class PluginSettings { public ISettings Settings { get; set; } public UserControl View { get; set; } public string Name { get; set; } public string Icon { get; set; } } public class SettingsViewModel : ObservableObject { private static ILogger logger = LogManager.GetLogger(); private IWindowFactory window; private IDialogsFactory dialogs; private IResourceProvider resources; private GameDatabase database; public ExtensionFactory Extensions { get; set; } private PlayniteSettings settings; public PlayniteSettings Settings { get { return settings; } set { settings = value; OnPropertyChanged(); } } public bool AnyGenericPluginSettings { get => GenericPluginSettings?.Any() == true; } public List<Theme> AvailableSkins { get => Themes.AvailableThemes; } public List<PlayniteLanguage> AvailableLanguages { get => Localization.AvailableLanguages; } public List<Theme> AvailableFullscreenSkins { get => Themes.AvailableFullscreenThemes; } public bool ProviderIntegrationChanged { get; private set; } = false; public bool DatabaseLocationChanged { get; private set; } = false; public List<SelectablePlugin> PluginsList { get; } public Dictionary<Guid, PluginSettings> LibraryPluginSettings { get; } = new Dictionary<Guid, PluginSettings>(); public Dictionary<Guid, PluginSettings> GenericPluginSettings { get; } = new Dictionary<Guid, PluginSettings>(); #region Commands public RelayCommand<object> CancelCommand { get => new RelayCommand<object>((a) => { CloseView(); }); } public RelayCommand<object> ConfirmCommand { get => new RelayCommand<object>((a) => { ConfirmDialog(); }); } public RelayCommand<object> WindowClosingCommand { get => new RelayCommand<object>((a) => { WindowClosing(false); }); } public RelayCommand<object> SelectDbFileCommand { get => new RelayCommand<object>((a) => { SelectDbFile(); }); } public RelayCommand<object> ClearWebCacheCommand { get => new RelayCommand<object>((url) => { ClearWebcache(); }); } #endregion Commands public SettingsViewModel( GameDatabase database, PlayniteSettings settings, IWindowFactory window, IDialogsFactory dialogs, IResourceProvider resources, ExtensionFactory extensions) { Extensions = extensions; Settings = settings; Settings.BeginEdit(); this.database = database; this.window = window; this.dialogs = dialogs; this.resources = resources; PluginsList = Extensions .GetExtensionDescriptors() .Select(a => new SelectablePlugin(Settings.DisabledPlugins?.Contains(a.FolderName) != true, null, a)) .ToList(); foreach (var provider in Extensions.LibraryPlugins.Values) { var provSetting = provider.Plugin.GetSettings(false); var provView = provider.Plugin.GetSettingsView(false); if (provSetting != null && provView != null) { provView.DataContext = provSetting; provSetting.BeginEdit(); var plugSetting = new PluginSettings() { Name = provider.Plugin.Name, Settings = provSetting, View = provView, Icon = provider.Plugin.LibraryIcon }; LibraryPluginSettings.Add(provider.Plugin.Id, plugSetting); } } foreach (var plugin in Extensions.GenericPlugins.Values) { var provSetting = plugin.Plugin.GetSettings(false); var provView = plugin.Plugin.GetSettingsView(false); if (provSetting != null && provView != null) { provView.DataContext = provSetting; provSetting.BeginEdit(); var plugSetting = new PluginSettings() { Name = plugin.Description.Name, Settings = provSetting, View = provView }; GenericPluginSettings.Add(plugin.Plugin.Id, plugSetting); } } } public bool? OpenView() { return window.CreateAndOpenDialog(this); } public void CloseView() { Settings.CancelEdit(); foreach (var provider in LibraryPluginSettings.Keys) { LibraryPluginSettings[provider].Settings.CancelEdit(); } foreach (var provider in GenericPluginSettings.Keys) { GenericPluginSettings[provider].Settings.CancelEdit(); } WindowClosing(true); window.Close(false); } public void WindowClosing(bool closingHandled) { if (closingHandled) { return; } Settings.CancelEdit(); } public void ConfirmDialog() { foreach (var provider in LibraryPluginSettings.Keys) { if (!LibraryPluginSettings[provider].Settings.VerifySettings(out var errors)) { dialogs.ShowErrorMessage(string.Join(Environment.NewLine, errors), LibraryPluginSettings[provider].Name); return; } } foreach (var plugin in GenericPluginSettings.Keys) { if (!GenericPluginSettings[plugin].Settings.VerifySettings(out var errors)) { dialogs.ShowErrorMessage(string.Join(Environment.NewLine, errors), GenericPluginSettings[plugin].Name); return; } } var disabledPlugs = PluginsList.Where(a => !a.Selected)?.Select(a => a.Description.FolderName).ToList(); if (Settings.DisabledPlugins?.IsListEqual(disabledPlugs) != true) { Settings.DisabledPlugins = PluginsList.Where(a => !a.Selected)?.Select(a => a.Description.FolderName).ToList(); } if (Settings.EditedFields.Contains(nameof(Settings.StartOnBoot))) { try { PlayniteSettings.SetBootupStateRegistration(Settings.StartOnBoot); } catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors) { logger.Error(e, "Failed to register Playnite to start on boot."); dialogs.ShowErrorMessage(resources.FindString("LOCSettingsStartOnBootRegistrationError") + Environment.NewLine + e.Message, ""); } } Settings.EndEdit(); Settings.SaveSettings(); foreach (var provider in LibraryPluginSettings.Keys) { LibraryPluginSettings[provider].Settings.EndEdit(); } foreach (var plugin in GenericPluginSettings.Keys) { GenericPluginSettings[plugin].Settings.EndEdit(); } if (Settings.EditedFields?.Any() == true) { if (Settings.EditedFields.IntersectsExactlyWith( new List<string>() { nameof(Settings.Skin), nameof(Settings.AsyncImageLoading), nameof(Settings.DisableHwAcceleration), nameof(Settings.DisableDpiAwareness), nameof(Settings.DatabasePath), nameof(Settings.DisabledPlugins) })) { if (dialogs.ShowMessage( resources.FindString("LOCSettingsRestartAskMessage"), resources.FindString("LOCSettingsRestartTitle"), MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { App.CurrentApp.Restart(); } } } WindowClosing(true); window.Close(true); } public void SelectDbFile() { var path = dialogs.SelectFolder(); if (!string.IsNullOrEmpty(path)) { dialogs.ShowMessage(resources.FindString("LOCSettingsDBPathNotification")); Settings.DatabasePath = path; Settings.OnPropertyChanged("DatabasePath", true); } } public void ClearWebcache() { if (dialogs.ShowMessage( resources.FindString("LOCSettingsClearCacheWarn"), resources.FindString("LOCSettingsClearCacheTitle"), MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { Cef.Shutdown(); System.IO.Directory.Delete(PlaynitePaths.BrowserCachePath, true); App.CurrentApp.Restart(); } } } }
32.411311
137
0.504442
[ "MIT" ]
ArashBaba/Playnite
source/PlayniteUI/ViewModels/SettingsViewModel.cs
12,610
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; namespace EfsTools.Items.Efs { [Serializable] [EfsFile("/nv/item_files/rfnv/00024907", true, 0xE1FF)] [Attributes(9)] public class LteB33TxLinMasterForApt1 { [ElementsCount(64)] [ElementType("uint16")] [Description("")] public ushort[] TxLinMasterForApt1 { get; set; } } }
22.571429
60
0.630802
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Efs/LteB33TxLinMasterForApt1I.cs
474
C#
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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. */ #pragma warning disable 1591 using System; using System.ComponentModel; using System.Diagnostics; using System.Xml.Serialization; namespace DotNetCasClient.Validation.Schema.Saml11.Assertion { [Serializable] [DebuggerStepThrough] [DesignerCategory("code")] [XmlType(Namespace="urn:oasis:names:tc:SAML:1.0:assertion")] [XmlRoot("AudienceRestrictionCondition", Namespace="urn:oasis:names:tc:SAML:1.0:assertion", IsNullable=false)] public class AudienceRestrictionConditionType : ConditionAbstractType { [XmlElement("Audience", DataType="anyURI")] public string[] Audience { get; set; } } } #pragma warning restore 1591
33.568182
114
0.729181
[ "Apache-2.0" ]
abisteknoloji/dotnet-cas-client
DotNetCasClient/Validation/Schema/Saml11/Assertion/Condition/AudienceRestrictionConditionType.cs
1,479
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CopyText : MonoBehaviour { public GameObject First; private void Start() { this.gameObject.GetComponent<Text>().text = First.GetComponent<Text>().text; } private void Update() { TimeStealer(); } private void TimeStealer() { this.gameObject.GetComponent<Text>().text = First.GetComponent<Text>().text; } }
19.304348
78
0.725225
[ "MIT" ]
GeorgiosVeropoulos/CubeGame
Making a New Game/Assets/Scripts/CopyText.cs
446
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.Resources.MSGraph.Models.ApiV10Beta { using static Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Extensions; /// <summary>The structure of this object is service-specific</summary> public partial class OdataErrorMainInnererror { /// <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.Resources.MSGraph.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.Resources.MSGraph.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.Resources.MSGraph.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.Resources.MSGraph.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.Resources.MSGraph.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10Beta.IOdataErrorMainInnererror. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10Beta.IOdataErrorMainInnererror. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10Beta.IOdataErrorMainInnererror FromJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonObject json ? new OdataErrorMainInnererror(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonObject into a new instance of <see cref="OdataErrorMainInnererror" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonObject instance to deserialize from.</param> /// <param name="exclusions"></param> internal OdataErrorMainInnererror(Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet<string> exclusions = null) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.IAssociativeArray<global::System.Object>)this).AdditionalProperties, Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.JsonSerializable.DeserializeDictionary(()=>new global::System.Collections.Generic.Dictionary<global::System.String,global::System.Object>()),exclusions ); AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="OdataErrorMainInnererror" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.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.Resources.MSGraph.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="OdataErrorMainInnererror" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.IAssociativeArray<global::System.Object>)this).AdditionalProperties, container); AfterToJson(ref container); return container; } } }
71.317757
454
0.702529
[ "MIT" ]
ariklin/azure-powershell-1
src/Resources/MSGraph.Autorest/generated/api/Models/ApiV10Beta/OdataErrorMainInnererror.json.cs
7,525
C#
using Translation.Common.Models.Base; namespace Translation.Common.Models.Responses.Project { public class ProjectRestoreResponse : TranslationBaseResponse { } }
21.875
65
0.777143
[ "MIT" ]
Enisbeygorus/translation
Source/Translation.Common/Models/Responses/Project/ProjectRestoreResponse.cs
177
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.Diagnostics; using System.Runtime.Serialization; namespace System.Globalization { // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM March 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. public abstract class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; private int _currentEraValue = -1; private bool _isReadOnly = false; // The minimum supported DateTime range for the calendar. public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual CalendarId ID { get { return CalendarId.UNINITIALIZED_VALUE; } } /// // Return the Base calendar ID for calendars that didn't have defined data in calendarData // internal virtual CalendarId BaseCalendarID { get { return ID; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// public bool IsReadOnly { get { return (_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of ICloneable. // //////////////////////////////////////////////////////////////////////// public virtual object Clone() { object o = MemberwiseClone(); ((Calendar)o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState(true); return (clonedCalendar); } internal void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { _isReadOnly = readOnly; } /*=================================CurrentEraValue========================== **Action: This is used to convert CurretEra(0) to an appropriate era value. **Returns: **Arguments: **Exceptions: **Notes: ** The value is from calendar.nlp. ============================================================================*/ internal virtual int CurrentEraValue { get { // The following code assumes that the current era value can not be -1. if (_currentEraValue == -1) { Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID"); _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (_currentEraValue); } } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange, minValue, maxValue))); } } internal DateTime Add(DateTime time, double value, int scale) { // From ECMA CLI spec, Partition III, section 3.27: // // If overflow occurs converting a floating-point type to an integer, or if the floating-point value // being converted to an integer is a NaN, the value returned is unspecified. // // Based upon this, this method should be performing the comparison against the double // before attempting a cast. Otherwise, the result is undefined. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue); } long millis = (long)tempMillis; long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return (Add(time, milliseconds, 1)); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays(DateTime time, int days) { return (Add(time, days, MillisPerDay)); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours(DateTime time, int hours) { return (Add(time, hours, MillisPerHour)); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes(DateTime time, int minutes) { return (Add(time, minutes, MillisPerMinute)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public abstract DateTime AddMonths(DateTime time, int months); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, MillisPerSecond); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks(DateTime time, int weeks) { return (AddDays(time, weeks * 7)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public abstract DateTime AddYears(DateTime time, int years); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth(DateTime time); // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public abstract DayOfWeek GetDayOfWeek(DateTime time); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear(DateTime time); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth(int year, int month) { return (GetDaysInMonth(year, month, CurrentEra)); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth(int year, int month, int era); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear(int year) { return (GetDaysInYear(year, CurrentEra)); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear(int year, int era); // Returns the era for the specified DateTime value. public abstract int GetEra(DateTime time); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour(DateTime time) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds(DateTime time) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute(DateTime time) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth(DateTime time); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear(int year) { return (GetMonthsInYear(year, CurrentEra)); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear(int year, int era); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond(DateTime time) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day / 7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7; // Calculate the offset (how many days from the start of the year to the start of the week) int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7; if (offset == 0 || offset >= minimumDaysInFirstWeek) { // First of year falls in the first week of the year return 1; } int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7); // starting from first day of the year, how many days do you have to go forward // before getting to the first day of the week? int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7; int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek; if (daysInInitialPartialWeek >= minimumDaysInFirstWeek) { // If the offset is greater than the minimum Days in the first week, it means that // First of year is part of the first week of the year even though it is only a partial week // add another week day += 7; } return (day / 7 + 1); } // it would be nice to make this abstract but we can't since that would break previous implementations protected virtual int DaysInYearBeforeMinSupportedYear { get { return 365; } } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear(DateTime time); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay(int year, int month, int day) { return (IsLeapDay(year, month, day, CurrentEra)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public abstract bool IsLeapDay(int year, int month, int day, int era); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth(int year, int month) { return (IsLeapMonth(year, month, CurrentEra)); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public abstract bool IsLeapMonth(int year, int month, int era); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth(int year) { return (GetLeapMonth(year, CurrentEra)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) return 0; int monthsCount = GetMonthsInYear(year, era); for (int month = 1; month <= monthsCount; month++) { if (IsLeapMonth(year, month, era)) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear(int year) { return (IsLeapYear(year, CurrentEra)); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public abstract bool IsLeapYear(int year, int era); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime)); } internal virtual bool IsValidMonth(int year, int month, int era) { return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era)); } internal virtual bool IsValidDay(int year, int month, int day, int era) { return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era)); } // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.InvariantCulture, SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1))); } return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue) { int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID); if (twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } }
40.445898
157
0.562811
[ "MIT" ]
Alecu100/coreclr
src/mscorlib/shared/System/Globalization/Calendar.cs
34,015
C#
using System.Threading.Tasks; using Sitecore.Commerce.Core; using Sitecore.Commerce.EntityViews; using Sitecore.Commerce.Plugin.Orders; using Sitecore.Framework.Pipelines; using System.Linq; using Plugin.Konabos.Loyalty.Components; namespace Plugin.Konabos.Loyalty.Pipelines.Blocks { public class GetLoyaltyPointsOrderViewBlock : PipelineBlock<EntityView, EntityView, CommercePipelineExecutionContext> { public override Task<EntityView> Run(EntityView arg, CommercePipelineExecutionContext context) { EntityViewArgument entityViewArgument = context.CommerceContext.GetObject<EntityViewArgument>(); if (entityViewArgument.ViewName != context.GetPolicy<KnownOrderViewsPolicy>().Summary && entityViewArgument.ViewName != context.GetPolicy<KnownOrderViewsPolicy>().Master) { // Do nothing if this entityViewArgument is for a different view return Task.FromResult(arg); } if (entityViewArgument.Entity == null) { // Do nothing if there is no entity loaded return Task.FromResult(arg); } // Only do something if the Entity is an order if (!(entityViewArgument.Entity is Order)) { return Task.FromResult(arg); } var order = entityViewArgument.Entity as Order; EntityView entityViewToProcess = null; if (entityViewArgument.ViewName == context.GetPolicy<KnownOrderViewsPolicy>().Master) { entityViewToProcess = arg.ChildViews.FirstOrDefault(p => p.Name == "Summary") as EntityView; } else { entityViewToProcess = arg; } if (entityViewToProcess == null) { return Task.FromResult(arg); } int pointsEarned = order.HasComponent<LoyaltyComponent>() ? order.GetComponent<LoyaltyComponent>().PointsEarned : 0; int pointsSpent = order.HasComponent<LoyaltyComponent>() ? order.GetComponent<LoyaltyComponent>().PointsSpent : 0; entityViewToProcess.Properties.Add(new ViewProperty { Name = "Points Earned", DisplayName = "Points Earned", IsReadOnly = true, RawValue = pointsEarned, Value = pointsEarned.ToString() }); entityViewToProcess.Properties.Add(new ViewProperty { Name = "Points Spent", DisplayName = "Points Spent", IsReadOnly = true, RawValue = pointsSpent, Value = pointsSpent.ToString() }); return Task.FromResult(arg); } } }
45.824561
200
0.646631
[ "MIT" ]
konabos/Sitecore-Commerce-Loyalty
Konabos Commerce Engine/2. Feature/Feature.Loyalty/Engine/Plugin.Konabos.Loyalty/Pipelines/Blocks/GetLoyaltyPointsOrderViewBlock.cs
2,614
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; using System.Collections.Generic; using System.Text; using ClearCanvas.Enterprise.Common; using System.Runtime.Serialization; namespace ClearCanvas.Ris.Application.Common.RegistrationWorkflow.OrderEntry { [DataContract] public class GetOrderRequisitionForEditResponse : DataContractBase { public GetOrderRequisitionForEditResponse(EntityRef orderRef, OrderRequisition requisition) { this.OrderRef = orderRef; this.Requisition = requisition; } [DataMember] public OrderRequisition Requisition; [DataMember] public EntityRef OrderRef; } }
41.75
100
0.725406
[ "Apache-2.0" ]
econmed/ImageServer20
Ris/Application/Common/RegistrationWorkflow/OrderEntry/GetOrderRequisitionForEditResponse.cs
2,340
C#
namespace GuessingGame { partial class Form1 { /// <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.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(12, 110); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "Guess"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(113, 66); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(59, 20); this.textBox1.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(99, 37); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(86, 13); this.label1.TabIndex = 2; this.label1.Text = "Guess a Number"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label2.Location = new System.Drawing.Point(12, 230); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(260, 23); this.label2.TabIndex = 3; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Guessing Game"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; } }
38.323232
166
0.560622
[ "MIT" ]
rawmx/Projects
C Sharp/GuessingGame/GuessingGame/Form1.Designer.cs
3,796
C#
using UISleuth.Reactions; using UISleuth.Widgets; namespace UISleuth.Messages { /// <summary> /// Signal's that the client has requested a tree structure of the UI elements on the surface. /// This "document outline" is created by a <see cref="SurfaceManager"/>. /// </summary> internal class GetVisualTreeRequest : Request {} /// <summary> /// Sent in response to a <see cref="GetVisualTreeRequest"/>. /// </summary> internal class GetVisualTreeResponse : Response { /// <summary> /// The visual tree's top-most widget. /// </summary> public UIWidget Root { get; set; } } }
28.434783
98
0.62844
[ "MIT" ]
michaeled/uisleuth
Mobile/Source/UISleuth/Messages/GetVisualTreeRequest.cs
656
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 Xunit; namespace System.Linq.Expressions.Tests { public static class UnaryPlusTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusShortTest(bool useInterpreter) { short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusShort(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusUShortTest(bool useInterpreter) { ushort[] values = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusUShort(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusIntTest(bool useInterpreter) { int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusInt(values[i], useInterpreter); VerifyArithmeticMakeUnaryPlusInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusUIntTest(bool useInterpreter) { uint[] values = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusUInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusLongTest(bool useInterpreter) { long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusLong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusULongTest(bool useInterpreter) { ulong[] values = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusULong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusFloatTest(bool useInterpreter) { float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusFloat(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusDoubleTest(bool useInterpreter) { double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusDouble(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] //[WorkItem(3196, "https://github.com/dotnet/corefx/issues/3196")] public static void CheckUnaryArithmeticUnaryPlusDecimalTest(bool useInterpreter) { decimal[] values = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticUnaryPlusDecimal(values[i], useInterpreter); } } [Fact] public static void ToStringTest() { UnaryExpression e = Expression.UnaryPlus(Expression.Parameter(typeof(int), "x")); Assert.Equal("+x", e.ToString()); } #endregion #region Test verifiers private static void VerifyArithmeticUnaryPlusShort(short value, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.UnaryPlus(Expression.Constant(value, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal((short)(+value), f()); } private static void VerifyArithmeticUnaryPlusUShort(ushort value, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.UnaryPlus(Expression.Constant(value, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal((ushort)(+value), f()); } private static void VerifyArithmeticUnaryPlusInt(int value, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.UnaryPlus(Expression.Constant(value, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal((int)(+value), f()); } private static void VerifyArithmeticMakeUnaryPlusInt(int value, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.MakeUnary(ExpressionType.UnaryPlus, Expression.Constant(value), null), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal((int)(+value), f()); } private static void VerifyArithmeticUnaryPlusUInt(uint value, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.UnaryPlus(Expression.Constant(value, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal((uint)(+value), f()); } private static void VerifyArithmeticUnaryPlusLong(long value, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.UnaryPlus(Expression.Constant(value, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal((long)(+value), f()); } private static void VerifyArithmeticUnaryPlusULong(ulong value, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.UnaryPlus(Expression.Constant(value, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal((ulong)(+value), f()); } private static void VerifyArithmeticUnaryPlusFloat(float value, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.UnaryPlus(Expression.Constant(value, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); Assert.Equal((float)(+value), f()); } private static void VerifyArithmeticUnaryPlusDouble(double value, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.UnaryPlus(Expression.Constant(value, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); Assert.Equal((double)(+value), f()); } private static void VerifyArithmeticUnaryPlusDecimal(decimal value, bool useInterpreter) { Expression<Func<decimal>> e = Expression.Lambda<Func<decimal>>( Expression.UnaryPlus(Expression.Constant(value, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<decimal> f = e.Compile(useInterpreter); Assert.Equal((decimal)(+value), f()); } #endregion } }
43.858447
168
0.59292
[ "MIT" ]
2E0PGS/corefx
src/System.Linq.Expressions/tests/Unary/UnaryUnaryPlusTests.cs
9,605
C#
using System.Collections.Generic; using GRA.Controllers.ViewModel.Shared; using GRA.Domain.Model; namespace GRA.Controllers.ViewModel.MissionControl.PerformerManagement { public class AgeGroupsListViewModel : PerformerManagementPartialViewModel { public ICollection<PsAgeGroup> AgeGroups { get; set; } public PaginateViewModel PaginateModel { get; set; } public PsAgeGroup AgeGroup { get; set; } public List<Domain.Model.System> Systems { get; set; } public string BackToBackBranchesString { get; set; } } }
33.117647
77
0.730018
[ "MIT" ]
MCLD/greatreadingadventure
src/GRA.Controllers/ViewModel/MissionControl/PerformerManagement/AgeGroupsListViewModel.cs
565
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace TerribleBankInc.Models.ViewModels { public class UserProfileViewModel { public int ID { get; set; } [Required] public string Username { get; set; } public bool IsAdmin { get; set; } } }
23.9375
44
0.691906
[ "MIT" ]
ecraciun/TerribleBankInc
src/TerribleBankInc/Models/ViewModels/UserProfileViewModel.cs
385
C#
using System.Management.Automation; namespace SampleModule { [Cmdlet(VerbsCommon.Get, "Foo")] public class GetFooCmdlet : PSCmdlet { } [Cmdlet("BadVerb", "Foo")] public class GetFooCmdlet2 : PSCmdlet { } }
14.294118
41
0.633745
[ "MIT" ]
edyoung/psros
tests/SampleModule/SampleModule.cs
245
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("task5_Boxes")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("task5_Boxes")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("a2a3176f-431a-42a8-830b-d6e51b59790f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.189189
84
0.748054
[ "MIT" ]
NadiaKaradjova/SoftUni
Programming Fundamentals/RegEx - Lab/Objects and Classes - More Exercises/task5 Boxes/Properties/AssemblyInfo.cs
1,416
C#
using System; using System.Globalization; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using IdentityServer4.EntityFramework.Entities; using IdentityServer4.EntityFramework.Options; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Skoruba.IdentityServer4.Admin.BusinessLogic.Dtos.Configuration; using Skoruba.IdentityServer4.Admin.BusinessLogic.Extensions; using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Dtos.Identity; using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Extensions; using Skoruba.IdentityServer4.Admin.BusinessLogic.Services.Interfaces; using Skoruba.IdentityServer4.Admin.Controllers; using Skoruba.IdentityServer4.Admin.EntityFramework.DbContexts; using Skoruba.IdentityServer4.Admin.EntityFramework.Identity.Entities.Identity; using Skoruba.IdentityServer4.Admin.UnitTests.Mocks; using Skoruba.IdentityServer4.Admin.Helpers; using Xunit; namespace Skoruba.IdentityServer4.Admin.UnitTests.Controllers { public class ConfigurationControllerTests { [Fact] public async Task GetClients() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var newClient = await GenerateClient(dbContext); // Get controller var controller = PrepareConfigurationController(serviceProvider); // Act var result = await controller.Clients(page: 1, search: string.Empty); // Assert var viewResult = Assert.IsType<ViewResult>(result); viewResult.ViewName.Should().BeNullOrEmpty(); viewResult.ViewData.Should().NotBeNull(); var viewModel = Assert.IsType<ClientsDto>(viewResult.ViewData.Model); viewModel.Clients.Should().NotBeNull(); viewModel.Clients.Should().HaveCount(1); viewModel.Clients[0].ClientId.Should().Be(newClient.ClientId); viewModel.Clients[0].ClientName.Should().Be(newClient.ClientName); } [Fact] public async Task AddClient() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var result = await controller.Client(clientDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be(nameof(Client)); var client = await dbContext.Clients.Where(x => x.ClientId == clientDto.ClientId).SingleOrDefaultAsync(); var adddedClient = await clientService.GetClientAsync(client.Id); clientDto.ShouldBeEquivalentTo(adddedClient, opts => opts.Excluding(x => x.Id) .Excluding(x => x.AccessTokenTypes) .Excluding(x => x.ProtocolTypes) .Excluding(x => x.RefreshTokenExpirations) .Excluding(x => x.RefreshTokenUsages)); } [Fact] public async Task UpdateClient() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientToAdd = ClientMock.GenerateRandomClient(0); await dbContext.Clients.AddAsync(clientToAdd); await dbContext.SaveChangesAsync(); dbContext.Entry(clientToAdd).State = EntityState.Detached; var clientDto = ClientDtoMock.GenerateRandomClient(clientToAdd.Id); var result = await controller.Client(clientDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("Client"); var client = await dbContext.Clients.Where(x => x.ClientId == clientDto.ClientId).SingleOrDefaultAsync(); var adddedClient = await clientService.GetClientAsync(client.Id); clientDto.ShouldBeEquivalentTo(adddedClient, opts => opts.Excluding(x => x.Id) .Excluding(x => x.AccessTokenTypes) .Excluding(x => x.ProtocolTypes) .Excluding(x => x.RefreshTokenExpirations) .Excluding(x => x.RefreshTokenUsages)); } [Fact] public async Task DeleteClient() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var client = ClientMock.GenerateRandomClient(0); await dbContext.Clients.AddAsync(client); await dbContext.SaveChangesAsync(); dbContext.Entry(client).State = EntityState.Detached; var clientDto = ClientDtoMock.GenerateRandomClient(client.Id); var result = await controller.ClientDelete(clientDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("Clients"); var deletedClient = await dbContext.Clients.Where(x => x.Id == clientDto.Id).SingleOrDefaultAsync(); deletedClient.Should().BeNull(); } [Fact] public async Task AddClientClaim() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientClaim = ClientDtoMock.GenerateRandomClientClaim(0, clientId); var result = await controller.ClientClaims(clientClaim); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ClientClaims"); var clientClaimAdded = await dbContext.ClientClaims.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); var adddedClientClaim = await clientService.GetClientClaimAsync(clientClaimAdded.Id); clientClaim.ShouldBeEquivalentTo(adddedClientClaim, opts => opts.Excluding(x => x.ClientClaimId) .Excluding(x => x.ClientClaims) .Excluding(x => x.ClientName)); } [Fact] public async Task GetClientClaim() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientClaim = ClientDtoMock.GenerateRandomClientClaim(0, clientId); await clientService.AddClientClaimAsync(clientClaim); var clientClaimAdded = await dbContext.ClientClaims.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); clientClaim.ClientClaimId = clientClaimAdded.Id; var result = await controller.ClientClaims(clientId, page: 1); // Assert var viewResult = Assert.IsType<ViewResult>(result); viewResult.ViewName.Should().BeNullOrEmpty(); viewResult.ViewData.Should().NotBeNull(); var viewModel = Assert.IsType<ClientClaimsDto>(viewResult.ViewData.Model); viewModel.ClientClaims.Count.Should().Be(1); viewModel.ClientClaims[0].ShouldBeEquivalentTo(clientClaimAdded); } [Fact] public async Task DeleteClientClaim() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientClaim = ClientDtoMock.GenerateRandomClientClaim(0, clientId); await clientService.AddClientClaimAsync(clientClaim); var clientClaimAdded = await dbContext.ClientClaims.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); clientClaim.ClientClaimId = clientClaimAdded.Id; dbContext.Entry(clientClaimAdded).State = EntityState.Detached; var result = await controller.ClientClaimDelete(clientClaim); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ClientClaims"); var clientClaimDelete = await dbContext.ClientClaims.Where(x => x.Id == clientClaimAdded.Id).SingleOrDefaultAsync(); clientClaimDelete.Should().BeNull(); } [Fact] public async Task AddClientSecret() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientSecret = ClientDtoMock.GenerateRandomClientSecret(0, clientId); var result = await controller.ClientSecrets(clientSecret); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ClientSecrets"); var clientSecretAdded = await dbContext.ClientSecrets.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); var newClientSecret = await clientService.GetClientSecretAsync(clientSecretAdded.Id); clientSecret.ShouldBeEquivalentTo(newClientSecret, opts => opts.Excluding(x => x.ClientSecretId) .Excluding(x => x.ClientSecrets) .Excluding(x => x.ClientName)); } [Fact] public async Task GetClientSecret() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientSecret = ClientDtoMock.GenerateRandomClientSecret(0, clientId); await clientService.AddClientSecretAsync(clientSecret); var clientSecretAdded = await dbContext.ClientSecrets.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); clientSecret.ClientSecretId = clientSecretAdded.Id; var result = await controller.ClientSecrets(clientId, page: 1); // Assert var viewResult = Assert.IsType<ViewResult>(result); viewResult.ViewName.Should().BeNullOrEmpty(); viewResult.ViewData.Should().NotBeNull(); var viewModel = Assert.IsType<ClientSecretsDto>(viewResult.ViewData.Model); viewModel.ClientSecrets.Count.Should().Be(1); viewModel.ClientSecrets[0].ShouldBeEquivalentTo(clientSecretAdded); } [Fact] public async Task DeleteClientSecret() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientSecret = ClientDtoMock.GenerateRandomClientSecret(0, clientId); await clientService.AddClientSecretAsync(clientSecret); var clientSecretAdded = await dbContext.ClientSecrets.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); clientSecret.ClientSecretId = clientSecretAdded.Id; dbContext.Entry(clientSecretAdded).State = EntityState.Detached; var result = await controller.ClientSecretDelete(clientSecret); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ClientSecrets"); var clientSecretDelete = await dbContext.ClientSecrets.Where(x => x.Id == clientSecretAdded.Id).SingleOrDefaultAsync(); clientSecretDelete.Should().BeNull(); } [Fact] public async Task AddClientProperty() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientProperty = ClientDtoMock.GenerateRandomClientProperty(0, clientId); var result = await controller.ClientProperties(clientProperty); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ClientProperties"); var clientPropertyAdded = await dbContext.ClientProperties.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); var newClientProperty = await clientService.GetClientPropertyAsync(clientPropertyAdded.Id); clientProperty.ShouldBeEquivalentTo(newClientProperty, opts => opts.Excluding(x => x.ClientPropertyId) .Excluding(x => x.ClientProperties) .Excluding(x => x.ClientName)); } [Fact] public async Task GetClientProperty() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientProperty = ClientDtoMock.GenerateRandomClientProperty(0, clientId); await clientService.AddClientPropertyAsync(clientProperty); var clientPropertyAdded = await dbContext.ClientProperties.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); clientProperty.ClientPropertyId = clientPropertyAdded.Id; var result = await controller.ClientProperties(clientId, page: 1); // Assert var viewResult = Assert.IsType<ViewResult>(result); viewResult.ViewName.Should().BeNullOrEmpty(); viewResult.ViewData.Should().NotBeNull(); var viewModel = Assert.IsType<ClientPropertiesDto>(viewResult.ViewData.Model); viewModel.ClientProperties.Count.Should().Be(1); viewModel.ClientProperties[0].ShouldBeEquivalentTo(clientPropertyAdded); } [Fact] public async Task DeleteClientProperty() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var clientDto = ClientDtoMock.GenerateRandomClient(0); var clientId = await clientService.AddClientAsync(clientDto); var clientProperty = ClientDtoMock.GenerateRandomClientProperty(0, clientId); await clientService.AddClientPropertyAsync(clientProperty); var clientPropertyAdded = await dbContext.ClientProperties.Where(x => x.Client.Id == clientId).SingleOrDefaultAsync(); clientProperty.ClientPropertyId = clientPropertyAdded.Id; dbContext.Entry(clientPropertyAdded).State = EntityState.Detached; var result = await controller.ClientPropertyDelete(clientProperty); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ClientProperties"); var newClientProperty = await dbContext.ClientProperties.Where(x => x.Id == clientPropertyAdded.Id).SingleOrDefaultAsync(); newClientProperty.Should().BeNull(); } [Fact] public async Task AddClientModelIsNotValid() { //Get Services var serviceProvider = GetServices(); // Get controller var controller = PrepareConfigurationController(serviceProvider); //Create empty dto object var clientDto = new ClientDto(); //Setup requirements for model validation controller.ModelState.AddModelError("ClientId", "Required"); controller.ModelState.AddModelError("ClientName", "Required"); //Action var result = await controller.Client(clientDto); // Assert var viewResult = Assert.IsType<ViewResult>(result); viewResult.ViewData.ModelState.IsValid.Should().BeFalse(); } [Fact] public async Task AddIdentityResource() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var identityResourceService = serviceProvider.GetRequiredService<IIdentityResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var identityResourceDto = IdentityResourceDtoMock.GenerateRandomIdentityResource(0); var result = await controller.IdentityResource(identityResourceDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("IdentityResource"); var identityResource = await dbContext.IdentityResources.Where(x => x.Name == identityResourceDto.Name).SingleOrDefaultAsync(); var addedIdentityResource = await identityResourceService.GetIdentityResourceAsync(identityResource.Id); identityResourceDto.ShouldBeEquivalentTo(addedIdentityResource, opts => opts.Excluding(x => x.Id)); } [Fact] public async Task DeleteIdentityResource() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var identityResourceService = serviceProvider.GetRequiredService<IIdentityResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var identityResourceDto = IdentityResourceDtoMock.GenerateRandomIdentityResource(0); await identityResourceService.AddIdentityResourceAsync(identityResourceDto); var identityResourceId = await dbContext.IdentityResources.Where(x => x.Name == identityResourceDto.Name).Select(x => x.Id).SingleOrDefaultAsync(); identityResourceId.Should().NotBe(0); identityResourceDto.Id = identityResourceId; var result = await controller.IdentityResourceDelete(identityResourceDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("IdentityResources"); var identityResource = await dbContext.IdentityResources.Where(x => x.Id == identityResourceDto.Id).SingleOrDefaultAsync(); identityResource.Should().BeNull(); } [Fact] public async Task AddApiResource() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); var result = await controller.ApiResource(apiResourceDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ApiResource"); var apiResource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); var addedApiResource = await apiResourceService.GetApiResourceAsync(apiResource.Id); apiResourceDto.ShouldBeEquivalentTo(addedApiResource, opts => opts.Excluding(x => x.Id)); } [Fact] public async Task DeleteApiResource() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var apiResourceId = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).Select(x => x.Id).SingleOrDefaultAsync(); apiResourceId.Should().NotBe(0); apiResourceDto.Id = apiResourceId; var result = await controller.ApiResourceDelete(apiResourceDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ApiResources"); var apiResource = await dbContext.ApiResources.Where(x => x.Id == apiResourceDto.Id).SingleOrDefaultAsync(); apiResource.Should().BeNull(); } [Fact] public async Task AddApiScope() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var resource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); var apiScopeDto = ApiResourceDtoMock.GenerateRandomApiScope(0, resource.Id); var result = await controller.ApiScopes(apiScopeDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ApiScopes"); var apiScope = await dbContext.ApiScopes.Where(x => x.Name == apiScopeDto.Name).SingleOrDefaultAsync(); var addedApiScope = await apiResourceService.GetApiScopeAsync(resource.Id, apiScope.Id); apiScopeDto.ShouldBeEquivalentTo(addedApiScope, opts => opts.Excluding(x => x.ApiResourceId).Excluding(x => x.ResourceName).Excluding(x => x.ApiScopeId)); } [Fact] public async Task GetApiScopes() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var resource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); const int generateScopes = 5; // Add Api Scopes for (var i = 0; i < generateScopes; i++) { var apiScopeDto = ApiResourceDtoMock.GenerateRandomApiScope(0, resource.Id); await apiResourceService.AddApiScopeAsync(apiScopeDto); } var result = await controller.ApiScopes(resource.Id, 1, null); // Assert var viewResult = Assert.IsType<ViewResult>(result); viewResult.ViewName.Should().BeNullOrEmpty(); viewResult.ViewData.Should().NotBeNull(); var viewModel = Assert.IsType<ApiScopesDto>(viewResult.ViewData.Model); viewModel.Scopes.Count.Should().Be(generateScopes); } [Fact] public async Task UpdateApiScope() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var resource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); var apiScopeDto = ApiResourceDtoMock.GenerateRandomApiScope(0, resource.Id); await apiResourceService.AddApiScopeAsync(apiScopeDto); var apiScopeAdded = await dbContext.ApiScopes.Where(x => x.Name == apiScopeDto.Name).SingleOrDefaultAsync(); dbContext.Entry(apiScopeAdded).State = EntityState.Detached; apiScopeAdded.Should().NotBeNull(); var updatedApiScopeDto = ApiResourceDtoMock.GenerateRandomApiScope(apiScopeAdded.Id, resource.Id); var result = await controller.ApiScopes(updatedApiScopeDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ApiScopes"); var apiScope = await dbContext.ApiScopes.Where(x => x.Id == apiScopeAdded.Id).SingleOrDefaultAsync(); var addedApiScope = await apiResourceService.GetApiScopeAsync(resource.Id, apiScope.Id); updatedApiScopeDto.ShouldBeEquivalentTo(addedApiScope, opts => opts.Excluding(x => x.ApiResourceId) .Excluding(x => x.ResourceName) .Excluding(x => x.ApiScopeId)); } [Fact] public async Task DeleteApiScope() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var resource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); var apiScopeDto = ApiResourceDtoMock.GenerateRandomApiScope(0, resource.Id); await apiResourceService.AddApiScopeAsync(apiScopeDto); var apiScopeId = await dbContext.ApiScopes.Where(x => x.Name == apiScopeDto.Name).Select(x => x.Id).SingleOrDefaultAsync(); apiScopeId.Should().NotBe(0); apiScopeDto.ApiScopeId = apiScopeId; var result = await controller.ApiScopeDelete(apiScopeDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ApiScopes"); var apiScope = await dbContext.ApiScopes.Where(x => x.Id == apiScopeDto.ApiScopeId).SingleOrDefaultAsync(); apiScope.Should().BeNull(); } [Fact] public async Task GetApiSecrets() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var resource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); const int generateApiSecrets = 5; for (var i = 0; i < generateApiSecrets; i++) { var apiSecretsDto = ApiResourceDtoMock.GenerateRandomApiSecret(0, resource.Id); await apiResourceService.AddApiSecretAsync(apiSecretsDto); } var result = await controller.ApiSecrets(resource.Id, 1); // Assert var viewResult = Assert.IsType<ViewResult>(result); viewResult.ViewName.Should().BeNullOrEmpty(); viewResult.ViewData.Should().NotBeNull(); var viewModel = Assert.IsType<ApiSecretsDto>(viewResult.ViewData.Model); viewModel.ApiSecrets.Count.Should().Be(generateApiSecrets); } [Fact] public async Task AddApiSecret() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var resource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); var apiSecretsDto = ApiResourceDtoMock.GenerateRandomApiSecret(0, resource.Id); var result = await controller.ApiSecrets(apiSecretsDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ApiSecrets"); var apiSecret = await dbContext.ApiSecrets.Where(x => x.Value == apiSecretsDto.Value).SingleOrDefaultAsync(); var addedApiScope = await apiResourceService.GetApiSecretAsync(apiSecret.Id); apiSecretsDto.ShouldBeEquivalentTo(addedApiScope, opts => opts.Excluding(x => x.ApiResourceId).Excluding(x => x.ApiResourceName).Excluding(x => x.ApiSecretId)); } [Fact] public async Task DeleteApiSecret() { //Get Services var serviceProvider = GetServices(); var dbContext = serviceProvider.GetRequiredService<IdentityServerConfigurationDbContext>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); // Get controller var controller = PrepareConfigurationController(serviceProvider); var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0); await apiResourceService.AddApiResourceAsync(apiResourceDto); var resource = await dbContext.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync(); var apiSecretsDto = ApiResourceDtoMock.GenerateRandomApiSecret(0, resource.Id); await apiResourceService.AddApiSecretAsync(apiSecretsDto); var apiSecretId = await dbContext.ApiSecrets.Where(x => x.Value == apiSecretsDto.Value).Select(x => x.Id) .SingleOrDefaultAsync(); apiSecretId.Should().NotBe(0); apiSecretsDto.ApiSecretId = apiSecretId; var result = await controller.ApiSecretDelete(apiSecretsDto); // Assert var viewResult = Assert.IsType<RedirectToActionResult>(result); viewResult.ActionName.Should().Be("ApiSecrets"); var apiSecret = await dbContext.ApiSecrets.Where(x => x.Id == apiSecretsDto.ApiSecretId).SingleOrDefaultAsync(); apiSecret.Should().BeNull(); } private ConfigurationController PrepareConfigurationController(IServiceProvider serviceProvider) { // Arrange var identityResourceService = serviceProvider.GetRequiredService<IIdentityResourceService>(); var apiResourceService = serviceProvider.GetRequiredService<IApiResourceService>(); var clientService = serviceProvider.GetRequiredService<IClientService>(); var localizer = serviceProvider.GetRequiredService<IStringLocalizer<ConfigurationController>>(); var logger = serviceProvider.GetRequiredService<ILogger<ConfigurationController>>(); var tempDataDictionaryFactory = serviceProvider.GetRequiredService<ITempDataDictionaryFactory>(); //Get Controller var controller = new ConfigurationController(identityResourceService, apiResourceService, clientService, localizer, logger); //Setup TempData for notofication in basecontroller var httpContext = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext; var tempData = tempDataDictionaryFactory.GetTempData(httpContext); controller.TempData = tempData; return controller; } private async Task<Client> GenerateClient(IdentityServerConfigurationDbContext dbContext) { var client = ClientMock.GenerateRandomClient(id: 0); await dbContext.Clients.AddAsync(client); await dbContext.SaveChangesAsync(); return client; } private IServiceProvider GetServices() { var services = new ServiceCollection(); services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); //Entity framework var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider(); services.AddOptions(); services.AddDbContext<IdentityServerConfigurationDbContext>(b => b.UseInMemoryDatabase(Guid.NewGuid().ToString()).UseInternalServiceProvider(efServiceProvider)); //Http Context var context = new DefaultHttpContext(); services.AddSingleton<IHttpContextAccessor>(new HttpContextAccessor { HttpContext = context }); //IdentityServer4 EntityFramework configuration services.AddSingleton<ConfigurationStoreOptions>(); services.AddSingleton<OperationalStoreOptions>(); //Add Admin services services.AddMvcExceptionFilters(); services.AddAdminServices<IdentityServerConfigurationDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext>(); services.AddAdminAspNetIdentityServices<AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, UserDto<string>, string, RoleDto<string>, string, string, string, UserIdentity, UserIdentityRole, string, UserIdentityUserClaim, UserIdentityUserRole, UserIdentityUserLogin, UserIdentityRoleClaim, UserIdentityUserToken, UsersDto<UserDto<string>, string>, RolesDto<RoleDto<string>, string>, UserRolesDto<RoleDto<string>, string, string>, UserClaimsDto<string>, UserProviderDto<string>, UserProvidersDto<string>, UserChangePasswordDto<string>, RoleClaimsDto<string>, UserClaimDto<string>, RoleClaimDto<string>>(); services.AddSession(); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddViewLocalization( LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; }) .AddDataAnnotationsLocalization(); services.Configure<RequestLocalizationOptions>( opts => { var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("en") }; opts.DefaultRequestCulture = new RequestCulture("en"); opts.SupportedCultures = supportedCultures; opts.SupportedUICultures = supportedCultures; }); services.AddLogging(); return services.BuildServiceProvider(); } } }
47.779762
180
0.666251
[ "MIT" ]
StredaX/IdentityServer4.Admin
tests/Skoruba.IdentityServer4.Admin.UnitTests/Controllers/ConfigurationControllerTests.cs
40,137
C#
using System; namespace BasicsOfCSharp{ class Employee //Proper { //variables - camelCase //Declaration of variables internal string firstName, lastName, ssn; internal int Age; private decimal salary; //Properites: Smart fields to access the private variables outside the class public decimal _salary { //always set to public get{ return salary; } set{ salary=value; //value is a key word } } //Methods - Specification and Definition (body) public void GetDetails() { Console.WriteLine($"Name {firstName} {lastName}, {Age} years old, has Social Security - {ssn}. The salary is {salary}"); } //constructors in C#: special methods which is used to initialize the memory //parametereless constructor public Employee() { firstName = "Cameron"; lastName = "Coley"; ssn = "123456789"; Age = 30; salary = 8000.00M; Console.WriteLine($"Name {firstName} {lastName}, {Age} years old, has Social Security - {ssn}. The salary is {salary}"); } //parameterized constructor public Employee(string firstName, string lastName, string ssn, int Age, decimal salary) { this.firstName = firstName; this.lastName = lastName; this.ssn = ssn; this.Age = Age; this.salary = salary; Console.WriteLine($"Name {firstName} {lastName}, {Age} years old, has Social Security - {ssn}. The salary is {salary}"); } } }
32.169811
132
0.556598
[ "MIT" ]
1905-may06-dotnet/Coombs_Daniel_Project0
01-CSharp/BasicsOfCSharp/Types.cs
1,705
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection.Emit; using System.Runtime.ExceptionServices; using System.Threading; namespace System.Reflection { // Helper class to handle the IL EMIT for the generation of proxies. // Much of this code was taken directly from the Silverlight proxy generation. // Differences between this and the Silverlight version are: // 1. This version is based on DispatchProxy from NET Native and CoreCLR, not RealProxy in Silverlight ServiceModel. // There are several notable differences between them. // 2. Both DispatchProxy and RealProxy permit the caller to ask for a proxy specifying a pair of types: // the interface type to implement, and a base type. But they behave slightly differently: // - RealProxy generates a proxy type that derives from Object and *implements" all the base type's // interfaces plus all the interface type's interfaces. // - DispatchProxy generates a proxy type that *derives* from the base type and implements all // the interface type's interfaces. This is true for both the CLR version in NET Native and this // version for CoreCLR. // 3. DispatchProxy and RealProxy use different type hierarchies for the generated proxies: // - RealProxy type hierarchy is: // proxyType : proxyBaseType : object // Presumably the 'proxyBaseType' in the middle is to allow it to implement the base type's interfaces // explicitly, preventing collision for same name methods on the base and interface types. // - DispatchProxy hierarchy is: // proxyType : baseType (where baseType : DispatchProxy) // The generated DispatchProxy proxy type does not need to generate implementation methods // for the base type's interfaces, because the base type already must have implemented them. // 4. RealProxy required a proxy instance to hold a backpointer to the RealProxy instance to mirror // the .NET Remoting design that required the proxy and RealProxy to be separate instances. // But the DispatchProxy design encourages the proxy type to *be* an DispatchProxy. Therefore, // the proxy's 'this' becomes the equivalent of RealProxy's backpointer to RealProxy, so we were // able to remove an extraneous field and ctor arg from the DispatchProxy proxies. // internal static class DispatchProxyGenerator { // Generated proxies have a private MethodInfo[] field that generated methods use to get the corresponding MethodInfo. // It is the first field in the class and the first ctor parameter. private const int MethodInfosFieldAndCtorParameterIndex = 0; // Proxies are requested for a pair of types: base type and interface type. // The generated proxy will subclass the given base type and implement the interface type. // We maintain a cache keyed by 'base type' containing a dictionary keyed by interface type, // containing the generated proxy type for that pair. There are likely to be few (maybe only 1) // base type in use for many interface types. // Note: this differs from Silverlight's RealProxy implementation which keys strictly off the // interface type. But this does not allow the same interface type to be used with more than a // single base type. The implementation here permits multiple interface types to be used with // multiple base types, and the generated proxy types will be unique. // This cache of generated types grows unbounded, one element per unique T/ProxyT pair. // This approach is used to prevent regenerating identical proxy types for identical T/Proxy pairs, // which would ultimately be a more expensive leak. // Proxy instances are not cached. Their lifetime is entirely owned by the caller of DispatchProxy.Create. private static readonly Dictionary< Type, Dictionary<Type, GeneratedTypeInfo> > s_baseTypeAndInterfaceToGeneratedProxyType = new Dictionary< Type, Dictionary<Type, GeneratedTypeInfo> >(); private static readonly ProxyAssembly s_proxyAssembly = new ProxyAssembly(); private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(DispatchProxy).GetMethod( "Invoke", BindingFlags.NonPublic | BindingFlags.Instance )!; private static readonly MethodInfo s_getTypeFromHandleMethod = typeof(Type).GetRuntimeMethod( "GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) } )!; private static readonly MethodInfo s_makeGenericMethodMethod = typeof(MethodInfo).GetMethod( "MakeGenericMethod", new Type[] { typeof(Type[]) } )!; // Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType' internal static object CreateProxyInstance( [DynamicallyAccessedMembers( DynamicallyAccessedMemberTypes.PublicParameterlessConstructor )] Type baseType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType ) { Debug.Assert(baseType != null); Debug.Assert(interfaceType != null); GeneratedTypeInfo proxiedType = GetProxyType(baseType, interfaceType); return Activator.CreateInstance( proxiedType.GeneratedType, new object[] { proxiedType.MethodInfos } )!; } private static GeneratedTypeInfo GetProxyType( [DynamicallyAccessedMembers( DynamicallyAccessedMemberTypes.PublicParameterlessConstructor )] Type baseType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType ) { lock (s_baseTypeAndInterfaceToGeneratedProxyType) { if ( !s_baseTypeAndInterfaceToGeneratedProxyType.TryGetValue( baseType, out Dictionary<Type, GeneratedTypeInfo>? interfaceToProxy ) ) { interfaceToProxy = new Dictionary<Type, GeneratedTypeInfo>(); s_baseTypeAndInterfaceToGeneratedProxyType[baseType] = interfaceToProxy; } if ( !interfaceToProxy.TryGetValue( interfaceType, out GeneratedTypeInfo? generatedProxy ) ) { generatedProxy = GenerateProxyType(baseType, interfaceType); interfaceToProxy[interfaceType] = generatedProxy; } return generatedProxy; } } // Unconditionally generates a new proxy type derived from 'baseType' and implements 'interfaceType' [UnconditionalSuppressMessage( "ReflectionAnalysis", "IL2062:UnrecognizedReflectionPattern", Justification = "interfaceType is annotated as preserve All members, so any Types returned from GetInterfaces should be preserved as well once https://github.com/mono/linker/issues/1731 is fixed." )] private static GeneratedTypeInfo GenerateProxyType( [DynamicallyAccessedMembers( DynamicallyAccessedMemberTypes.PublicParameterlessConstructor )] Type baseType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType ) { // Parameter validation is deferred until the point we need to create the proxy. // This prevents unnecessary overhead revalidating cached proxy types. // The interface type must be an interface, not a class if (!interfaceType.IsInterface) { // "T" is the generic parameter seen via the public contract throw new ArgumentException( SR.Format(SR.InterfaceType_Must_Be_Interface, interfaceType.FullName), "T" ); } // The base type cannot be sealed because the proxy needs to subclass it. if (baseType.IsSealed) { // "TProxy" is the generic parameter seen via the public contract throw new ArgumentException( SR.Format(SR.BaseType_Cannot_Be_Sealed, baseType.FullName), "TProxy" ); } // The base type cannot be abstract if (baseType.IsAbstract) { throw new ArgumentException( SR.Format(SR.BaseType_Cannot_Be_Abstract, baseType.FullName), "TProxy" ); } // The base type must have a public default ctor if (baseType.GetConstructor(Type.EmptyTypes) == null) { throw new ArgumentException( SR.Format(SR.BaseType_Must_Have_Default_Ctor, baseType.FullName), "TProxy" ); } // Create a type that derives from 'baseType' provided by caller ProxyBuilder pb = s_proxyAssembly.CreateProxy("generatedProxy", baseType); foreach (Type t in interfaceType.GetInterfaces()) pb.AddInterfaceImpl(t); pb.AddInterfaceImpl(interfaceType); GeneratedTypeInfo generatedProxyType = pb.CreateType(); return generatedProxyType; } private sealed class GeneratedTypeInfo { public GeneratedTypeInfo( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type generatedType, MethodInfo[] methodInfos ) { GeneratedType = generatedType; MethodInfos = methodInfos; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public Type GeneratedType { get; } public MethodInfo[] MethodInfos { get; } } private sealed class ProxyAssembly { private readonly AssemblyBuilder _ab; private readonly ModuleBuilder _mb; private int _typeId; private readonly HashSet<string?> _ignoresAccessAssemblyNames = new HashSet<string?>(); private ConstructorInfo? _ignoresAccessChecksToAttributeConstructor; public ProxyAssembly() { _ab = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("ProxyBuilder"), AssemblyBuilderAccess.Run ); _mb = _ab.DefineDynamicModule("testmod"); } // Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute. // This attribute is both defined and referenced in the dynamic assembly to // allow access to internal types in other assemblies. internal ConstructorInfo IgnoresAccessChecksAttributeConstructor { get { if (_ignoresAccessChecksToAttributeConstructor == null) { _ignoresAccessChecksToAttributeConstructor = IgnoreAccessChecksToAttributeBuilder.AddToModule(_mb); } return _ignoresAccessChecksToAttributeConstructor; } } [UnconditionalSuppressMessage( "ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "Only the parameterless ctor is referenced on proxyBaseType. Other members can be trimmed if unused." )] public ProxyBuilder CreateProxy( string name, [DynamicallyAccessedMembers( DynamicallyAccessedMemberTypes.PublicParameterlessConstructor )] Type proxyBaseType ) { int nextId = Interlocked.Increment(ref _typeId); TypeBuilder tb = _mb.DefineType( name + "_" + nextId, TypeAttributes.Public, proxyBaseType ); return new ProxyBuilder(this, tb, proxyBaseType); } // Generates an instance of the IgnoresAccessChecksToAttribute to // identify the given assembly as one which contains internal types // the dynamic assembly will need to reference. internal void GenerateInstanceOfIgnoresAccessChecksToAttribute(string assemblyName) { // Add this assembly level attribute: // [assembly: System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute(assemblyName)] ConstructorInfo attributeConstructor = IgnoresAccessChecksAttributeConstructor; CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder( attributeConstructor, new object[] { assemblyName } ); _ab.SetCustomAttribute(customAttributeBuilder); } // Ensures the type we will reference from the dynamic assembly // is visible. Non-public types need to emit an attribute that // allows access from the dynamic assembly. internal void EnsureTypeIsVisible(Type type) { if (!type.IsVisible) { string assemblyName = type.Assembly.GetName().Name!; if (!_ignoresAccessAssemblyNames.Contains(assemblyName)) { GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyName); _ignoresAccessAssemblyNames.Add(assemblyName); } } } } private sealed class ProxyBuilder { private readonly ProxyAssembly _assembly; private readonly TypeBuilder _tb; [DynamicallyAccessedMembers( DynamicallyAccessedMemberTypes.PublicParameterlessConstructor )] private readonly Type _proxyBaseType; private readonly List<FieldBuilder> _fields; private readonly List<MethodInfo> _methodInfos; internal ProxyBuilder( ProxyAssembly assembly, TypeBuilder tb, [DynamicallyAccessedMembers( DynamicallyAccessedMemberTypes.PublicParameterlessConstructor )] Type proxyBaseType ) { _assembly = assembly; _tb = tb; _proxyBaseType = proxyBaseType; _fields = new List<FieldBuilder>(); _fields.Add( tb.DefineField("_methodInfos", typeof(MethodInfo[]), FieldAttributes.Private) ); _methodInfos = new List<MethodInfo>(); _assembly.EnsureTypeIsVisible(proxyBaseType); } private void Complete() { Type[] args = new Type[_fields.Count]; for (int i = 0; i < args.Length; i++) { args[i] = _fields[i].FieldType; } ConstructorBuilder cb = _tb.DefineConstructor( MethodAttributes.Public, CallingConventions.HasThis, args ); ILGenerator il = cb.GetILGenerator(); // chained ctor call ConstructorInfo? baseCtor = _proxyBaseType.GetConstructor(Type.EmptyTypes); Debug.Assert(baseCtor != null); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseCtor!); // store all the fields for (int i = 0; i < args.Length; i++) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, i + 1); il.Emit(OpCodes.Stfld, _fields[i]); } il.Emit(OpCodes.Ret); } internal GeneratedTypeInfo CreateType() { this.Complete(); return new GeneratedTypeInfo(_tb.CreateType()!, _methodInfos.ToArray()); } internal void AddInterfaceImpl( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type iface ) { // If necessary, generate an attribute to permit visibility // to internal types. _assembly.EnsureTypeIsVisible(iface); _tb.AddInterfaceImplementation(iface); // AccessorMethods -> Metadata mappings. var propertyMap = new Dictionary<MethodInfo, PropertyAccessorInfo>( MethodInfoEqualityComparer.Instance ); foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { var ai = new PropertyAccessorInfo(pi.GetMethod, pi.SetMethod); if (pi.GetMethod != null) propertyMap[pi.GetMethod] = ai; if (pi.SetMethod != null) propertyMap[pi.SetMethod] = ai; } var eventMap = new Dictionary<MethodInfo, EventAccessorInfo>( MethodInfoEqualityComparer.Instance ); foreach (EventInfo ei in iface.GetRuntimeEvents()) { var ai = new EventAccessorInfo(ei.AddMethod, ei.RemoveMethod, ei.RaiseMethod); if (ei.AddMethod != null) eventMap[ei.AddMethod] = ai; if (ei.RemoveMethod != null) eventMap[ei.RemoveMethod] = ai; if (ei.RaiseMethod != null) eventMap[ei.RaiseMethod] = ai; } foreach (MethodInfo mi in iface.GetRuntimeMethods()) { // Skip regular/non-virtual instance methods, static methods, and methods that cannot be overriden // ("methods that cannot be overriden" includes default implementation of other interface methods). if (!mi.IsVirtual || mi.IsFinal) continue; int methodInfoIndex = _methodInfos.Count; _methodInfos.Add(mi); MethodBuilder mdb = AddMethodImpl(mi, methodInfoIndex); if (propertyMap.TryGetValue(mi, out PropertyAccessorInfo? associatedProperty)) { if ( MethodInfoEqualityComparer.Instance.Equals( associatedProperty.InterfaceGetMethod, mi ) ) associatedProperty.GetMethodBuilder = mdb; else associatedProperty.SetMethodBuilder = mdb; } if (eventMap.TryGetValue(mi, out EventAccessorInfo? associatedEvent)) { if ( MethodInfoEqualityComparer.Instance.Equals( associatedEvent.InterfaceAddMethod, mi ) ) associatedEvent.AddMethodBuilder = mdb; else if ( MethodInfoEqualityComparer.Instance.Equals( associatedEvent.InterfaceRemoveMethod, mi ) ) associatedEvent.RemoveMethodBuilder = mdb; else associatedEvent.RaiseMethodBuilder = mdb; } } foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { PropertyAccessorInfo ai = propertyMap[pi.GetMethod ?? pi.SetMethod!]; // If we didn't make an overriden accessor above, this was a static property, non-virtual property, // or a default implementation of a property of a different interface. In any case, we don't need // to redeclare it. if (ai.GetMethodBuilder == null && ai.SetMethodBuilder == null) continue; PropertyBuilder pb = _tb.DefineProperty( pi.Name, pi.Attributes, pi.PropertyType, pi.GetIndexParameters().Select(p => p.ParameterType).ToArray() ); if (ai.GetMethodBuilder != null) pb.SetGetMethod(ai.GetMethodBuilder); if (ai.SetMethodBuilder != null) pb.SetSetMethod(ai.SetMethodBuilder); } foreach (EventInfo ei in iface.GetRuntimeEvents()) { EventAccessorInfo ai = eventMap[ei.AddMethod ?? ei.RemoveMethod!]; // If we didn't make an overriden accessor above, this was a static event, non-virtual event, // or a default implementation of an event of a different interface. In any case, we don't // need to redeclare it. if ( ai.AddMethodBuilder == null && ai.RemoveMethodBuilder == null && ai.RaiseMethodBuilder == null ) continue; Debug.Assert(ei.EventHandlerType != null); EventBuilder eb = _tb.DefineEvent(ei.Name, ei.Attributes, ei.EventHandlerType!); if (ai.AddMethodBuilder != null) eb.SetAddOnMethod(ai.AddMethodBuilder); if (ai.RemoveMethodBuilder != null) eb.SetRemoveOnMethod(ai.RemoveMethodBuilder); if (ai.RaiseMethodBuilder != null) eb.SetRaiseMethod(ai.RaiseMethodBuilder); } } private MethodBuilder AddMethodImpl(MethodInfo mi, int methodInfoIndex) { ParameterInfo[] parameters = mi.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; Type[][] paramReqMods = new Type[paramTypes.Length][]; for (int i = 0; i < parameters.Length; i++) { paramTypes[i] = parameters[i].ParameterType; paramReqMods[i] = parameters[i].GetRequiredCustomModifiers(); } MethodBuilder mdb = _tb.DefineMethod( mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard, mi.ReturnType, null, null, paramTypes, paramReqMods, null ); if (mi.ContainsGenericParameters) { Type[] ts = mi.GetGenericArguments(); string[] ss = new string[ts.Length]; for (int i = 0; i < ts.Length; i++) { ss[i] = ts[i].Name; } GenericTypeParameterBuilder[] genericParameters = mdb.DefineGenericParameters( ss ); for (int i = 0; i < genericParameters.Length; i++) { genericParameters[i].SetGenericParameterAttributes( ts[i].GenericParameterAttributes ); } } ILGenerator il = mdb.GetILGenerator(); ParametersArray args = new ParametersArray(il, paramTypes); // object[] args = new object[paramCount]; il.Emit(OpCodes.Nop); GenericArray<object> argsArr = new GenericArray<object>(il, parameters.Length); for (int i = 0; i < parameters.Length; i++) { // args[i] = argi; bool isOutRef = parameters[i].IsOut && parameters[i].ParameterType.IsByRef && !parameters[i].IsIn; if (!isOutRef) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } // MethodInfo methodInfo = _methodInfos[methodInfoIndex]; LocalBuilder methodInfoLocal = il.DeclareLocal(typeof(MethodInfo)); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, _fields[MethodInfosFieldAndCtorParameterIndex]); // MethodInfo[] _methodInfos il.Emit(OpCodes.Ldc_I4, methodInfoIndex); il.Emit(OpCodes.Ldelem_Ref); il.Emit(OpCodes.Stloc, methodInfoLocal); if (mi.ContainsGenericParameters) { // methodInfo = methodInfo.MakeGenericMethod(mi.GetGenericArguments()); il.Emit(OpCodes.Ldloc, methodInfoLocal); Type[] genericTypes = mi.GetGenericArguments(); GenericArray<Type> typeArr = new GenericArray<Type>(il, genericTypes.Length); for (int i = 0; i < genericTypes.Length; ++i) { typeArr.BeginSet(i); il.Emit(OpCodes.Ldtoken, genericTypes[i]); il.Emit(OpCodes.Call, s_getTypeFromHandleMethod); typeArr.EndSet(typeof(Type)); } typeArr.Load(); il.Emit(OpCodes.Callvirt, s_makeGenericMethodMethod); il.Emit(OpCodes.Stloc, methodInfoLocal); } // object result = this.Invoke(methodInfo, args); LocalBuilder? resultLocal = mi.ReturnType != typeof(void) ? il.DeclareLocal(typeof(object)) : null; il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldloc, methodInfoLocal); argsArr.Load(); il.Emit(OpCodes.Callvirt, s_dispatchProxyInvokeMethod); if (resultLocal != null) { il.Emit(OpCodes.Stloc, resultLocal); } else { // drop the result for void methods il.Emit(OpCodes.Pop); } for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { args.BeginSet(i); argsArr.Get(i); args.EndSet(i, typeof(object)); } } if (resultLocal != null) { // return (mi.ReturnType)result; il.Emit(OpCodes.Ldloc, resultLocal); Convert(il, typeof(object), mi.ReturnType, false); } il.Emit(OpCodes.Ret); _tb.DefineMethodOverride(mdb, mi); return mdb; } // TypeCode does not exist in ProjectK or ProjectN. // This lookup method was copied from PortableLibraryThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs // but returns the integer value equivalent to its TypeCode enum. private static int GetTypeCode(Type? type) { if (type == null) return 0; // TypeCode.Empty; if (type == typeof(bool)) return 3; // TypeCode.Boolean; if (type == typeof(char)) return 4; // TypeCode.Char; if (type == typeof(sbyte)) return 5; // TypeCode.SByte; if (type == typeof(byte)) return 6; // TypeCode.Byte; if (type == typeof(short)) return 7; // TypeCode.Int16; if (type == typeof(ushort)) return 8; // TypeCode.UInt16; if (type == typeof(int)) return 9; // TypeCode.Int32; if (type == typeof(uint)) return 10; // TypeCode.UInt32; if (type == typeof(long)) return 11; // TypeCode.Int64; if (type == typeof(ulong)) return 12; // TypeCode.UInt64; if (type == typeof(float)) return 13; // TypeCode.Single; if (type == typeof(double)) return 14; // TypeCode.Double; if (type == typeof(decimal)) return 15; // TypeCode.Decimal; if (type == typeof(DateTime)) return 16; // TypeCode.DateTime; if (type == typeof(string)) return 18; // TypeCode.String; if (type.IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); return 1; // TypeCode.Object; } private static readonly OpCode[] s_convOpCodes = new OpCode[] { OpCodes.Nop, //Empty = 0, OpCodes.Nop, //Object = 1, OpCodes.Nop, //DBNull = 2, OpCodes.Conv_I1, //Boolean = 3, OpCodes.Conv_I2, //Char = 4, OpCodes.Conv_I1, //SByte = 5, OpCodes.Conv_U1, //Byte = 6, OpCodes.Conv_I2, //Int16 = 7, OpCodes.Conv_U2, //UInt16 = 8, OpCodes.Conv_I4, //Int32 = 9, OpCodes.Conv_U4, //UInt32 = 10, OpCodes.Conv_I8, //Int64 = 11, OpCodes.Conv_U8, //UInt64 = 12, OpCodes.Conv_R4, //Single = 13, OpCodes.Conv_R8, //Double = 14, OpCodes.Nop, //Decimal = 15, OpCodes.Nop, //DateTime = 16, OpCodes.Nop, //17 OpCodes.Nop, //String = 18, }; private static readonly OpCode[] s_ldindOpCodes = new OpCode[] { OpCodes.Nop, //Empty = 0, OpCodes.Nop, //Object = 1, OpCodes.Nop, //DBNull = 2, OpCodes.Ldind_I1, //Boolean = 3, OpCodes.Ldind_I2, //Char = 4, OpCodes.Ldind_I1, //SByte = 5, OpCodes.Ldind_U1, //Byte = 6, OpCodes.Ldind_I2, //Int16 = 7, OpCodes.Ldind_U2, //UInt16 = 8, OpCodes.Ldind_I4, //Int32 = 9, OpCodes.Ldind_U4, //UInt32 = 10, OpCodes.Ldind_I8, //Int64 = 11, OpCodes.Ldind_I8, //UInt64 = 12, OpCodes.Ldind_R4, //Single = 13, OpCodes.Ldind_R8, //Double = 14, OpCodes.Nop, //Decimal = 15, OpCodes.Nop, //DateTime = 16, OpCodes.Nop, //17 OpCodes.Ldind_Ref, //String = 18, }; private static readonly OpCode[] s_stindOpCodes = new OpCode[] { OpCodes.Nop, //Empty = 0, OpCodes.Nop, //Object = 1, OpCodes.Nop, //DBNull = 2, OpCodes.Stind_I1, //Boolean = 3, OpCodes.Stind_I2, //Char = 4, OpCodes.Stind_I1, //SByte = 5, OpCodes.Stind_I1, //Byte = 6, OpCodes.Stind_I2, //Int16 = 7, OpCodes.Stind_I2, //UInt16 = 8, OpCodes.Stind_I4, //Int32 = 9, OpCodes.Stind_I4, //UInt32 = 10, OpCodes.Stind_I8, //Int64 = 11, OpCodes.Stind_I8, //UInt64 = 12, OpCodes.Stind_R4, //Single = 13, OpCodes.Stind_R8, //Double = 14, OpCodes.Nop, //Decimal = 15, OpCodes.Nop, //DateTime = 16, OpCodes.Nop, //17 OpCodes.Stind_Ref, //String = 18, }; private static void Convert(ILGenerator il, Type source, Type target, bool isAddress) { Debug.Assert(!target.IsByRef); if (target == source) return; if (source.IsByRef) { Debug.Assert(!isAddress); Type argType = source.GetElementType()!; Ldind(il, argType); Convert(il, argType, target, isAddress); return; } if (target.IsValueType) { if (source.IsValueType) { OpCode opCode = s_convOpCodes[GetTypeCode(target)]; Debug.Assert(!opCode.Equals(OpCodes.Nop)); il.Emit(opCode); } else { Debug.Assert(source.IsAssignableFrom(target)); il.Emit(OpCodes.Unbox, target); if (!isAddress) Ldind(il, target); } } else if (target.IsAssignableFrom(source)) { if (source.IsValueType || source.IsGenericParameter) { if (isAddress) Ldind(il, source); il.Emit(OpCodes.Box, source); } } else { Debug.Assert( source.IsAssignableFrom(target) || target.IsInterface || source.IsInterface ); if (target.IsGenericParameter) { il.Emit(OpCodes.Unbox_Any, target); } else { il.Emit(OpCodes.Castclass, target); } } } private static void Ldind(ILGenerator il, Type type) { OpCode opCode = s_ldindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Ldobj, type); } } private static void Stind(ILGenerator il, Type type) { OpCode opCode = s_stindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Stobj, type); } } private sealed class ParametersArray { private readonly ILGenerator _il; private readonly Type[] _paramTypes; internal ParametersArray(ILGenerator il, Type[] paramTypes) { _il = il; _paramTypes = paramTypes; } internal void Get(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void EndSet(int i, Type stackType) { Debug.Assert(_paramTypes[i].IsByRef); Type argType = _paramTypes[i].GetElementType()!; Convert(_il, stackType, argType, false); Stind(_il, argType); } } private sealed class GenericArray<T> { private readonly ILGenerator _il; private readonly LocalBuilder _lb; internal GenericArray(ILGenerator il, int len) { _il = il; _lb = il.DeclareLocal(typeof(T[])); il.Emit(OpCodes.Ldc_I4, len); il.Emit(OpCodes.Newarr, typeof(T)); il.Emit(OpCodes.Stloc, _lb); } internal void Load() { _il.Emit(OpCodes.Ldloc, _lb); } internal void Get(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); _il.Emit(OpCodes.Ldelem_Ref); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); } internal void EndSet(Type stackType) { Convert(_il, stackType, typeof(T), false); _il.Emit(OpCodes.Stelem_Ref); } } private sealed class PropertyAccessorInfo { public MethodInfo? InterfaceGetMethod { get; } public MethodInfo? InterfaceSetMethod { get; } public MethodBuilder? GetMethodBuilder { get; set; } public MethodBuilder? SetMethodBuilder { get; set; } public PropertyAccessorInfo( MethodInfo? interfaceGetMethod, MethodInfo? interfaceSetMethod ) { InterfaceGetMethod = interfaceGetMethod; InterfaceSetMethod = interfaceSetMethod; } } private sealed class EventAccessorInfo { public MethodInfo? InterfaceAddMethod { get; } public MethodInfo? InterfaceRemoveMethod { get; } public MethodInfo? InterfaceRaiseMethod { get; } public MethodBuilder? AddMethodBuilder { get; set; } public MethodBuilder? RemoveMethodBuilder { get; set; } public MethodBuilder? RaiseMethodBuilder { get; set; } public EventAccessorInfo( MethodInfo? interfaceAddMethod, MethodInfo? interfaceRemoveMethod, MethodInfo? interfaceRaiseMethod ) { InterfaceAddMethod = interfaceAddMethod; InterfaceRemoveMethod = interfaceRemoveMethod; InterfaceRaiseMethod = interfaceRaiseMethod; } } private sealed class MethodInfoEqualityComparer : EqualityComparer<MethodInfo> { public static readonly MethodInfoEqualityComparer Instance = new MethodInfoEqualityComparer(); private MethodInfoEqualityComparer() { } public sealed override bool Equals(MethodInfo? left, MethodInfo? right) { if (ReferenceEquals(left, right)) return true; if (left == null) return right == null; else if (right == null) return false; // This assembly should work in netstandard1.3, // so we cannot use MemberInfo.MetadataToken here. // Therefore, it compares honestly referring ECMA-335 I.8.6.1.6 Signature Matching. if (!Equals(left.DeclaringType, right.DeclaringType)) return false; if (!Equals(left.ReturnType, right.ReturnType)) return false; if (left.CallingConvention != right.CallingConvention) return false; if (left.IsStatic != right.IsStatic) return false; if (left.Name != right.Name) return false; Type[] leftGenericParameters = left.GetGenericArguments(); Type[] rightGenericParameters = right.GetGenericArguments(); if (leftGenericParameters.Length != rightGenericParameters.Length) return false; for (int i = 0; i < leftGenericParameters.Length; i++) { if (!Equals(leftGenericParameters[i], rightGenericParameters[i])) return false; } ParameterInfo[] leftParameters = left.GetParameters(); ParameterInfo[] rightParameters = right.GetParameters(); if (leftParameters.Length != rightParameters.Length) return false; for (int i = 0; i < leftParameters.Length; i++) { if ( !Equals( leftParameters[i].ParameterType, rightParameters[i].ParameterType ) ) return false; } return true; } public sealed override int GetHashCode(MethodInfo obj) { if (obj == null) return 0; Debug.Assert(obj.DeclaringType != null); int hashCode = obj.DeclaringType!.GetHashCode(); hashCode ^= obj.Name.GetHashCode(); foreach (ParameterInfo parameter in obj.GetParameters()) { hashCode ^= parameter.ParameterType.GetHashCode(); } return hashCode; } } } } }
41.608779
208
0.504862
[ "MIT" ]
belav/runtime
src/libraries/System.Reflection.DispatchProxy/src/System/Reflection/DispatchProxyGenerator.cs
43,606
C#
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator}) // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Commvault.Powershell.Cmdlets { using static Commvault.Powershell.Runtime.Extensions; /// <summary>Get All Resource Pools</summary> /// <remarks> /// [OpenAPI] GetResourcePools=>GET:"/V4/ResourcePool" /// </remarks> [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"ResourcePool_Get")] [global::System.Management.Automation.OutputType(typeof(Commvault.Powershell.Models.IResourcePoolSummary))] [global::Commvault.Powershell.Description(@"Get All Resource Pools")] [global::Commvault.Powershell.Generated] public partial class GetResourcePool_Get : global::System.Management.Automation.PSCmdlet, Commvault.Powershell.Runtime.IEventListener { /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Commvault.Powershell.Category(global::Commvault.Powershell.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Commvault.Powershell.CommvaultPowerShell Client => Commvault.Powershell.Module.Instance.ClientAPI; /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Commvault.Powershell.Category(global::Commvault.Powershell.ParameterCategory.Runtime)] public Commvault.Powershell.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Commvault.Powershell.Category(global::Commvault.Powershell.ParameterCategory.Runtime)] public Commvault.Powershell.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Commvault.Powershell.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Commvault.Powershell.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] [global::Commvault.Powershell.Category(global::Commvault.Powershell.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter PassThru { get; set; } /// <summary> /// The instance of the <see cref="Commvault.Powershell.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Commvault.Powershell.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Commvault.Powershell.Category(global::Commvault.Powershell.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Commvault.Powershell.Category(global::Commvault.Powershell.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Commvault.Powershell.Category(global::Commvault.Powershell.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary> /// <c>overrideOnNotFound</c> will be called before the regular onNotFound has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="returnNow">/// Determines if the rest of the onNotFound method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnNotFound(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Commvault.Powershell.Models.IResourcePoolListResponse" /> from /// the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Commvault.Powershell.Models.IResourcePoolListResponse> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Commvault.Powershell.Runtime.AttachDebugger.Break(); } ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary> /// Intializes a new instance of the <see cref="GetResourcePool_Get" /> cmdlet class. /// </summary> public GetResourcePool_Get() { } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Commvault.Powershell.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Commvault.Powershell.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Commvault.Powershell.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Commvault.Powershell.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Commvault.Powershell.Runtime.Events.Information: { var data = messageData(); WriteInformation(data, new[] { data.Message }); return ; } case Commvault.Powershell.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Commvault.Powershell.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } } await Commvault.Powershell.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Commvault.Powershell.Runtime.IEventListener)this).Signal(i,t,()=> Commvault.Powershell.Runtime.EventDataConverter.ConvertFrom( m() ) as Commvault.Powershell.Runtime.EventData ), InvocationInformation, this.ParameterSetName, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } try { // work using( var asyncCommandRuntime = new Commvault.Powershell.Runtime.PowerShell.AsyncCommandRuntime(this, ((Commvault.Powershell.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Commvault.Powershell.Runtime.IEventListener)this).Token); } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletGetPipeline); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Commvault.Powershell.Module.Instance.CreatePipeline(InvocationInformation, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Commvault.Powershell.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Commvault.Powershell.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletBeforeAPICall); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.GetResourcePools(onOk, onNotFound, this, Pipeline); await ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletAfterAPICall); if( ((Commvault.Powershell.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Commvault.Powershell.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Commvault.Powershell.Runtime.IEventListener)this).Signal(Commvault.Powershell.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Commvault.Powershell.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary>a delegate that is called when the remote service returns 404 (NotFound).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onNotFound(global::System.Net.Http.HttpResponseMessage responseMessage) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnNotFound(responseMessage, ref _returnNow); // if overrideOnNotFound has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onNotFound - response for 404 / if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) { WriteObject(true); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Commvault.Powershell.Models.IResourcePoolListResponse" /> from /// the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Commvault.Powershell.Models.IResourcePoolListResponse> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // response should be returning an array of some kind. +Pageable // nested-array / resourcePools / <none> WriteObject((await response).ResourcePools, true); } } } }
64.802508
334
0.657169
[ "MIT" ]
Commvault/CVPowershellSDKV2
generated/cmdlets/GetResourcePool_Get.cs
20,672
C#
#pragma checksum "..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "9103CDEAA88B4F4EDA85E43B8B3514D2FD680502" //------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using sdPck; namespace sdPck { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; #line 5 "..\..\App.xaml" this.Startup += new System.Windows.StartupEventHandler(this.Application_Startup); #line default #line hidden #line 5 "..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden System.Uri resourceLocater = new System.Uri("/sdPck_china;component/app.xaml", System.UriKind.Relative); #line 1 "..\..\App.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public static void Main() { sdPck.App app = new sdPck.App(); app.InitializeComponent(); app.Run(); } } }
32.333333
118
0.590722
[ "Apache-2.0" ]
Kn1fe/sdPck_china
sdPck/obj/Debug/App.g.i.cs
3,046
C#
namespace Uania.Tools.Models.Wrapper { public class RespWrapper { public int Code { get; set; } public string? Message { get; set; } public RespWrapper() { } public RespWrapper(int code, string message) { (Code, Message) = (code, message); } } public class RespWrapper<T> : RespWrapper where T : class { public RespWrapper() { } public RespWrapper(int code, string message) : base(code, message) { } public T? Data { get; set; } } public class RespListWrapper<T> : RespWrapper where T : class { public List<T>? Data { get; set; } } public class RespPaginationWrapper<T> : RespListWrapper<T> where T : class { public Common.Paginatioin? Paginatioin { get; set; } } }
21.487805
78
0.53916
[ "MIT" ]
uania/tools
src/Uania.Tools.Models/Wrapper/RespWrapper.cs
881
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; public class EventData { private string EventIdKey = "EventId"; public Dictionary<string, object> Data; public EventData(string eventId) { Data = new Dictionary<string, object>(); Data[EventIdKey] = eventId; } public object this[string key] { get { return Data[key]; } set { Data[key] = value; } } public void Log() { string logStr = "Event: " + Data[EventIdKey] + '('; int keyIndex = 0; foreach (var kvp in Data) { keyIndex++; if (kvp.Key != EventIdKey) { logStr += kvp.Key + ":" + kvp.Value; if (keyIndex < Data.Count) logStr += " "; } } logStr += ")"; Debug.Log(logStr); } }
19.026316
53
0.621024
[ "MIT" ]
Enter-your-name-studio/HackgamesMobile
Mutant/Assets/Thirdparty/GameTemplate/Scripts/Singleton/EventManager/EventData.cs
725
C#
namespace _09_StackFibonacci { using System; using System.Collections.Generic; class StartUp { static void Main() { var numberToSearch = int.Parse(Console.ReadLine()); var allNumbers = new Stack<long>(); allNumbers.Push(0); allNumbers.Push(1); for (int i = 1; i < numberToSearch; i++) { var lastNumber = allNumbers.Pop(); var oneBeforeLastNumber = allNumbers.Peek(); var numberToAdd = lastNumber + oneBeforeLastNumber; allNumbers.Push(lastNumber); allNumbers.Push(numberToAdd); } Console.WriteLine(allNumbers.Peek()); } } }
25.827586
67
0.528705
[ "MIT" ]
MrPIvanov/SoftUni
04-Csharp Advanced/04-EXERCISE STACKS & QUEUES/04-StacksAndQueuesExercise/09-StackFibonacci/StartUp.cs
751
C#
using Microsoft.Extensions.Configuration; using SPID.AspNetCore.Authentication.Helpers; using SPID.AspNetCore.Authentication.Models; using System.Linq; using System.Security.Cryptography.X509Certificates; namespace SPID.AspNetCore.Authentication.Helpers { static class OptionsHelper { internal static SpidConfiguration CreateFromConfiguration(IConfiguration configuration) { var section = configuration.GetSection("Spid"); var options = new SpidConfiguration(); options.AddIdentityProviders(section .GetSection("Providers") .GetChildren() .ToList() .Select(x => new IdentityProvider { Method = x.GetValue<RequestMethod>("Method"), Name = x.GetValue<string>("Name"), OrganizationDisplayName = x.GetValue<string>("OrganizationDisplayName"), OrganizationLogoUrl = x.GetValue<string>("OrganizationLogoUrl"), OrganizationName = x.GetValue<string>("OrganizationName"), OrganizationUrl = x.GetValue<string>("OrganizationUrl"), OrganizationUrlMetadata = x.GetValue<string>("OrganizationUrlMetadata"), ProviderType = x.GetValue<ProviderType>("Type"), SingleSignOnServiceUrl = x.GetValue<string>("SingleSignOnServiceUrl"), SingleSignOutServiceUrl = x.GetValue<string>("SingleSignOutServiceUrl"), SubjectNameIdRemoveText = x.GetValue<string>("SubjectNameIdRemoveText"), SecurityLevel = x.GetValue<int?>("SecurityLevel") ?? 2, })); options.IsStagingValidatorEnabled = section.GetValue<bool?>("IsStagingValidatorEnabled") ?? false; options.IsLocalValidatorEnabled = section.GetValue<bool?>("IsLocalValidatorEnabled") ?? false; options.AllowUnsolicitedLogins = section.GetValue<bool?>("AllowUnsolicitedLogins") ?? false; options.AssertionConsumerServiceIndex = section.GetValue<ushort?>("AssertionConsumerServiceIndex") ?? 0; options.AttributeConsumingServiceIndex = section.GetValue<ushort?>("AttributeConsumingServiceIndex") ?? 0; options.CallbackPath = section.GetValue<string>("CallbackPath"); options.EntityId = section.GetValue<string>("EntityId"); options.RemoteSignOutPath = section.GetValue<string>("RemoteSignOutPath"); options.SignOutScheme = section.GetValue<string>("SignOutScheme"); options.UseTokenLifetime = section.GetValue<bool?>("UseTokenLifetime") ?? false; options.SkipUnrecognizedRequests = section.GetValue<bool?>("SkipUnrecognizedRequests") ?? true; options.CacheIdpMetadata = section.GetValue<bool?>("CacheIdpMetadata") ?? false; options.SecurityLevel = section.GetValue<int?>("SecurityLevel") ?? 2; var certificateSection = section.GetSection("Certificate"); if (certificateSection != null) { var certificateSource = certificateSection.GetValue<string>("Source"); if (certificateSource == "Store") { var storeConfiguration = certificateSection.GetSection("Store"); var location = storeConfiguration.GetValue<StoreLocation>("Location"); var name = storeConfiguration.GetValue<StoreName>("Name"); var findType = storeConfiguration.GetValue<X509FindType>("FindType"); var findValue = storeConfiguration.GetValue<string>("FindValue"); var validOnly = storeConfiguration.GetValue<bool>("validOnly"); options.Certificate = X509Helpers.GetCertificateFromStore( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, findValue, validOnly: false); } else if (certificateSource == "File") { var storeConfiguration = certificateSection.GetSection("File"); var path = storeConfiguration.GetValue<string>("Path"); var password = storeConfiguration.GetValue<string>("Password"); options.Certificate = X509Helpers.GetCertificateFromFile(path, password); } else if(certificateSource == "Raw") { var storeConfiguration = certificateSection.GetSection("Raw"); var certificate = storeConfiguration.GetValue<string>("Certificate"); var key = storeConfiguration.GetValue<string>("Password"); options.Certificate = X509Helpers.GetCertificateFromStrings(certificate, key); } } return options; } internal static void LoadFromConfiguration(SpidConfiguration options, IConfiguration configuration) { var createdOptions = CreateFromConfiguration(configuration); options.AddIdentityProviders(createdOptions.IdentityProviders); options.AllowUnsolicitedLogins = createdOptions.AllowUnsolicitedLogins; options.AssertionConsumerServiceIndex = createdOptions.AssertionConsumerServiceIndex; options.AttributeConsumingServiceIndex = createdOptions.AttributeConsumingServiceIndex; options.CallbackPath = createdOptions.CallbackPath; options.Certificate = createdOptions.Certificate; options.EntityId = createdOptions.EntityId; options.IsLocalValidatorEnabled = createdOptions.IsLocalValidatorEnabled; options.IsStagingValidatorEnabled = createdOptions.IsStagingValidatorEnabled; options.RemoteSignOutPath = createdOptions.RemoteSignOutPath; options.SignOutScheme = createdOptions.SignOutScheme; options.SkipUnrecognizedRequests = createdOptions.SkipUnrecognizedRequests; options.UseTokenLifetime = createdOptions.UseTokenLifetime; } } }
60.883495
118
0.633551
[ "MIT" ]
Magicianred/spid-aspnetcore
SPID.AspNetCore.Authentication/SPID.AspNetCore.Authentication/Helpers/OptionsHelper.cs
6,273
C#
using System.Collections.Generic; using System.Linq; namespace CodingInterview.ArraysAndStrings { /// <summary> /// Given two strings, write a method to decide if one is a permutation of the other. /// </summary> public static class CheckPermutation { public static bool Run(string one, string two) { if (one.Length != two.Length) return false; var oneSorted = one.OrderBy(x => x).ToList(); var twoSorted = two.OrderBy(x => x).ToList(); var first = string.Join("", oneSorted); var second = string.Join("", twoSorted); return first.Equals(second); } public static bool RunWithoutSort(string one, string two) { if (one.Length != two.Length) return false; var letters = new Dictionary<char, int>(); foreach (var character in one) { if (letters.ContainsKey(character)) letters[character]++; else letters.Add(character, 1); } foreach (var character in two) { if (letters.ContainsKey(character)) letters[character]--; else return false; if (letters[character] < 0) return false; } return letters.Values.All(x => x == 0); } } }
27.418182
89
0.492042
[ "MIT" ]
mmrauta/CondigInterview
CodingInterview/CodingInterview/ArraysAndStrings/CheckPermutation.cs
1,510
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/imm.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="CANDIDATELIST" /> struct.</summary> public static unsafe partial class CANDIDATELISTTests { /// <summary>Validates that the <see cref="CANDIDATELIST" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CANDIDATELIST>(), Is.EqualTo(sizeof(CANDIDATELIST))); } /// <summary>Validates that the <see cref="CANDIDATELIST" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CANDIDATELIST).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CANDIDATELIST" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(CANDIDATELIST), Is.EqualTo(28)); } }
36.428571
145
0.710588
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/imm/CANDIDATELISTTests.cs
1,277
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityType.cs.tt namespace Microsoft.Graph.TermStore { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Store. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class Store : Microsoft.Graph.Entity { ///<summary> /// The Store constructor ///</summary> public Store() { this.ODataType = "microsoft.graph.termStore.store"; } /// <summary> /// Gets or sets default language tag. /// Default language of the term store. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "defaultLanguageTag", Required = Newtonsoft.Json.Required.Default)] public string DefaultLanguageTag { get; set; } /// <summary> /// Gets or sets language tags. /// List of languages for the term store. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "languageTags", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<string> LanguageTags { get; set; } /// <summary> /// Gets or sets groups. /// Collection of all groups available in the term store. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "groups", Required = Newtonsoft.Json.Required.Default)] public IStoreGroupsCollectionPage Groups { get; set; } /// <summary> /// Gets or sets sets. /// Collection of all sets available in the term store. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "sets", Required = Newtonsoft.Json.Required.Default)] public IStoreSetsCollectionPage Sets { get; set; } } }
37.59375
153
0.60266
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/termstore/model/Store.cs
2,406
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://www.apache.org/licenses/LICENSE-2.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. */ namespace Amazon.QLDB.Driver.IntegrationTests { using Amazon.QLDBSession; using Amazon.QLDBSession.Model; using Amazon.IonDotnet.Builders; using Amazon.IonDotnet.Tree; using Amazon.IonDotnet.Tree.Impl; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using Amazon.QLDB.Driver.Serialization; [TestClass] public class StatementExecutionTests { private static readonly IValueFactory ValueFactory = new ValueFactory(); private static AmazonQLDBSessionConfig amazonQldbSessionConfig; private static IntegrationTestBase integrationTestBase; private static QldbDriver qldbDriver; [ClassInitialize] public static void SetUp(TestContext context) { // Get AWS configuration properties from .runsettings file. string region = context.Properties["region"].ToString(); const string ledgerName = "DotnetStatementExecution"; amazonQldbSessionConfig = IntegrationTestBase.CreateAmazonQLDBSessionConfig(region); integrationTestBase = new IntegrationTestBase(ledgerName, region); integrationTestBase.RunForceDeleteLedger(); integrationTestBase.RunCreateLedger(); qldbDriver = integrationTestBase.CreateDriver(amazonQldbSessionConfig, new ObjectSerializer()); // Create table. var query = $"CREATE TABLE {Constants.TableName}"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); var result = qldbDriver.ListTableNames(); foreach (var row in result) { Assert.AreEqual(Constants.TableName, row); } } [ClassCleanup] public static void ClassCleanup() { qldbDriver.Dispose(); integrationTestBase.RunForceDeleteLedger(); } [TestCleanup] public void TestCleanup() { // Delete all documents in table. qldbDriver.Execute(txn => txn.Execute($"DELETE FROM {Constants.TableName}")); } [TestMethod] public void Execute_DropExistingTable_TableDropped() { // Given. var create_table_query = $"CREATE TABLE {Constants.CreateTableName}"; var create_table_count = qldbDriver.Execute(txn => { var result = txn.Execute(create_table_query); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, create_table_count); // Execute ListTableNames() to ensure table is created. var result = qldbDriver.ListTableNames(); var tables = new List<string>(); foreach (var row in result) { tables.Add(row); } Assert.IsTrue(tables.Contains(Constants.CreateTableName)); // When. var drop_table_query = $"DROP TABLE {Constants.CreateTableName}"; var drop_table_count = qldbDriver.Execute(txn => { var result = txn.Execute(drop_table_query); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, drop_table_count); // Then. tables.Clear(); var updated_tables_result = qldbDriver.ListTableNames(); foreach (var row in updated_tables_result) { tables.Add(row); } Assert.IsFalse(tables.Contains(Constants.CreateTableName)); } [TestMethod] public void Execute_ListTables_ReturnsListOfTables() { // When. var result = qldbDriver.ListTableNames(); // Then. int count = 0; foreach (var row in result) { count++; Assert.AreEqual(Constants.TableName, row); } Assert.AreEqual(1, count); } [TestMethod] [ExpectedException(typeof(BadRequestException))] public void Execute_CreateTableThatAlreadyExist_ThrowBadRequestException() { // Given. var query = $"CREATE TABLE {Constants.TableName}"; // When. qldbDriver.Execute(txn => txn.Execute(query)); } [TestMethod] public void Execute_CreateIndex_IndexIsCreated() { // Given. var query = $"CREATE INDEX on {Constants.TableName} ({Constants.IndexAttribute})"; // When. var count = qldbDriver.Execute(txn => { var result = txn.Execute(query); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); // Then. var search_query = $@"SELECT VALUE indexes[0] FROM information_schema.user_tables WHERE status = 'ACTIVE' AND name = '{Constants.TableName}'"; var indexColumn = qldbDriver.Execute(txn => { var result = txn.Execute(search_query); // Extract the index name by querying the information_schema. /* This gives: { expr: "[MyColumn]" } */ var indexColumn = ""; foreach (var row in result) { indexColumn = row.GetField("expr").StringValue; } return indexColumn; }); Assert.AreEqual("[" + Constants.IndexAttribute + "]", indexColumn); } [TestMethod] public void Execute_QueryTableThatHasNoRecords_ReturnsEmptyResult() { // Given. var query = $"SELECT * FROM {Constants.TableName}"; // When. int resultSetSize = qldbDriver.Execute(txn => { var result = txn.Execute(query); int count = 0; foreach (var row in result) { count++; } return count; }); // Then. Assert.AreEqual(0, resultSetSize); } [TestMethod] public void Execute_InsertDocument_DocumentIsInserted() { // Given. // Create Ion struct to insert. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.SingleDocumentValue)); // When. var query = $"INSERT INTO {Constants.TableName} ?"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); // Then. var searchQuery = $@"SELECT VALUE {Constants.ColumnName} FROM {Constants.TableName} WHERE {Constants.ColumnName} = '{Constants.SingleDocumentValue}'"; var value = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); var value = ""; foreach (var row in result) { value = row.StringValue; } return value; }); Assert.AreEqual(Constants.SingleDocumentValue, value); } [TestMethod] public void Execute_InsertDocument_UsingObjectSerialization() { ParameterObject testObject = new ParameterObject(); var query = $"INSERT INTO {Constants.TableName} ?"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(txn.Query<ResultObject>(query, testObject)); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); var searchQuery = $"SELECT * FROM {Constants.TableName}"; var searchResult = qldbDriver.Execute(txn => { var result = txn.Execute(txn.Query<ParameterObject>(searchQuery)); ParameterObject value = null; foreach (var row in result) { value = row; } return value; }); Assert.AreEqual(testObject.ToString(), searchResult.ToString()); } [TestMethod] public void Execute_InsertDocumentWithMultipleFields_DocumentIsInserted() { // Given. // Create Ion struct to insert. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.SingleDocumentValue)); ionStruct.SetField(Constants.SecondColumnName, ValueFactory.NewString(Constants.SingleDocumentValue)); // When. var query = $"INSERT INTO {Constants.TableName} ?"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); // Then. var searchQuery = $@"SELECT {Constants.ColumnName}, {Constants.SecondColumnName} FROM {Constants.TableName} WHERE {Constants.ColumnName} = '{Constants.SingleDocumentValue}' AND {Constants.SecondColumnName} = '{Constants.SingleDocumentValue}'"; IIonValue value = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); IIonValue value = null; foreach (var row in result) { value = row; } return value; }); var ionReader = IonReaderBuilder.Build(value); ionReader.MoveNext(); ionReader.StepIn(); ionReader.MoveNext(); Assert.AreEqual(Constants.ColumnName, ionReader.CurrentFieldName); Assert.AreEqual(Constants.SingleDocumentValue, ionReader.StringValue()); ionReader.MoveNext(); Assert.AreEqual(Constants.SecondColumnName, ionReader.CurrentFieldName); Assert.AreEqual(Constants.SingleDocumentValue, ionReader.StringValue()); } [TestMethod] public void Execute_QuerySingleField_ReturnsSingleField() { // Given. // Create Ion struct to insert. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.SingleDocumentValue)); var query = $"INSERT INTO {Constants.TableName} ?"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); // When. var searchQuery = $@"SELECT VALUE {Constants.ColumnName} FROM {Constants.TableName} WHERE {Constants.ColumnName} = '{Constants.SingleDocumentValue}'"; var value = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); var value = ""; foreach (var row in result) { value = row.StringValue; } return value; }); // Then. Assert.AreEqual(Constants.SingleDocumentValue, value); } [TestMethod] public void Execute_QueryTableEnclosedInQuotes_ReturnsResult() { // Given. // Create Ion struct to insert. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.SingleDocumentValue)); var query = $"INSERT INTO {Constants.TableName} ?"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); // When. var searchQuery = $@"SELECT VALUE {Constants.ColumnName} FROM ""{Constants.TableName}"" WHERE {Constants.ColumnName} = '{Constants.SingleDocumentValue}'"; var value = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); var value = ""; foreach (var row in result) { value = row.StringValue; } return value; }); // Then. Assert.AreEqual(Constants.SingleDocumentValue, value); } [TestMethod] public void Execute_InsertMultipleDocuments_DocumentsInserted() { IIonValue ionString1 = ValueFactory.NewString(Constants.MultipleDocumentValue1); IIonValue ionString2 = ValueFactory.NewString(Constants.MultipleDocumentValue2); // Given. // Create Ion structs to insert. IIonValue ionStruct1 = ValueFactory.NewEmptyStruct(); ionStruct1.SetField(Constants.ColumnName, ionString1); IIonValue ionStruct2 = ValueFactory.NewEmptyStruct(); ionStruct2.SetField(Constants.ColumnName, ionString2); List<IIonValue> parameters = new List<IIonValue>() { ionStruct1, ionStruct2 }; // When. var query = $"INSERT INTO {Constants.TableName} <<?,?>>"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query, parameters); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(2, count); // Then. var searchQuery = $@"SELECT VALUE {Constants.ColumnName} FROM {Constants.TableName} WHERE {Constants.ColumnName} IN (?,?)"; var values = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery, ionString1, ionString2); var values = new List<String>(); foreach (var row in result) { values.Add(row.StringValue); } return values; }); Assert.IsTrue(values.Contains(Constants.MultipleDocumentValue1)); Assert.IsTrue(values.Contains(Constants.MultipleDocumentValue2)); } [TestMethod] public void Execute_DeleteSingleDocument_DocumentIsDeleted() { // Given. // Create Ion struct to insert. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.SingleDocumentValue)); var query = $"INSERT INTO {Constants.TableName} ?"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); // When. var deleteQuery = $@"DELETE FROM { Constants.TableName} WHERE {Constants.ColumnName} = '{Constants.SingleDocumentValue}'"; var deletedCount = qldbDriver.Execute(txn => { var result = txn.Execute(deleteQuery); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, deletedCount); // Then. var searchQuery = $"SELECT COUNT(*) FROM {Constants.TableName}"; var searchCount = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); int count = -1; foreach (var row in result) { // This gives: // { // _1: 1 // } IIonValue ionValue = row.GetField("_1"); count = ((IIonInt)ionValue).IntValue; } return count; }); Assert.AreEqual(0, searchCount); } [TestMethod] public void Execute_DeleteAllDocuments_DocumentsAreDeleted() { // Given. // Create Ion structs to insert. IIonValue ionStruct1 = ValueFactory.NewEmptyStruct(); ionStruct1.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.MultipleDocumentValue1)); IIonValue ionStruct2 = ValueFactory.NewEmptyStruct(); ionStruct2.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.MultipleDocumentValue2)); List<IIonValue> parameters = new List<IIonValue>() { ionStruct1, ionStruct2 }; var query = $"INSERT INTO {Constants.TableName} <<?,?>>"; var count = qldbDriver.Execute(txn => { var result = txn.Execute(query, parameters); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(2, count); // When. var deleteQuery = $"DELETE FROM { Constants.TableName}"; var deleteCount = qldbDriver.Execute(txn => { var result = txn.Execute(deleteQuery); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(2, deleteCount); // Then. var searchQuery = $"SELECT COUNT(*) FROM {Constants.TableName}"; var searchCount = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); int count = -1; foreach (var row in result) { // This gives: // { // _1: 1 // } IIonValue ionValue = row.GetField("_1"); count = ((IIonInt)ionValue).IntValue; } return count; }); Assert.AreEqual(0, searchCount); } [TestMethod] [ExpectedException(typeof(OccConflictException))] public void Execute_UpdateSameRecordAtSameTime_ThrowsOccException() { // Create a driver that does not retry OCC errors QldbDriver driver = integrationTestBase.CreateDriver(amazonQldbSessionConfig, default, default); // Insert document. // Create Ion struct with int value 0 to insert. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewInt(0)); var query = $"INSERT INTO {Constants.TableName} ?"; var count = driver.Execute(txn => { var result = txn.Execute(query, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, count); string selectQuery = $"SELECT VALUE {Constants.ColumnName} FROM {Constants.TableName}"; string updateQuery = $"UPDATE {Constants.TableName} SET {Constants.ColumnName} = ?"; // For testing purposes only. Forcefully causes an OCC conflict to occur. // Do not invoke QldbDriver.Execute within the lambda function under normal circumstances. driver.Execute(txn => { // Query table. var result = txn.Execute(selectQuery); var currentValue = 0; foreach (var row in result) { currentValue = row.IntValue; } driver.Execute(txn => { // Update document. var ionValue = ValueFactory.NewInt(currentValue + 5); txn.Execute(updateQuery, ionValue); }, RetryPolicy.Builder().WithMaxRetries(0).Build()); }, RetryPolicy.Builder().WithMaxRetries(0).Build()); } [TestMethod] [CreateIonValues] public void Execute_InsertAndReadIonTypes_IonTypesAreInsertedAndRead(IIonValue ionValue) { // Given. // Create Ion struct to be inserted. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ionValue); var query = $"INSERT INTO {Constants.TableName} ?"; var insertCount = qldbDriver.Execute(txn => { var result = txn.Execute(query, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, insertCount); // When. IIonValue searchResult; if (ionValue.IsNull) { var searchQuery = $@"SELECT VALUE { Constants.ColumnName } FROM { Constants.TableName } WHERE { Constants.ColumnName } IS NULL"; searchResult = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); IIonValue ionVal = null; foreach (var row in result) { ionVal = row; } return ionVal; }); } else { var searchQuery = $@"SELECT VALUE { Constants.ColumnName } FROM { Constants.TableName } WHERE { Constants.ColumnName } = ?"; searchResult = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery, ionValue); IIonValue ionVal = null; foreach (var row in result) { ionVal = row; } return ionVal; }); } // Then. if (searchResult.Type() != ionValue.Type()) { Assert.Fail($"The queried value type, { searchResult.Type().ToString() }," + $"does not match { ionValue.Type().ToString() }."); } } [TestMethod] [CreateIonValues] public void Execute_UpdateIonTypes_IonTypesAreUpdated(IIonValue ionValue) { // Given. // Create Ion struct to be inserted. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewNull()); // Insert first record which will be subsequently updated. var insertQuery = $"INSERT INTO {Constants.TableName} ?"; var insertCount = qldbDriver.Execute(txn => { var result = txn.Execute(insertQuery, ionStruct); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, insertCount); // When. var updateQuery = $"UPDATE { Constants.TableName } SET { Constants.ColumnName } = ?"; var updateCount = qldbDriver.Execute(txn => { var result = txn.Execute(updateQuery, ionValue); var count = 0; foreach (var row in result) { count++; } return count; }); Assert.AreEqual(1, updateCount); // Then. IIonValue searchResult; if (ionValue.IsNull) { var searchQuery = $@"SELECT VALUE { Constants.ColumnName } FROM { Constants.TableName } WHERE { Constants.ColumnName } IS NULL"; searchResult = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); IIonValue ionVal = null; foreach (var row in result) { ionVal = row; } return ionVal; }); } else { var searchQuery = $@"SELECT VALUE { Constants.ColumnName } FROM { Constants.TableName } WHERE { Constants.ColumnName } = ?"; searchResult = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery, ionValue); IIonValue ionVal = null; foreach (var row in result) { ionVal = row; } return ionVal; }); } if (searchResult.Type() != ionValue.Type()) { Assert.Fail($"The queried value type, { searchResult.Type().ToString() }," + $"does not match { ionValue.Type().ToString() }."); } } [TestMethod] public void Execute_ExecuteLambdaThatDoesNotReturnValue_RecordIsUpdated() { // Given. // Create Ion struct to insert. IIonValue ionStruct = ValueFactory.NewEmptyStruct(); ionStruct.SetField(Constants.ColumnName, ValueFactory.NewString(Constants.SingleDocumentValue)); // When. var query = $"INSERT INTO {Constants.TableName} ?"; qldbDriver.Execute(txn => txn.Execute(query, ionStruct)); // Then. var searchQuery = $@"SELECT VALUE {Constants.ColumnName} FROM {Constants.TableName} WHERE {Constants.ColumnName} = '{Constants.SingleDocumentValue}'"; var value = qldbDriver.Execute(txn => { var result = txn.Execute(searchQuery); string value = ""; foreach (var row in result) { value = row.StringValue; } return value; }); Assert.AreEqual(Constants.SingleDocumentValue, value); } [TestMethod] [ExpectedException(typeof(BadRequestException))] public void Execute_DeleteTableThatDoesntExist_ThrowsBadRequestException() { // Given. var query = "DELETE FROM NonExistentTable"; // When. qldbDriver.Execute(txn => txn.Execute(query)); } [TestMethod] public void Execute_ExecutionMetrics() { qldbDriver.Execute(txn => { var insertQuery = String.Format("INSERT INTO {0} << {{'col': 1}}, {{'col': 2}}, {{'col': 3}} >>", Constants.TableName); txn.Execute(insertQuery); }); // Given var selectQuery = String.Format("SELECT * FROM {0} as a, {0} as b, {0} as c, {0} as d, {0} as e, {0} as f", Constants.TableName); // When qldbDriver.Execute(txn => { var result = txn.Execute(selectQuery); long readIOs = 0; long processingTime = 0; foreach (IIonValue row in result) { var ioUsage = result.GetConsumedIOs(); if (ioUsage != null) readIOs = ioUsage.Value.ReadIOs; var timingInfo = result.GetTimingInformation(); if (timingInfo != null) processingTime = timingInfo.Value.ProcessingTimeMilliseconds; } // The 1092 value is from selectQuery, that performs self joins on a table. Assert.AreEqual(1092, readIOs); Assert.IsTrue(processingTime > 0); }); // When var result = qldbDriver.Execute(txn => { return txn.Execute(selectQuery); }); var ioUsage = result.GetConsumedIOs(); var timingInfo = result.GetTimingInformation(); Assert.IsNotNull(ioUsage); Assert.IsNotNull(timingInfo); // The 1092 value is from selectQuery, that performs self joins on a table. Assert.AreEqual(1092, ioUsage?.ReadIOs); Assert.IsTrue(timingInfo?.ProcessingTimeMilliseconds > 0); } [TestMethod] public void Execute_ReturnTransactionIdAfterStatementExecution() { var query = $"SELECT * FROM {Constants.TableName}"; var txnId = qldbDriver.Execute(txn => { txn.Execute(query); return txn.Id; }); Assert.IsNotNull(txnId); Assert.IsTrue(txnId.Length > 0); } } }
34.916031
167
0.499563
[ "Apache-2.0" ]
awslabs/amazon-qldb-driver-dotnet
Amazon.QLDB.Driver.IntegrationTests/StatementExecutionTests.cs
32,020
C#
using System; using System.Linq; using NUnit.Framework; using Shouldly; namespace Nimbus.UnitTests.MulticastRequestResponseTests { [TestFixture] internal class WhenTakingASingleResponse : GivenAWrapperWithTwoResponses { private readonly TimeSpan _timeout = TimeSpan.FromSeconds(1); private string[] _result; protected override void When() { _result = Subject.ReturnResponsesOpportunistically(_timeout).Take(1).ToArray(); } [Test] public void TheElapsedTimeShouldBeLessThanTheTimeout() { ElapsedTime.ShouldBeLessThan(_timeout); } [Test] public void ThereShouldBeASingleResult() { _result.Count().ShouldBe(1); } } }
24.1875
91
0.647287
[ "MIT" ]
dicko2/Nimbus
src/Tests/Nimbus.UnitTests/MulticastRequestResponseTests/WhenTakingASingleResponse.cs
774
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 lex-models-2017-04-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Net; using Amazon.LexModelBuildingService.Model; using Amazon.LexModelBuildingService.Model.Internal.MarshallTransformations; using Amazon.LexModelBuildingService.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.LexModelBuildingService { /// <summary> /// Implementation for accessing LexModelBuildingService /// /// Amazon Lex Build-Time Actions /// <para> /// Amazon Lex is an AWS service for building conversational voice and text interfaces. /// Use these actions to create, update, and delete conversational bots for new and existing /// client applications. /// </para> /// </summary> public partial class AmazonLexModelBuildingServiceClient : AmazonServiceClient, IAmazonLexModelBuildingService { private static IServiceMetadata serviceMetadata = new AmazonLexModelBuildingServiceMetadata(); #region Constructors /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonLexModelBuildingServiceClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonLexModelBuildingServiceConfig()) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonLexModelBuildingServiceClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonLexModelBuildingServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonLexModelBuildingServiceClient Configuration Object</param> public AmazonLexModelBuildingServiceClient(AmazonLexModelBuildingServiceConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonLexModelBuildingServiceClient(AWSCredentials credentials) : this(credentials, new AmazonLexModelBuildingServiceConfig()) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonLexModelBuildingServiceClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonLexModelBuildingServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Credentials and an /// AmazonLexModelBuildingServiceClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonLexModelBuildingServiceClient Configuration Object</param> public AmazonLexModelBuildingServiceClient(AWSCredentials credentials, AmazonLexModelBuildingServiceConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonLexModelBuildingServiceClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonLexModelBuildingServiceConfig()) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonLexModelBuildingServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonLexModelBuildingServiceConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonLexModelBuildingServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonLexModelBuildingServiceClient Configuration Object</param> public AmazonLexModelBuildingServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonLexModelBuildingServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonLexModelBuildingServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLexModelBuildingServiceConfig()) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonLexModelBuildingServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonLexModelBuildingServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonLexModelBuildingServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonLexModelBuildingServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonLexModelBuildingServiceClient Configuration Object</param> public AmazonLexModelBuildingServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonLexModelBuildingServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region CreateBotVersion /// <summary> /// Creates a new version of the bot based on the <code>$LATEST</code> version. If the /// <code>$LATEST</code> version of this resource hasn't changed since you created the /// last version, Amazon Lex doesn't create a new version. It returns the last created /// version. /// /// <note> /// <para> /// You can update only the <code>$LATEST</code> version of the bot. You can't update /// the numbered versions that you create with the <code>CreateBotVersion</code> operation. /// </para> /// </note> /// <para> /// When you create the first version of a bot, Amazon Lex sets the version to 1. Subsequent /// versions increment by 1. For more information, see <a>versioning-intro</a>. /// </para> /// /// <para> /// This operation requires permission for the <code>lex:CreateBotVersion</code> action. /// /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateBotVersion service method.</param> /// /// <returns>The response from the CreateBotVersion service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.PreconditionFailedException"> /// The checksum of the resource that you are trying to change does not match the checksum /// in the request. Check the resource's checksum and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateBotVersion">REST API Reference for CreateBotVersion Operation</seealso> public virtual CreateBotVersionResponse CreateBotVersion(CreateBotVersionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateBotVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateBotVersionResponseUnmarshaller.Instance; return Invoke<CreateBotVersionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateBotVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateBotVersion operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateBotVersion /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateBotVersion">REST API Reference for CreateBotVersion Operation</seealso> public virtual IAsyncResult BeginCreateBotVersion(CreateBotVersionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateBotVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateBotVersionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateBotVersion operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateBotVersion.</param> /// /// <returns>Returns a CreateBotVersionResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateBotVersion">REST API Reference for CreateBotVersion Operation</seealso> public virtual CreateBotVersionResponse EndCreateBotVersion(IAsyncResult asyncResult) { return EndInvoke<CreateBotVersionResponse>(asyncResult); } #endregion #region CreateIntentVersion /// <summary> /// Creates a new version of an intent based on the <code>$LATEST</code> version of the /// intent. If the <code>$LATEST</code> version of this intent hasn't changed since you /// last updated it, Amazon Lex doesn't create a new version. It returns the last version /// you created. /// /// <note> /// <para> /// You can update only the <code>$LATEST</code> version of the intent. You can't update /// the numbered versions that you create with the <code>CreateIntentVersion</code> operation. /// </para> /// </note> /// <para> /// When you create a version of an intent, Amazon Lex sets the version to 1. Subsequent /// versions increment by 1. For more information, see <a>versioning-intro</a>. /// </para> /// /// <para> /// This operation requires permissions to perform the <code>lex:CreateIntentVersion</code> /// action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateIntentVersion service method.</param> /// /// <returns>The response from the CreateIntentVersion service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.PreconditionFailedException"> /// The checksum of the resource that you are trying to change does not match the checksum /// in the request. Check the resource's checksum and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateIntentVersion">REST API Reference for CreateIntentVersion Operation</seealso> public virtual CreateIntentVersionResponse CreateIntentVersion(CreateIntentVersionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateIntentVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateIntentVersionResponseUnmarshaller.Instance; return Invoke<CreateIntentVersionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateIntentVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateIntentVersion operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateIntentVersion /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateIntentVersion">REST API Reference for CreateIntentVersion Operation</seealso> public virtual IAsyncResult BeginCreateIntentVersion(CreateIntentVersionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateIntentVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateIntentVersionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateIntentVersion operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateIntentVersion.</param> /// /// <returns>Returns a CreateIntentVersionResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateIntentVersion">REST API Reference for CreateIntentVersion Operation</seealso> public virtual CreateIntentVersionResponse EndCreateIntentVersion(IAsyncResult asyncResult) { return EndInvoke<CreateIntentVersionResponse>(asyncResult); } #endregion #region CreateSlotTypeVersion /// <summary> /// Creates a new version of a slot type based on the <code>$LATEST</code> version of /// the specified slot type. If the <code>$LATEST</code> version of this resource has /// not changed since the last version that you created, Amazon Lex doesn't create a new /// version. It returns the last version that you created. /// /// <note> /// <para> /// You can update only the <code>$LATEST</code> version of a slot type. You can't update /// the numbered versions that you create with the <code>CreateSlotTypeVersion</code> /// operation. /// </para> /// </note> /// <para> /// When you create a version of a slot type, Amazon Lex sets the version to 1. Subsequent /// versions increment by 1. For more information, see <a>versioning-intro</a>. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:CreateSlotTypeVersion</code> /// action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateSlotTypeVersion service method.</param> /// /// <returns>The response from the CreateSlotTypeVersion service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.PreconditionFailedException"> /// The checksum of the resource that you are trying to change does not match the checksum /// in the request. Check the resource's checksum and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateSlotTypeVersion">REST API Reference for CreateSlotTypeVersion Operation</seealso> public virtual CreateSlotTypeVersionResponse CreateSlotTypeVersion(CreateSlotTypeVersionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateSlotTypeVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateSlotTypeVersionResponseUnmarshaller.Instance; return Invoke<CreateSlotTypeVersionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateSlotTypeVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateSlotTypeVersion operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateSlotTypeVersion /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateSlotTypeVersion">REST API Reference for CreateSlotTypeVersion Operation</seealso> public virtual IAsyncResult BeginCreateSlotTypeVersion(CreateSlotTypeVersionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateSlotTypeVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateSlotTypeVersionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateSlotTypeVersion operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateSlotTypeVersion.</param> /// /// <returns>Returns a CreateSlotTypeVersionResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateSlotTypeVersion">REST API Reference for CreateSlotTypeVersion Operation</seealso> public virtual CreateSlotTypeVersionResponse EndCreateSlotTypeVersion(IAsyncResult asyncResult) { return EndInvoke<CreateSlotTypeVersionResponse>(asyncResult); } #endregion #region DeleteBot /// <summary> /// Deletes all versions of the bot, including the <code>$LATEST</code> version. To delete /// a specific version of the bot, use the <a>DeleteBotVersion</a> operation. The <code>DeleteBot</code> /// operation doesn't immediately remove the bot schema. Instead, it is marked for deletion /// and removed later. /// /// /// <para> /// Amazon Lex stores utterances indefinitely for improving the ability of your bot to /// respond to user inputs. These utterances are not removed when the bot is deleted. /// To remove the utterances, use the <a>DeleteUtterances</a> operation. /// </para> /// /// <para> /// If a bot has an alias, you can't delete it. Instead, the <code>DeleteBot</code> operation /// returns a <code>ResourceInUseException</code> exception that includes a reference /// to the alias that refers to the bot. To remove the reference to the bot, delete the /// alias. If you get the same exception again, delete the referring alias until the <code>DeleteBot</code> /// operation is successful. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:DeleteBot</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteBot service method.</param> /// /// <returns>The response from the DeleteBot service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ResourceInUseException"> /// The resource that you are attempting to delete is referred to by another resource. /// Use this information to remove references to the resource that you are trying to delete. /// /// /// <para> /// The body of the exception contains a JSON object that describes the resource. /// </para> /// /// <para> /// <code>{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,</code> /// </para> /// /// <para> /// <code>"resourceReference": {</code> /// </para> /// /// <para> /// <code>"name": <i>string</i>, "version": <i>string</i> } }</code> /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBot">REST API Reference for DeleteBot Operation</seealso> public virtual DeleteBotResponse DeleteBot(DeleteBotRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotResponseUnmarshaller.Instance; return Invoke<DeleteBotResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteBot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteBot operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteBot /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBot">REST API Reference for DeleteBot Operation</seealso> public virtual IAsyncResult BeginDeleteBot(DeleteBotRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteBot operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteBot.</param> /// /// <returns>Returns a DeleteBotResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBot">REST API Reference for DeleteBot Operation</seealso> public virtual DeleteBotResponse EndDeleteBot(IAsyncResult asyncResult) { return EndInvoke<DeleteBotResponse>(asyncResult); } #endregion #region DeleteBotAlias /// <summary> /// Deletes an alias for the specified bot. /// /// /// <para> /// You can't delete an alias that is used in the association between a bot and a messaging /// channel. If an alias is used in a channel association, the <code>DeleteBot</code> /// operation returns a <code>ResourceInUseException</code> exception that includes a /// reference to the channel association that refers to the bot. You can remove the reference /// to the alias by deleting the channel association. If you get the same exception again, /// delete the referring association until the <code>DeleteBotAlias</code> operation is /// successful. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteBotAlias service method.</param> /// /// <returns>The response from the DeleteBotAlias service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ResourceInUseException"> /// The resource that you are attempting to delete is referred to by another resource. /// Use this information to remove references to the resource that you are trying to delete. /// /// /// <para> /// The body of the exception contains a JSON object that describes the resource. /// </para> /// /// <para> /// <code>{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,</code> /// </para> /// /// <para> /// <code>"resourceReference": {</code> /// </para> /// /// <para> /// <code>"name": <i>string</i>, "version": <i>string</i> } }</code> /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotAlias">REST API Reference for DeleteBotAlias Operation</seealso> public virtual DeleteBotAliasResponse DeleteBotAlias(DeleteBotAliasRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotAliasRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotAliasResponseUnmarshaller.Instance; return Invoke<DeleteBotAliasResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteBotAlias operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteBotAlias operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteBotAlias /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotAlias">REST API Reference for DeleteBotAlias Operation</seealso> public virtual IAsyncResult BeginDeleteBotAlias(DeleteBotAliasRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotAliasRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotAliasResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteBotAlias operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteBotAlias.</param> /// /// <returns>Returns a DeleteBotAliasResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotAlias">REST API Reference for DeleteBotAlias Operation</seealso> public virtual DeleteBotAliasResponse EndDeleteBotAlias(IAsyncResult asyncResult) { return EndInvoke<DeleteBotAliasResponse>(asyncResult); } #endregion #region DeleteBotChannelAssociation /// <summary> /// Deletes the association between an Amazon Lex bot and a messaging platform. /// /// /// <para> /// This operation requires permission for the <code>lex:DeleteBotChannelAssociation</code> /// action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteBotChannelAssociation service method.</param> /// /// <returns>The response from the DeleteBotChannelAssociation service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotChannelAssociation">REST API Reference for DeleteBotChannelAssociation Operation</seealso> public virtual DeleteBotChannelAssociationResponse DeleteBotChannelAssociation(DeleteBotChannelAssociationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotChannelAssociationRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotChannelAssociationResponseUnmarshaller.Instance; return Invoke<DeleteBotChannelAssociationResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteBotChannelAssociation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteBotChannelAssociation operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteBotChannelAssociation /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotChannelAssociation">REST API Reference for DeleteBotChannelAssociation Operation</seealso> public virtual IAsyncResult BeginDeleteBotChannelAssociation(DeleteBotChannelAssociationRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotChannelAssociationRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotChannelAssociationResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteBotChannelAssociation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteBotChannelAssociation.</param> /// /// <returns>Returns a DeleteBotChannelAssociationResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotChannelAssociation">REST API Reference for DeleteBotChannelAssociation Operation</seealso> public virtual DeleteBotChannelAssociationResponse EndDeleteBotChannelAssociation(IAsyncResult asyncResult) { return EndInvoke<DeleteBotChannelAssociationResponse>(asyncResult); } #endregion #region DeleteBotVersion /// <summary> /// Deletes a specific version of a bot. To delete all versions of a bot, use the <a>DeleteBot</a> /// operation. /// /// /// <para> /// This operation requires permissions for the <code>lex:DeleteBotVersion</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteBotVersion service method.</param> /// /// <returns>The response from the DeleteBotVersion service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ResourceInUseException"> /// The resource that you are attempting to delete is referred to by another resource. /// Use this information to remove references to the resource that you are trying to delete. /// /// /// <para> /// The body of the exception contains a JSON object that describes the resource. /// </para> /// /// <para> /// <code>{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,</code> /// </para> /// /// <para> /// <code>"resourceReference": {</code> /// </para> /// /// <para> /// <code>"name": <i>string</i>, "version": <i>string</i> } }</code> /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotVersion">REST API Reference for DeleteBotVersion Operation</seealso> public virtual DeleteBotVersionResponse DeleteBotVersion(DeleteBotVersionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotVersionResponseUnmarshaller.Instance; return Invoke<DeleteBotVersionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteBotVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteBotVersion operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteBotVersion /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotVersion">REST API Reference for DeleteBotVersion Operation</seealso> public virtual IAsyncResult BeginDeleteBotVersion(DeleteBotVersionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteBotVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteBotVersionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteBotVersion operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteBotVersion.</param> /// /// <returns>Returns a DeleteBotVersionResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotVersion">REST API Reference for DeleteBotVersion Operation</seealso> public virtual DeleteBotVersionResponse EndDeleteBotVersion(IAsyncResult asyncResult) { return EndInvoke<DeleteBotVersionResponse>(asyncResult); } #endregion #region DeleteIntent /// <summary> /// Deletes all versions of the intent, including the <code>$LATEST</code> version. To /// delete a specific version of the intent, use the <a>DeleteIntentVersion</a> operation. /// /// /// <para> /// You can delete a version of an intent only if it is not referenced. To delete an /// intent that is referred to in one or more bots (see <a>how-it-works</a>), you must /// remove those references first. /// </para> /// <note> /// <para> /// If you get the <code>ResourceInUseException</code> exception, it provides an example /// reference that shows where the intent is referenced. To remove the reference to the /// intent, either update the bot or delete it. If you get the same exception when you /// attempt to delete the intent again, repeat until the intent has no references and /// the call to <code>DeleteIntent</code> is successful. /// </para> /// </note> /// <para> /// This operation requires permission for the <code>lex:DeleteIntent</code> action. /// /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteIntent service method.</param> /// /// <returns>The response from the DeleteIntent service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ResourceInUseException"> /// The resource that you are attempting to delete is referred to by another resource. /// Use this information to remove references to the resource that you are trying to delete. /// /// /// <para> /// The body of the exception contains a JSON object that describes the resource. /// </para> /// /// <para> /// <code>{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,</code> /// </para> /// /// <para> /// <code>"resourceReference": {</code> /// </para> /// /// <para> /// <code>"name": <i>string</i>, "version": <i>string</i> } }</code> /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntent">REST API Reference for DeleteIntent Operation</seealso> public virtual DeleteIntentResponse DeleteIntent(DeleteIntentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteIntentResponseUnmarshaller.Instance; return Invoke<DeleteIntentResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteIntent operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteIntent operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteIntent /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntent">REST API Reference for DeleteIntent Operation</seealso> public virtual IAsyncResult BeginDeleteIntent(DeleteIntentRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteIntentResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteIntent operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteIntent.</param> /// /// <returns>Returns a DeleteIntentResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntent">REST API Reference for DeleteIntent Operation</seealso> public virtual DeleteIntentResponse EndDeleteIntent(IAsyncResult asyncResult) { return EndInvoke<DeleteIntentResponse>(asyncResult); } #endregion #region DeleteIntentVersion /// <summary> /// Deletes a specific version of an intent. To delete all versions of a intent, use the /// <a>DeleteIntent</a> operation. /// /// /// <para> /// This operation requires permissions for the <code>lex:DeleteIntentVersion</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteIntentVersion service method.</param> /// /// <returns>The response from the DeleteIntentVersion service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ResourceInUseException"> /// The resource that you are attempting to delete is referred to by another resource. /// Use this information to remove references to the resource that you are trying to delete. /// /// /// <para> /// The body of the exception contains a JSON object that describes the resource. /// </para> /// /// <para> /// <code>{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,</code> /// </para> /// /// <para> /// <code>"resourceReference": {</code> /// </para> /// /// <para> /// <code>"name": <i>string</i>, "version": <i>string</i> } }</code> /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntentVersion">REST API Reference for DeleteIntentVersion Operation</seealso> public virtual DeleteIntentVersionResponse DeleteIntentVersion(DeleteIntentVersionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteIntentVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteIntentVersionResponseUnmarshaller.Instance; return Invoke<DeleteIntentVersionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteIntentVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteIntentVersion operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteIntentVersion /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntentVersion">REST API Reference for DeleteIntentVersion Operation</seealso> public virtual IAsyncResult BeginDeleteIntentVersion(DeleteIntentVersionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteIntentVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteIntentVersionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteIntentVersion operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteIntentVersion.</param> /// /// <returns>Returns a DeleteIntentVersionResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntentVersion">REST API Reference for DeleteIntentVersion Operation</seealso> public virtual DeleteIntentVersionResponse EndDeleteIntentVersion(IAsyncResult asyncResult) { return EndInvoke<DeleteIntentVersionResponse>(asyncResult); } #endregion #region DeleteSlotType /// <summary> /// Deletes all versions of the slot type, including the <code>$LATEST</code> version. /// To delete a specific version of the slot type, use the <a>DeleteSlotTypeVersion</a> /// operation. /// /// /// <para> /// You can delete a version of a slot type only if it is not referenced. To delete a /// slot type that is referred to in one or more intents, you must remove those references /// first. /// </para> /// <note> /// <para> /// If you get the <code>ResourceInUseException</code> exception, the exception provides /// an example reference that shows the intent where the slot type is referenced. To remove /// the reference to the slot type, either update the intent or delete it. If you get /// the same exception when you attempt to delete the slot type again, repeat until the /// slot type has no references and the <code>DeleteSlotType</code> call is successful. /// /// </para> /// </note> /// <para> /// This operation requires permission for the <code>lex:DeleteSlotType</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteSlotType service method.</param> /// /// <returns>The response from the DeleteSlotType service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ResourceInUseException"> /// The resource that you are attempting to delete is referred to by another resource. /// Use this information to remove references to the resource that you are trying to delete. /// /// /// <para> /// The body of the exception contains a JSON object that describes the resource. /// </para> /// /// <para> /// <code>{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,</code> /// </para> /// /// <para> /// <code>"resourceReference": {</code> /// </para> /// /// <para> /// <code>"name": <i>string</i>, "version": <i>string</i> } }</code> /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotType">REST API Reference for DeleteSlotType Operation</seealso> public virtual DeleteSlotTypeResponse DeleteSlotType(DeleteSlotTypeRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteSlotTypeRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteSlotTypeResponseUnmarshaller.Instance; return Invoke<DeleteSlotTypeResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteSlotType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteSlotType operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteSlotType /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotType">REST API Reference for DeleteSlotType Operation</seealso> public virtual IAsyncResult BeginDeleteSlotType(DeleteSlotTypeRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteSlotTypeRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteSlotTypeResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteSlotType operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteSlotType.</param> /// /// <returns>Returns a DeleteSlotTypeResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotType">REST API Reference for DeleteSlotType Operation</seealso> public virtual DeleteSlotTypeResponse EndDeleteSlotType(IAsyncResult asyncResult) { return EndInvoke<DeleteSlotTypeResponse>(asyncResult); } #endregion #region DeleteSlotTypeVersion /// <summary> /// Deletes a specific version of a slot type. To delete all versions of a slot type, /// use the <a>DeleteSlotType</a> operation. /// /// /// <para> /// This operation requires permissions for the <code>lex:DeleteSlotTypeVersion</code> /// action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteSlotTypeVersion service method.</param> /// /// <returns>The response from the DeleteSlotTypeVersion service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ResourceInUseException"> /// The resource that you are attempting to delete is referred to by another resource. /// Use this information to remove references to the resource that you are trying to delete. /// /// /// <para> /// The body of the exception contains a JSON object that describes the resource. /// </para> /// /// <para> /// <code>{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,</code> /// </para> /// /// <para> /// <code>"resourceReference": {</code> /// </para> /// /// <para> /// <code>"name": <i>string</i>, "version": <i>string</i> } }</code> /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotTypeVersion">REST API Reference for DeleteSlotTypeVersion Operation</seealso> public virtual DeleteSlotTypeVersionResponse DeleteSlotTypeVersion(DeleteSlotTypeVersionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteSlotTypeVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteSlotTypeVersionResponseUnmarshaller.Instance; return Invoke<DeleteSlotTypeVersionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteSlotTypeVersion operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteSlotTypeVersion operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteSlotTypeVersion /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotTypeVersion">REST API Reference for DeleteSlotTypeVersion Operation</seealso> public virtual IAsyncResult BeginDeleteSlotTypeVersion(DeleteSlotTypeVersionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteSlotTypeVersionRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteSlotTypeVersionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteSlotTypeVersion operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteSlotTypeVersion.</param> /// /// <returns>Returns a DeleteSlotTypeVersionResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotTypeVersion">REST API Reference for DeleteSlotTypeVersion Operation</seealso> public virtual DeleteSlotTypeVersionResponse EndDeleteSlotTypeVersion(IAsyncResult asyncResult) { return EndInvoke<DeleteSlotTypeVersionResponse>(asyncResult); } #endregion #region DeleteUtterances /// <summary> /// Deletes stored utterances. /// /// /// <para> /// Amazon Lex stores the utterances that users send to your bot. Utterances are stored /// for 15 days for use with the <a>GetUtterancesView</a> operation, and then stored indefinitely /// for use in improving the ability of your bot to respond to user input. /// </para> /// /// <para> /// Use the <code>DeleteUtterances</code> operation to manually delete stored utterances /// for a specific user. When you use the <code>DeleteUtterances</code> operation, utterances /// stored for improving your bot's ability to respond to user input are deleted immediately. /// Utterances stored for use with the <code>GetUtterancesView</code> operation are deleted /// after 15 days. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:DeleteUtterances</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteUtterances service method.</param> /// /// <returns>The response from the DeleteUtterances service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteUtterances">REST API Reference for DeleteUtterances Operation</seealso> public virtual DeleteUtterancesResponse DeleteUtterances(DeleteUtterancesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteUtterancesRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteUtterancesResponseUnmarshaller.Instance; return Invoke<DeleteUtterancesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteUtterances operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteUtterances operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteUtterances /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteUtterances">REST API Reference for DeleteUtterances Operation</seealso> public virtual IAsyncResult BeginDeleteUtterances(DeleteUtterancesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteUtterancesRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteUtterancesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteUtterances operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteUtterances.</param> /// /// <returns>Returns a DeleteUtterancesResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteUtterances">REST API Reference for DeleteUtterances Operation</seealso> public virtual DeleteUtterancesResponse EndDeleteUtterances(IAsyncResult asyncResult) { return EndInvoke<DeleteUtterancesResponse>(asyncResult); } #endregion #region GetBot /// <summary> /// Returns metadata information for a specific bot. You must provide the bot name and /// the bot version or alias. /// /// /// <para> /// This operation requires permissions for the <code>lex:GetBot</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBot service method.</param> /// /// <returns>The response from the GetBot service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBot">REST API Reference for GetBot Operation</seealso> public virtual GetBotResponse GetBot(GetBotRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotResponseUnmarshaller.Instance; return Invoke<GetBotResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBot operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBot /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBot">REST API Reference for GetBot Operation</seealso> public virtual IAsyncResult BeginGetBot(GetBotRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBot operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBot.</param> /// /// <returns>Returns a GetBotResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBot">REST API Reference for GetBot Operation</seealso> public virtual GetBotResponse EndGetBot(IAsyncResult asyncResult) { return EndInvoke<GetBotResponse>(asyncResult); } #endregion #region GetBotAlias /// <summary> /// Returns information about an Amazon Lex bot alias. For more information about aliases, /// see <a>versioning-aliases</a>. /// /// /// <para> /// This operation requires permissions for the <code>lex:GetBotAlias</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBotAlias service method.</param> /// /// <returns>The response from the GetBotAlias service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAlias">REST API Reference for GetBotAlias Operation</seealso> public virtual GetBotAliasResponse GetBotAlias(GetBotAliasRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotAliasRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotAliasResponseUnmarshaller.Instance; return Invoke<GetBotAliasResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBotAlias operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBotAlias operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBotAlias /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAlias">REST API Reference for GetBotAlias Operation</seealso> public virtual IAsyncResult BeginGetBotAlias(GetBotAliasRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotAliasRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotAliasResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBotAlias operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBotAlias.</param> /// /// <returns>Returns a GetBotAliasResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAlias">REST API Reference for GetBotAlias Operation</seealso> public virtual GetBotAliasResponse EndGetBotAlias(IAsyncResult asyncResult) { return EndInvoke<GetBotAliasResponse>(asyncResult); } #endregion #region GetBotAliases /// <summary> /// Returns a list of aliases for a specified Amazon Lex bot. /// /// /// <para> /// This operation requires permissions for the <code>lex:GetBotAliases</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBotAliases service method.</param> /// /// <returns>The response from the GetBotAliases service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAliases">REST API Reference for GetBotAliases Operation</seealso> public virtual GetBotAliasesResponse GetBotAliases(GetBotAliasesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotAliasesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotAliasesResponseUnmarshaller.Instance; return Invoke<GetBotAliasesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBotAliases operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBotAliases operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBotAliases /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAliases">REST API Reference for GetBotAliases Operation</seealso> public virtual IAsyncResult BeginGetBotAliases(GetBotAliasesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotAliasesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotAliasesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBotAliases operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBotAliases.</param> /// /// <returns>Returns a GetBotAliasesResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAliases">REST API Reference for GetBotAliases Operation</seealso> public virtual GetBotAliasesResponse EndGetBotAliases(IAsyncResult asyncResult) { return EndInvoke<GetBotAliasesResponse>(asyncResult); } #endregion #region GetBotChannelAssociation /// <summary> /// Returns information about the association between an Amazon Lex bot and a messaging /// platform. /// /// /// <para> /// This operation requires permissions for the <code>lex:GetBotChannelAssociation</code> /// action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBotChannelAssociation service method.</param> /// /// <returns>The response from the GetBotChannelAssociation service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociation">REST API Reference for GetBotChannelAssociation Operation</seealso> public virtual GetBotChannelAssociationResponse GetBotChannelAssociation(GetBotChannelAssociationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotChannelAssociationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotChannelAssociationResponseUnmarshaller.Instance; return Invoke<GetBotChannelAssociationResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBotChannelAssociation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBotChannelAssociation operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBotChannelAssociation /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociation">REST API Reference for GetBotChannelAssociation Operation</seealso> public virtual IAsyncResult BeginGetBotChannelAssociation(GetBotChannelAssociationRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotChannelAssociationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotChannelAssociationResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBotChannelAssociation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBotChannelAssociation.</param> /// /// <returns>Returns a GetBotChannelAssociationResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociation">REST API Reference for GetBotChannelAssociation Operation</seealso> public virtual GetBotChannelAssociationResponse EndGetBotChannelAssociation(IAsyncResult asyncResult) { return EndInvoke<GetBotChannelAssociationResponse>(asyncResult); } #endregion #region GetBotChannelAssociations /// <summary> /// Returns a list of all of the channels associated with the specified bot. /// /// /// <para> /// The <code>GetBotChannelAssociations</code> operation requires permissions for the /// <code>lex:GetBotChannelAssociations</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBotChannelAssociations service method.</param> /// /// <returns>The response from the GetBotChannelAssociations service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociations">REST API Reference for GetBotChannelAssociations Operation</seealso> public virtual GetBotChannelAssociationsResponse GetBotChannelAssociations(GetBotChannelAssociationsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotChannelAssociationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotChannelAssociationsResponseUnmarshaller.Instance; return Invoke<GetBotChannelAssociationsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBotChannelAssociations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBotChannelAssociations operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBotChannelAssociations /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociations">REST API Reference for GetBotChannelAssociations Operation</seealso> public virtual IAsyncResult BeginGetBotChannelAssociations(GetBotChannelAssociationsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotChannelAssociationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotChannelAssociationsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBotChannelAssociations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBotChannelAssociations.</param> /// /// <returns>Returns a GetBotChannelAssociationsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociations">REST API Reference for GetBotChannelAssociations Operation</seealso> public virtual GetBotChannelAssociationsResponse EndGetBotChannelAssociations(IAsyncResult asyncResult) { return EndInvoke<GetBotChannelAssociationsResponse>(asyncResult); } #endregion #region GetBots /// <summary> /// Returns bot information as follows: /// /// <ul> <li> /// <para> /// If you provide the <code>nameContains</code> field, the response includes information /// for the <code>$LATEST</code> version of all bots whose name contains the specified /// string. /// </para> /// </li> <li> /// <para> /// If you don't specify the <code>nameContains</code> field, the operation returns information /// about the <code>$LATEST</code> version of all of your bots. /// </para> /// </li> </ul> /// <para> /// This operation requires permission for the <code>lex:GetBots</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBots service method.</param> /// /// <returns>The response from the GetBots service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBots">REST API Reference for GetBots Operation</seealso> public virtual GetBotsResponse GetBots(GetBotsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotsResponseUnmarshaller.Instance; return Invoke<GetBotsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBots operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBots operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBots /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBots">REST API Reference for GetBots Operation</seealso> public virtual IAsyncResult BeginGetBots(GetBotsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBots operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBots.</param> /// /// <returns>Returns a GetBotsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBots">REST API Reference for GetBots Operation</seealso> public virtual GetBotsResponse EndGetBots(IAsyncResult asyncResult) { return EndInvoke<GetBotsResponse>(asyncResult); } #endregion #region GetBotVersions /// <summary> /// Gets information about all of the versions of a bot. /// /// /// <para> /// The <code>GetBotVersions</code> operation returns a <code>BotMetadata</code> object /// for each version of a bot. For example, if a bot has three numbered versions, the /// <code>GetBotVersions</code> operation returns four <code>BotMetadata</code> objects /// in the response, one for each numbered version and one for the <code>$LATEST</code> /// version. /// </para> /// /// <para> /// The <code>GetBotVersions</code> operation always returns at least one version, the /// <code>$LATEST</code> version. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:GetBotVersions</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBotVersions service method.</param> /// /// <returns>The response from the GetBotVersions service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotVersions">REST API Reference for GetBotVersions Operation</seealso> public virtual GetBotVersionsResponse GetBotVersions(GetBotVersionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotVersionsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotVersionsResponseUnmarshaller.Instance; return Invoke<GetBotVersionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBotVersions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBotVersions operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBotVersions /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotVersions">REST API Reference for GetBotVersions Operation</seealso> public virtual IAsyncResult BeginGetBotVersions(GetBotVersionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBotVersionsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBotVersionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBotVersions operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBotVersions.</param> /// /// <returns>Returns a GetBotVersionsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotVersions">REST API Reference for GetBotVersions Operation</seealso> public virtual GetBotVersionsResponse EndGetBotVersions(IAsyncResult asyncResult) { return EndInvoke<GetBotVersionsResponse>(asyncResult); } #endregion #region GetBuiltinIntent /// <summary> /// Returns information about a built-in intent. /// /// /// <para> /// This operation requires permission for the <code>lex:GetBuiltinIntent</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBuiltinIntent service method.</param> /// /// <returns>The response from the GetBuiltinIntent service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntent">REST API Reference for GetBuiltinIntent Operation</seealso> public virtual GetBuiltinIntentResponse GetBuiltinIntent(GetBuiltinIntentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBuiltinIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBuiltinIntentResponseUnmarshaller.Instance; return Invoke<GetBuiltinIntentResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBuiltinIntent operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBuiltinIntent operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBuiltinIntent /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntent">REST API Reference for GetBuiltinIntent Operation</seealso> public virtual IAsyncResult BeginGetBuiltinIntent(GetBuiltinIntentRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBuiltinIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBuiltinIntentResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBuiltinIntent operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBuiltinIntent.</param> /// /// <returns>Returns a GetBuiltinIntentResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntent">REST API Reference for GetBuiltinIntent Operation</seealso> public virtual GetBuiltinIntentResponse EndGetBuiltinIntent(IAsyncResult asyncResult) { return EndInvoke<GetBuiltinIntentResponse>(asyncResult); } #endregion #region GetBuiltinIntents /// <summary> /// Gets a list of built-in intents that meet the specified criteria. /// /// /// <para> /// This operation requires permission for the <code>lex:GetBuiltinIntents</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBuiltinIntents service method.</param> /// /// <returns>The response from the GetBuiltinIntents service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntents">REST API Reference for GetBuiltinIntents Operation</seealso> public virtual GetBuiltinIntentsResponse GetBuiltinIntents(GetBuiltinIntentsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBuiltinIntentsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBuiltinIntentsResponseUnmarshaller.Instance; return Invoke<GetBuiltinIntentsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBuiltinIntents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBuiltinIntents operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBuiltinIntents /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntents">REST API Reference for GetBuiltinIntents Operation</seealso> public virtual IAsyncResult BeginGetBuiltinIntents(GetBuiltinIntentsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBuiltinIntentsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBuiltinIntentsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBuiltinIntents operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBuiltinIntents.</param> /// /// <returns>Returns a GetBuiltinIntentsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntents">REST API Reference for GetBuiltinIntents Operation</seealso> public virtual GetBuiltinIntentsResponse EndGetBuiltinIntents(IAsyncResult asyncResult) { return EndInvoke<GetBuiltinIntentsResponse>(asyncResult); } #endregion #region GetBuiltinSlotTypes /// <summary> /// Gets a list of built-in slot types that meet the specified criteria. /// /// /// <para> /// For a list of built-in slot types, see <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference">Slot /// Type Reference</a> in the <i>Alexa Skills Kit</i>. /// </para> /// /// <para> /// This operation requires permission for the <code>lex:GetBuiltInSlotTypes</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBuiltinSlotTypes service method.</param> /// /// <returns>The response from the GetBuiltinSlotTypes service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinSlotTypes">REST API Reference for GetBuiltinSlotTypes Operation</seealso> public virtual GetBuiltinSlotTypesResponse GetBuiltinSlotTypes(GetBuiltinSlotTypesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetBuiltinSlotTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBuiltinSlotTypesResponseUnmarshaller.Instance; return Invoke<GetBuiltinSlotTypesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetBuiltinSlotTypes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBuiltinSlotTypes operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBuiltinSlotTypes /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinSlotTypes">REST API Reference for GetBuiltinSlotTypes Operation</seealso> public virtual IAsyncResult BeginGetBuiltinSlotTypes(GetBuiltinSlotTypesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetBuiltinSlotTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetBuiltinSlotTypesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetBuiltinSlotTypes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBuiltinSlotTypes.</param> /// /// <returns>Returns a GetBuiltinSlotTypesResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinSlotTypes">REST API Reference for GetBuiltinSlotTypes Operation</seealso> public virtual GetBuiltinSlotTypesResponse EndGetBuiltinSlotTypes(IAsyncResult asyncResult) { return EndInvoke<GetBuiltinSlotTypesResponse>(asyncResult); } #endregion #region GetExport /// <summary> /// Exports the contents of a Amazon Lex resource in a specified format. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetExport service method.</param> /// /// <returns>The response from the GetExport service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetExport">REST API Reference for GetExport Operation</seealso> public virtual GetExportResponse GetExport(GetExportRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetExportRequestMarshaller.Instance; options.ResponseUnmarshaller = GetExportResponseUnmarshaller.Instance; return Invoke<GetExportResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetExport operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetExport operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetExport /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetExport">REST API Reference for GetExport Operation</seealso> public virtual IAsyncResult BeginGetExport(GetExportRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetExportRequestMarshaller.Instance; options.ResponseUnmarshaller = GetExportResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetExport operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetExport.</param> /// /// <returns>Returns a GetExportResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetExport">REST API Reference for GetExport Operation</seealso> public virtual GetExportResponse EndGetExport(IAsyncResult asyncResult) { return EndInvoke<GetExportResponse>(asyncResult); } #endregion #region GetImport /// <summary> /// Gets information about an import job started with the <code>StartImport</code> operation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetImport service method.</param> /// /// <returns>The response from the GetImport service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetImport">REST API Reference for GetImport Operation</seealso> public virtual GetImportResponse GetImport(GetImportRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetImportRequestMarshaller.Instance; options.ResponseUnmarshaller = GetImportResponseUnmarshaller.Instance; return Invoke<GetImportResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetImport operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetImport operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetImport /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetImport">REST API Reference for GetImport Operation</seealso> public virtual IAsyncResult BeginGetImport(GetImportRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetImportRequestMarshaller.Instance; options.ResponseUnmarshaller = GetImportResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetImport operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetImport.</param> /// /// <returns>Returns a GetImportResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetImport">REST API Reference for GetImport Operation</seealso> public virtual GetImportResponse EndGetImport(IAsyncResult asyncResult) { return EndInvoke<GetImportResponse>(asyncResult); } #endregion #region GetIntent /// <summary> /// Returns information about an intent. In addition to the intent name, you must specify /// the intent version. /// /// /// <para> /// This operation requires permissions to perform the <code>lex:GetIntent</code> action. /// /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetIntent service method.</param> /// /// <returns>The response from the GetIntent service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntent">REST API Reference for GetIntent Operation</seealso> public virtual GetIntentResponse GetIntent(GetIntentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = GetIntentResponseUnmarshaller.Instance; return Invoke<GetIntentResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetIntent operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIntent operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetIntent /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntent">REST API Reference for GetIntent Operation</seealso> public virtual IAsyncResult BeginGetIntent(GetIntentRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = GetIntentResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetIntent operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetIntent.</param> /// /// <returns>Returns a GetIntentResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntent">REST API Reference for GetIntent Operation</seealso> public virtual GetIntentResponse EndGetIntent(IAsyncResult asyncResult) { return EndInvoke<GetIntentResponse>(asyncResult); } #endregion #region GetIntents /// <summary> /// Returns intent information as follows: /// /// <ul> <li> /// <para> /// If you specify the <code>nameContains</code> field, returns the <code>$LATEST</code> /// version of all intents that contain the specified string. /// </para> /// </li> <li> /// <para> /// If you don't specify the <code>nameContains</code> field, returns information about /// the <code>$LATEST</code> version of all intents. /// </para> /// </li> </ul> /// <para> /// The operation requires permission for the <code>lex:GetIntents</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetIntents service method.</param> /// /// <returns>The response from the GetIntents service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntents">REST API Reference for GetIntents Operation</seealso> public virtual GetIntentsResponse GetIntents(GetIntentsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetIntentsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetIntentsResponseUnmarshaller.Instance; return Invoke<GetIntentsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetIntents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIntents operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetIntents /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntents">REST API Reference for GetIntents Operation</seealso> public virtual IAsyncResult BeginGetIntents(GetIntentsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetIntentsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetIntentsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetIntents operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetIntents.</param> /// /// <returns>Returns a GetIntentsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntents">REST API Reference for GetIntents Operation</seealso> public virtual GetIntentsResponse EndGetIntents(IAsyncResult asyncResult) { return EndInvoke<GetIntentsResponse>(asyncResult); } #endregion #region GetIntentVersions /// <summary> /// Gets information about all of the versions of an intent. /// /// /// <para> /// The <code>GetIntentVersions</code> operation returns an <code>IntentMetadata</code> /// object for each version of an intent. For example, if an intent has three numbered /// versions, the <code>GetIntentVersions</code> operation returns four <code>IntentMetadata</code> /// objects in the response, one for each numbered version and one for the <code>$LATEST</code> /// version. /// </para> /// /// <para> /// The <code>GetIntentVersions</code> operation always returns at least one version, /// the <code>$LATEST</code> version. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:GetIntentVersions</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetIntentVersions service method.</param> /// /// <returns>The response from the GetIntentVersions service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentVersions">REST API Reference for GetIntentVersions Operation</seealso> public virtual GetIntentVersionsResponse GetIntentVersions(GetIntentVersionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetIntentVersionsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetIntentVersionsResponseUnmarshaller.Instance; return Invoke<GetIntentVersionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetIntentVersions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIntentVersions operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetIntentVersions /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentVersions">REST API Reference for GetIntentVersions Operation</seealso> public virtual IAsyncResult BeginGetIntentVersions(GetIntentVersionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetIntentVersionsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetIntentVersionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetIntentVersions operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetIntentVersions.</param> /// /// <returns>Returns a GetIntentVersionsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentVersions">REST API Reference for GetIntentVersions Operation</seealso> public virtual GetIntentVersionsResponse EndGetIntentVersions(IAsyncResult asyncResult) { return EndInvoke<GetIntentVersionsResponse>(asyncResult); } #endregion #region GetMigration /// <summary> /// Provides details about an ongoing or complete migration from an Amazon Lex V1 bot /// to an Amazon Lex V2 bot. Use this operation to view the migration alerts and warnings /// related to the migration. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetMigration service method.</param> /// /// <returns>The response from the GetMigration service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetMigration">REST API Reference for GetMigration Operation</seealso> public virtual GetMigrationResponse GetMigration(GetMigrationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetMigrationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetMigrationResponseUnmarshaller.Instance; return Invoke<GetMigrationResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetMigration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetMigration operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetMigration /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetMigration">REST API Reference for GetMigration Operation</seealso> public virtual IAsyncResult BeginGetMigration(GetMigrationRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetMigrationRequestMarshaller.Instance; options.ResponseUnmarshaller = GetMigrationResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetMigration operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetMigration.</param> /// /// <returns>Returns a GetMigrationResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetMigration">REST API Reference for GetMigration Operation</seealso> public virtual GetMigrationResponse EndGetMigration(IAsyncResult asyncResult) { return EndInvoke<GetMigrationResponse>(asyncResult); } #endregion #region GetMigrations /// <summary> /// Gets a list of migrations between Amazon Lex V1 and Amazon Lex V2. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetMigrations service method.</param> /// /// <returns>The response from the GetMigrations service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetMigrations">REST API Reference for GetMigrations Operation</seealso> public virtual GetMigrationsResponse GetMigrations(GetMigrationsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetMigrationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetMigrationsResponseUnmarshaller.Instance; return Invoke<GetMigrationsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetMigrations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetMigrations operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetMigrations /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetMigrations">REST API Reference for GetMigrations Operation</seealso> public virtual IAsyncResult BeginGetMigrations(GetMigrationsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetMigrationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetMigrationsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetMigrations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetMigrations.</param> /// /// <returns>Returns a GetMigrationsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetMigrations">REST API Reference for GetMigrations Operation</seealso> public virtual GetMigrationsResponse EndGetMigrations(IAsyncResult asyncResult) { return EndInvoke<GetMigrationsResponse>(asyncResult); } #endregion #region GetSlotType /// <summary> /// Returns information about a specific version of a slot type. In addition to specifying /// the slot type name, you must specify the slot type version. /// /// /// <para> /// This operation requires permissions for the <code>lex:GetSlotType</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetSlotType service method.</param> /// /// <returns>The response from the GetSlotType service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotType">REST API Reference for GetSlotType Operation</seealso> public virtual GetSlotTypeResponse GetSlotType(GetSlotTypeRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetSlotTypeRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSlotTypeResponseUnmarshaller.Instance; return Invoke<GetSlotTypeResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetSlotType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSlotType operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSlotType /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotType">REST API Reference for GetSlotType Operation</seealso> public virtual IAsyncResult BeginGetSlotType(GetSlotTypeRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetSlotTypeRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSlotTypeResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetSlotType operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSlotType.</param> /// /// <returns>Returns a GetSlotTypeResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotType">REST API Reference for GetSlotType Operation</seealso> public virtual GetSlotTypeResponse EndGetSlotType(IAsyncResult asyncResult) { return EndInvoke<GetSlotTypeResponse>(asyncResult); } #endregion #region GetSlotTypes /// <summary> /// Returns slot type information as follows: /// /// <ul> <li> /// <para> /// If you specify the <code>nameContains</code> field, returns the <code>$LATEST</code> /// version of all slot types that contain the specified string. /// </para> /// </li> <li> /// <para> /// If you don't specify the <code>nameContains</code> field, returns information about /// the <code>$LATEST</code> version of all slot types. /// </para> /// </li> </ul> /// <para> /// The operation requires permission for the <code>lex:GetSlotTypes</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetSlotTypes service method.</param> /// /// <returns>The response from the GetSlotTypes service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypes">REST API Reference for GetSlotTypes Operation</seealso> public virtual GetSlotTypesResponse GetSlotTypes(GetSlotTypesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetSlotTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSlotTypesResponseUnmarshaller.Instance; return Invoke<GetSlotTypesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetSlotTypes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSlotTypes operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSlotTypes /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypes">REST API Reference for GetSlotTypes Operation</seealso> public virtual IAsyncResult BeginGetSlotTypes(GetSlotTypesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetSlotTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSlotTypesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetSlotTypes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSlotTypes.</param> /// /// <returns>Returns a GetSlotTypesResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypes">REST API Reference for GetSlotTypes Operation</seealso> public virtual GetSlotTypesResponse EndGetSlotTypes(IAsyncResult asyncResult) { return EndInvoke<GetSlotTypesResponse>(asyncResult); } #endregion #region GetSlotTypeVersions /// <summary> /// Gets information about all versions of a slot type. /// /// /// <para> /// The <code>GetSlotTypeVersions</code> operation returns a <code>SlotTypeMetadata</code> /// object for each version of a slot type. For example, if a slot type has three numbered /// versions, the <code>GetSlotTypeVersions</code> operation returns four <code>SlotTypeMetadata</code> /// objects in the response, one for each numbered version and one for the <code>$LATEST</code> /// version. /// </para> /// /// <para> /// The <code>GetSlotTypeVersions</code> operation always returns at least one version, /// the <code>$LATEST</code> version. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:GetSlotTypeVersions</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetSlotTypeVersions service method.</param> /// /// <returns>The response from the GetSlotTypeVersions service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypeVersions">REST API Reference for GetSlotTypeVersions Operation</seealso> public virtual GetSlotTypeVersionsResponse GetSlotTypeVersions(GetSlotTypeVersionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetSlotTypeVersionsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSlotTypeVersionsResponseUnmarshaller.Instance; return Invoke<GetSlotTypeVersionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetSlotTypeVersions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSlotTypeVersions operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetSlotTypeVersions /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypeVersions">REST API Reference for GetSlotTypeVersions Operation</seealso> public virtual IAsyncResult BeginGetSlotTypeVersions(GetSlotTypeVersionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetSlotTypeVersionsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetSlotTypeVersionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetSlotTypeVersions operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetSlotTypeVersions.</param> /// /// <returns>Returns a GetSlotTypeVersionsResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypeVersions">REST API Reference for GetSlotTypeVersions Operation</seealso> public virtual GetSlotTypeVersionsResponse EndGetSlotTypeVersions(IAsyncResult asyncResult) { return EndInvoke<GetSlotTypeVersionsResponse>(asyncResult); } #endregion #region GetUtterancesView /// <summary> /// Use the <code>GetUtterancesView</code> operation to get information about the utterances /// that your users have made to your bot. You can use this list to tune the utterances /// that your bot responds to. /// /// /// <para> /// For example, say that you have created a bot to order flowers. After your users have /// used your bot for a while, use the <code>GetUtterancesView</code> operation to see /// the requests that they have made and whether they have been successful. You might /// find that the utterance "I want flowers" is not being recognized. You could add this /// utterance to the <code>OrderFlowers</code> intent so that your bot recognizes that /// utterance. /// </para> /// /// <para> /// After you publish a new version of a bot, you can get information about the old version /// and the new so that you can compare the performance across the two versions. /// </para> /// /// <para> /// Utterance statistics are generated once a day. Data is available for the last 15 days. /// You can request information for up to 5 versions of your bot in each request. Amazon /// Lex returns the most frequent utterances received by the bot in the last 15 days. /// The response contains information about a maximum of 100 utterances for each version. /// </para> /// /// <para> /// If you set <code>childDirected</code> field to true when you created your bot, if /// you are using slot obfuscation with one or more slots, or if you opted out of participating /// in improving Amazon Lex, utterances are not available. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:GetUtterancesView</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetUtterancesView service method.</param> /// /// <returns>The response from the GetUtterancesView service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetUtterancesView">REST API Reference for GetUtterancesView Operation</seealso> public virtual GetUtterancesViewResponse GetUtterancesView(GetUtterancesViewRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetUtterancesViewRequestMarshaller.Instance; options.ResponseUnmarshaller = GetUtterancesViewResponseUnmarshaller.Instance; return Invoke<GetUtterancesViewResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetUtterancesView operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetUtterancesView operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetUtterancesView /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetUtterancesView">REST API Reference for GetUtterancesView Operation</seealso> public virtual IAsyncResult BeginGetUtterancesView(GetUtterancesViewRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetUtterancesViewRequestMarshaller.Instance; options.ResponseUnmarshaller = GetUtterancesViewResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetUtterancesView operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetUtterancesView.</param> /// /// <returns>Returns a GetUtterancesViewResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetUtterancesView">REST API Reference for GetUtterancesView Operation</seealso> public virtual GetUtterancesViewResponse EndGetUtterancesView(IAsyncResult asyncResult) { return EndInvoke<GetUtterancesViewResponse>(asyncResult); } #endregion #region ListTagsForResource /// <summary> /// Gets a list of tags associated with the specified resource. Only bots, bot aliases, /// and bot channels can have tags associated with them. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// /// <returns>The response from the ListTagsForResource service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return Invoke<ListTagsForResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param> /// /// <returns>Returns a ListTagsForResourceResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult) { return EndInvoke<ListTagsForResourceResponse>(asyncResult); } #endregion #region PutBot /// <summary> /// Creates an Amazon Lex conversational bot or replaces an existing bot. When you create /// or update a bot you are only required to specify a name, a locale, and whether the /// bot is directed toward children under age 13. You can use this to add intents later, /// or to remove intents from an existing bot. When you create a bot with the minimum /// information, the bot is created or updated but Amazon Lex returns the <code/> response /// <code>FAILED</code>. You can build the bot after you add one or more intents. For /// more information about Amazon Lex bots, see <a>how-it-works</a>. /// /// /// <para> /// If you specify the name of an existing bot, the fields in the request replace the /// existing values in the <code>$LATEST</code> version of the bot. Amazon Lex removes /// any fields that you don't provide values for in the request, except for the <code>idleTTLInSeconds</code> /// and <code>privacySettings</code> fields, which are set to their default values. If /// you don't specify values for required fields, Amazon Lex throws an exception. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:PutBot</code> action. For more /// information, see <a>security-iam</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutBot service method.</param> /// /// <returns>The response from the PutBot service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.PreconditionFailedException"> /// The checksum of the resource that you are trying to change does not match the checksum /// in the request. Check the resource's checksum and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBot">REST API Reference for PutBot Operation</seealso> public virtual PutBotResponse PutBot(PutBotRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = PutBotRequestMarshaller.Instance; options.ResponseUnmarshaller = PutBotResponseUnmarshaller.Instance; return Invoke<PutBotResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the PutBot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutBot operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutBot /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBot">REST API Reference for PutBot Operation</seealso> public virtual IAsyncResult BeginPutBot(PutBotRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = PutBotRequestMarshaller.Instance; options.ResponseUnmarshaller = PutBotResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutBot operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutBot.</param> /// /// <returns>Returns a PutBotResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBot">REST API Reference for PutBot Operation</seealso> public virtual PutBotResponse EndPutBot(IAsyncResult asyncResult) { return EndInvoke<PutBotResponse>(asyncResult); } #endregion #region PutBotAlias /// <summary> /// Creates an alias for the specified version of the bot or replaces an alias for the /// specified bot. To change the version of the bot that the alias points to, replace /// the alias. For more information about aliases, see <a>versioning-aliases</a>. /// /// /// <para> /// This operation requires permissions for the <code>lex:PutBotAlias</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutBotAlias service method.</param> /// /// <returns>The response from the PutBotAlias service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.PreconditionFailedException"> /// The checksum of the resource that you are trying to change does not match the checksum /// in the request. Check the resource's checksum and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBotAlias">REST API Reference for PutBotAlias Operation</seealso> public virtual PutBotAliasResponse PutBotAlias(PutBotAliasRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = PutBotAliasRequestMarshaller.Instance; options.ResponseUnmarshaller = PutBotAliasResponseUnmarshaller.Instance; return Invoke<PutBotAliasResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the PutBotAlias operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutBotAlias operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutBotAlias /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBotAlias">REST API Reference for PutBotAlias Operation</seealso> public virtual IAsyncResult BeginPutBotAlias(PutBotAliasRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = PutBotAliasRequestMarshaller.Instance; options.ResponseUnmarshaller = PutBotAliasResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutBotAlias operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutBotAlias.</param> /// /// <returns>Returns a PutBotAliasResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBotAlias">REST API Reference for PutBotAlias Operation</seealso> public virtual PutBotAliasResponse EndPutBotAlias(IAsyncResult asyncResult) { return EndInvoke<PutBotAliasResponse>(asyncResult); } #endregion #region PutIntent /// <summary> /// Creates an intent or replaces an existing intent. /// /// /// <para> /// To define the interaction between the user and your bot, you use one or more intents. /// For a pizza ordering bot, for example, you would create an <code>OrderPizza</code> /// intent. /// </para> /// /// <para> /// To create an intent or replace an existing intent, you must provide the following: /// </para> /// <ul> <li> /// <para> /// Intent name. For example, <code>OrderPizza</code>. /// </para> /// </li> <li> /// <para> /// Sample utterances. For example, "Can I order a pizza, please." and "I want to order /// a pizza." /// </para> /// </li> <li> /// <para> /// Information to be gathered. You specify slot types for the information that your bot /// will request from the user. You can specify standard slot types, such as a date or /// a time, or custom slot types such as the size and crust of a pizza. /// </para> /// </li> <li> /// <para> /// How the intent will be fulfilled. You can provide a Lambda function or configure the /// intent to return the intent information to the client application. If you use a Lambda /// function, when all of the intent information is available, Amazon Lex invokes your /// Lambda function. If you configure your intent to return the intent information to /// the client application. /// </para> /// </li> </ul> /// <para> /// You can specify other optional information in the request, such as: /// </para> /// <ul> <li> /// <para> /// A confirmation prompt to ask the user to confirm an intent. For example, "Shall I /// order your pizza?" /// </para> /// </li> <li> /// <para> /// A conclusion statement to send to the user after the intent has been fulfilled. For /// example, "I placed your pizza order." /// </para> /// </li> <li> /// <para> /// A follow-up prompt that asks the user for additional activity. For example, asking /// "Do you want to order a drink with your pizza?" /// </para> /// </li> </ul> /// <para> /// If you specify an existing intent name to update the intent, Amazon Lex replaces the /// values in the <code>$LATEST</code> version of the intent with the values in the request. /// Amazon Lex removes fields that you don't provide in the request. If you don't specify /// the required fields, Amazon Lex throws an exception. When you update the <code>$LATEST</code> /// version of an intent, the <code>status</code> field of any bot that uses the <code>$LATEST</code> /// version of the intent is set to <code>NOT_BUILT</code>. /// </para> /// /// <para> /// For more information, see <a>how-it-works</a>. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:PutIntent</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutIntent service method.</param> /// /// <returns>The response from the PutIntent service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.PreconditionFailedException"> /// The checksum of the resource that you are trying to change does not match the checksum /// in the request. Check the resource's checksum and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutIntent">REST API Reference for PutIntent Operation</seealso> public virtual PutIntentResponse PutIntent(PutIntentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = PutIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = PutIntentResponseUnmarshaller.Instance; return Invoke<PutIntentResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the PutIntent operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutIntent operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutIntent /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutIntent">REST API Reference for PutIntent Operation</seealso> public virtual IAsyncResult BeginPutIntent(PutIntentRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = PutIntentRequestMarshaller.Instance; options.ResponseUnmarshaller = PutIntentResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutIntent operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutIntent.</param> /// /// <returns>Returns a PutIntentResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutIntent">REST API Reference for PutIntent Operation</seealso> public virtual PutIntentResponse EndPutIntent(IAsyncResult asyncResult) { return EndInvoke<PutIntentResponse>(asyncResult); } #endregion #region PutSlotType /// <summary> /// Creates a custom slot type or replaces an existing custom slot type. /// /// /// <para> /// To create a custom slot type, specify a name for the slot type and a set of enumeration /// values, which are the values that a slot of this type can assume. For more information, /// see <a>how-it-works</a>. /// </para> /// /// <para> /// If you specify the name of an existing slot type, the fields in the request replace /// the existing values in the <code>$LATEST</code> version of the slot type. Amazon Lex /// removes the fields that you don't provide in the request. If you don't specify required /// fields, Amazon Lex throws an exception. When you update the <code>$LATEST</code> version /// of a slot type, if a bot uses the <code>$LATEST</code> version of an intent that contains /// the slot type, the bot's <code>status</code> field is set to <code>NOT_BUILT</code>. /// </para> /// /// <para> /// This operation requires permissions for the <code>lex:PutSlotType</code> action. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutSlotType service method.</param> /// /// <returns>The response from the PutSlotType service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.PreconditionFailedException"> /// The checksum of the resource that you are trying to change does not match the checksum /// in the request. Check the resource's checksum and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutSlotType">REST API Reference for PutSlotType Operation</seealso> public virtual PutSlotTypeResponse PutSlotType(PutSlotTypeRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = PutSlotTypeRequestMarshaller.Instance; options.ResponseUnmarshaller = PutSlotTypeResponseUnmarshaller.Instance; return Invoke<PutSlotTypeResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the PutSlotType operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutSlotType operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutSlotType /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutSlotType">REST API Reference for PutSlotType Operation</seealso> public virtual IAsyncResult BeginPutSlotType(PutSlotTypeRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = PutSlotTypeRequestMarshaller.Instance; options.ResponseUnmarshaller = PutSlotTypeResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PutSlotType operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutSlotType.</param> /// /// <returns>Returns a PutSlotTypeResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutSlotType">REST API Reference for PutSlotType Operation</seealso> public virtual PutSlotTypeResponse EndPutSlotType(IAsyncResult asyncResult) { return EndInvoke<PutSlotTypeResponse>(asyncResult); } #endregion #region StartImport /// <summary> /// Starts a job to import a resource to Amazon Lex. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartImport service method.</param> /// /// <returns>The response from the StartImport service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartImport">REST API Reference for StartImport Operation</seealso> public virtual StartImportResponse StartImport(StartImportRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartImportRequestMarshaller.Instance; options.ResponseUnmarshaller = StartImportResponseUnmarshaller.Instance; return Invoke<StartImportResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartImport operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartImport operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartImport /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartImport">REST API Reference for StartImport Operation</seealso> public virtual IAsyncResult BeginStartImport(StartImportRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartImportRequestMarshaller.Instance; options.ResponseUnmarshaller = StartImportResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartImport operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartImport.</param> /// /// <returns>Returns a StartImportResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartImport">REST API Reference for StartImport Operation</seealso> public virtual StartImportResponse EndStartImport(IAsyncResult asyncResult) { return EndInvoke<StartImportResponse>(asyncResult); } #endregion #region StartMigration /// <summary> /// Starts migrating a bot from Amazon Lex V1 to Amazon Lex V2. Migrate your bot when /// you want to take advantage of the new features of Amazon Lex V2. /// /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/lex/latest/dg/migrate.html">Migrating /// a bot</a> in the <i>Amazon Lex developer guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartMigration service method.</param> /// /// <returns>The response from the StartMigration service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.AccessDeniedException"> /// Your IAM user or role does not have permission to call the Amazon Lex V2 APIs required /// to migrate your bot. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartMigration">REST API Reference for StartMigration Operation</seealso> public virtual StartMigrationResponse StartMigration(StartMigrationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartMigrationRequestMarshaller.Instance; options.ResponseUnmarshaller = StartMigrationResponseUnmarshaller.Instance; return Invoke<StartMigrationResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the StartMigration operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartMigration operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartMigration /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartMigration">REST API Reference for StartMigration Operation</seealso> public virtual IAsyncResult BeginStartMigration(StartMigrationRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = StartMigrationRequestMarshaller.Instance; options.ResponseUnmarshaller = StartMigrationResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the StartMigration operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartMigration.</param> /// /// <returns>Returns a StartMigrationResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartMigration">REST API Reference for StartMigration Operation</seealso> public virtual StartMigrationResponse EndStartMigration(IAsyncResult asyncResult) { return EndInvoke<StartMigrationResponse>(asyncResult); } #endregion #region TagResource /// <summary> /// Adds the specified tags to the specified resource. If a tag key already exists, the /// existing value is replaced with the new value. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// /// <returns>The response from the TagResource service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/TagResource">REST API Reference for TagResource Operation</seealso> public virtual TagResourceResponse TagResource(TagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return Invoke<TagResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the TagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/TagResource">REST API Reference for TagResource Operation</seealso> public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the TagResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param> /// /// <returns>Returns a TagResourceResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/TagResource">REST API Reference for TagResource Operation</seealso> public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult) { return EndInvoke<TagResourceResponse>(asyncResult); } #endregion #region UntagResource /// <summary> /// Removes tags from a bot, bot alias or bot channel. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// /// <returns>The response from the UntagResource service method, as returned by LexModelBuildingService.</returns> /// <exception cref="Amazon.LexModelBuildingService.Model.BadRequestException"> /// The request is not well formed. For example, a value is invalid or a required field /// is missing. Check the field values, and try again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.ConflictException"> /// There was a conflict processing the request. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.InternalFailureException"> /// An internal Amazon Lex error occurred. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.LimitExceededException"> /// The request exceeded a limit. Try your request again. /// </exception> /// <exception cref="Amazon.LexModelBuildingService.Model.NotFoundException"> /// The resource specified in the request was not found. Check the resource and try again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual UntagResourceResponse UntagResource(UntagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return Invoke<UntagResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the UntagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonLexModelBuildingServiceClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the UntagResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param> /// /// <returns>Returns a UntagResourceResult from LexModelBuildingService.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult) { return EndInvoke<UntagResourceResponse>(asyncResult); } #endregion } }
56.289362
187
0.662421
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/LexModelBuildingService/Generated/_bcl35/AmazonLexModelBuildingServiceClient.cs
211,648
C#
using System; using System.Collections.Generic; using System.Linq; namespace SolidStack.Core.Flow.Internal { internal abstract class ActionableVoid<TSelf> : IActionable where TSelf : ActionableVoid<TSelf> { protected ActionableVoid(params Action[] actions) : this(actions.AsEnumerable()) { } protected ActionableVoid(IEnumerable<Action> actions) => Actions = actions.ToList(); private List<Action> Actions { get; } public void Execute() => Actions.ForEach(action => action()); protected IFilteredActionableVoid<TSelf> AppendNextAction() => new FilteredActionableVoid<TSelf>((TSelf) this, Actions.Add); protected IFilteredActionableVoid<TSelf> SkipNextAction() => new FilteredActionableVoid<TSelf>((TSelf) this, _ => { }); protected IFilteredActionableContent<TContent, TSelf> SkipNextContentAction<TContent>() => new FilteredActionableContent<TContent, TSelf>((TSelf) this, _ => { }); } }
32.363636
98
0.648876
[ "MIT" ]
idmobiles/solidstack
src/SolidStack.Core.Flow/Internal/ActionableVoid.cs
1,070
C#
using System.Collections.Generic; using System.Linq; using Terraria; using Terraria.ID; namespace MagicStorageExtra.Sorting { public abstract class ItemFilter { public abstract bool Passes(Item item); public bool Passes(object obj) { switch (obj) { case Item item: return Passes(item); case Recipe recipe: return Passes(recipe.createItem); default: return false; } } } public class FilterAll : ItemFilter { public override bool Passes(Item item) => true; } public class FilterWeaponMelee : ItemFilter { public override bool Passes(Item item) => (item.melee || item.thrown && !item.consumable) && item.pick == 0 && item.axe == 0 && item.hammer == 0 && item.damage > 0; } public class FilterWeaponRanged : ItemFilter { private readonly FilterWeaponThrown _thrown = new FilterWeaponThrown(); public override bool Passes(Item item) => item.ranged && item.damage > 0 && item.ammo <= 0 && !_thrown.Passes(item); } public class FilterWeaponMagic : ItemFilter { public override bool Passes(Item item) => (item.magic || item.mana > 0) && !item.summon && !item.consumable; } public class FilterWeaponSummon : ItemFilter { public override bool Passes(Item item) { switch (item.type) { case ItemID.LifeCrystal: case ItemID.ManaCrystal: case ItemID.CellPhone: case ItemID.PDA: case ItemID.MagicMirror: case ItemID.IceMirror: return false; } return item.summon || SortClassList.BossSpawn(item) || SortClassList.Cart(item) || SortClassList.LightPet(item) || SortClassList.Mount(item) || item.sentry; } } public class FilterWeaponThrown : ItemFilter { public override bool Passes(Item item) { switch (item.type) { case ItemID.Dynamite: case ItemID.StickyDynamite: case ItemID.BouncyDynamite: case ItemID.Bomb: case ItemID.StickyBomb: case ItemID.BouncyBomb: return true; } return item.thrown && item.damage > 0 || item.consumable && item.Name.ToLowerInvariant().EndsWith(" coating"); } } public class FilterAmmo : ItemFilter { public override bool Passes(Item item) => item.ammo > 0 && item.damage > 0 && item.ammo != AmmoID.Coin; } public class FilterVanity : ItemFilter { public override bool Passes(Item item) => item.vanity || SortClassList.Dye(item) || SortClassList.HairDye(item) || SortClassList.VanityPet(item); } public class FilterOtherWeapon : ItemFilter { public override bool Passes(Item item) => !item.melee && !item.ranged && !item.magic && !item.summon && !item.thrown && item.damage > 0; } public class FilterWeapon : ItemFilter { public override bool Passes(Item item) => !(item.consumable && item.thrown) && (item.damage > 0 || item.magic && item.healLife > 0 && item.mana > 0) && item.pick == 0 && item.axe == 0 && item.hammer == 0; } public class FilterPickaxe : ItemFilter { public override bool Passes(Item item) => item.pick > 0; } public class FilterAxe : ItemFilter { public override bool Passes(Item item) => item.axe > 0; } public class FilterHammer : ItemFilter { public override bool Passes(Item item) => item.hammer > 0; } public class FilterTool : ItemFilter { public override bool Passes(Item item) => item.pick > 0 || item.axe > 0 || item.hammer > 0; } public class FilterArmor : ItemFilter { public override bool Passes(Item item) => !item.vanity && (item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0); } public class FilterEquipment : ItemFilter { public override bool Passes(Item item) => !item.vanity && (item.accessory || Main.projHook[item.shoot] || item.mountType >= 0 || item.buffType > 0 && (Main.lightPet[item.buffType] || Main.vanityPet[item.buffType])); } public class FilterPotion : ItemFilter { public override bool Passes(Item item) => item.consumable && (item.healLife > 0 || item.healMana > 0 || item.buffType > 0 || item.potion || item.Name.ToLowerInvariant().Contains("potion") || item.Name.ToLowerInvariant().Contains("elixir")); } public class FilterPlaceable : ItemFilter { public override bool Passes(Item item) => item.createTile >= TileID.Dirt || item.createWall > 0; } public class FilterMisc : ItemFilter { private static readonly List<ItemFilter> blacklist = new List<ItemFilter> { new FilterWeaponMelee(), new FilterWeaponRanged(), new FilterWeaponMagic(), new FilterWeaponSummon(), new FilterWeaponThrown(), new FilterAmmo(), new FilterWeaponThrown(), new FilterVanity(), new FilterTool(), new FilterArmor(), new FilterEquipment(), new FilterPotion(), new FilterPlaceable() }; public override bool Passes(Item item) { return blacklist.All(filter => !filter.Passes(item)); } } }
27.627907
242
0.687079
[ "MIT" ]
ExterminatorX99/MagicStorage
Sorting/ItemFilter.cs
4,752
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 Microsoft.Win32.SafeHandles; namespace System.Threading { public static class WaitHandleExtensions { /// <summary> /// Gets the native operating system handle. /// </summary> /// <param name="waitHandle">The <see cref="System.Threading.WaitHandle"/> to operate on.</param> /// <returns>A <see cref="System.Runtime.InteropServices.SafeHandle"/> representing the native operating system handle.</returns> public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle) { if (waitHandle == null) { throw new ArgumentNullException(nameof(waitHandle)); } return waitHandle.SafeWaitHandle!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } /// <summary> /// Sets the native operating system handle /// </summary> /// <param name="waitHandle">The <see cref="System.Threading.WaitHandle"/> to operate on.</param> /// <param name="value">A <see cref="System.Runtime.InteropServices.SafeHandle"/> representing the native operating system handle.</param> public static void SetSafeWaitHandle(this WaitHandle waitHandle, SafeWaitHandle? value) { if (waitHandle == null) { throw new ArgumentNullException(nameof(waitHandle)); } waitHandle.SafeWaitHandle = value!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } } }
41.309524
146
0.645533
[ "MIT" ]
RobSiklos/corefx
src/System.Runtime/src/System/Threading/WaitHandleExtensions.cs
1,735
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 DLaB.Xrm.Entities { [System.Runtime.Serialization.DataContractAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")] public enum msdyn_rtvState { [System.Runtime.Serialization.EnumMemberAttribute()] Active = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Inactive = 1, } /// <summary> /// Records RTVs for products to be retuned to vendors /// </summary> [System.Runtime.Serialization.DataContractAttribute()] [Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("msdyn_rtv")] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")] public partial class msdyn_rtv : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged { public static class Fields { public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string ExchangeRate = "exchangerate"; public const string ImportSequenceNumber = "importsequencenumber"; public const string ModifiedBy = "modifiedby"; public const string ModifiedOn = "modifiedon"; public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; public const string msdyn_Address1 = "msdyn_address1"; public const string msdyn_Address2 = "msdyn_address2"; public const string msdyn_Address3 = "msdyn_address3"; public const string msdyn_ApprovedDeclinedBy = "msdyn_approveddeclinedby"; public const string msdyn_Booking = "msdyn_booking"; public const string msdyn_City = "msdyn_city"; public const string msdyn_Country = "msdyn_country"; public const string msdyn_Latitude = "msdyn_latitude"; public const string msdyn_Longitude = "msdyn_longitude"; public const string msdyn_name = "msdyn_name"; public const string msdyn_OriginalPurchaseOrder = "msdyn_originalpurchaseorder"; public const string msdyn_OriginatingRMA = "msdyn_originatingrma"; public const string msdyn_PostalCode = "msdyn_postalcode"; public const string msdyn_ReferenceNo = "msdyn_referenceno"; public const string msdyn_RequestDate = "msdyn_requestdate"; public const string msdyn_ReturnDate = "msdyn_returndate"; public const string msdyn_ReturnedBy = "msdyn_returnedby"; public const string msdyn_rtvId = "msdyn_rtvid"; public const string Id = "msdyn_rtvid"; public const string msdyn_ShipVia = "msdyn_shipvia"; public const string msdyn_StateOrProvince = "msdyn_stateorprovince"; public const string msdyn_SubStatus = "msdyn_substatus"; public const string msdyn_SystemStatus = "msdyn_systemstatus"; public const string msdyn_TaxCode = "msdyn_taxcode"; public const string msdyn_TotalAmount = "msdyn_totalamount"; public const string msdyn_totalamount_Base = "msdyn_totalamount_base"; public const string msdyn_Vendor = "msdyn_vendor"; public const string msdyn_VendorContact = "msdyn_vendorcontact"; public const string msdyn_VendorRMA = "msdyn_vendorrma"; public const string msdyn_WorkOrder = "msdyn_workorder"; public const string OverriddenCreatedOn = "overriddencreatedon"; public const string OwnerId = "ownerid"; public const string OwningBusinessUnit = "owningbusinessunit"; public const string OwningTeam = "owningteam"; public const string OwningUser = "owninguser"; public const string StateCode = "statecode"; public const string StatusCode = "statuscode"; public const string TimeZoneRuleVersionNumber = "timezoneruleversionnumber"; public const string TransactionCurrencyId = "transactioncurrencyid"; public const string UTCConversionTimeZoneCode = "utcconversiontimezonecode"; public const string VersionNumber = "versionnumber"; public const string business_unit_msdyn_rtv = "business_unit_msdyn_rtv"; public const string lk_msdyn_rtv_createdby = "lk_msdyn_rtv_createdby"; public const string lk_msdyn_rtv_createdonbehalfby = "lk_msdyn_rtv_createdonbehalfby"; public const string lk_msdyn_rtv_modifiedby = "lk_msdyn_rtv_modifiedby"; public const string lk_msdyn_rtv_modifiedonbehalfby = "lk_msdyn_rtv_modifiedonbehalfby"; public const string msdyn_account_msdyn_rtv_Vendor = "msdyn_account_msdyn_rtv_Vendor"; public const string msdyn_bookableresourcebooking_msdyn_rtv_Booking = "msdyn_bookableresourcebooking_msdyn_rtv_Booking"; public const string msdyn_contact_msdyn_rtv_VendorContact = "msdyn_contact_msdyn_rtv_VendorContact"; public const string msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO = "msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO"; public const string msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA = "msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA"; public const string msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus = "msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus"; public const string msdyn_msdyn_shipvia_msdyn_rtv_ShipVia = "msdyn_msdyn_shipvia_msdyn_rtv_ShipVia"; public const string msdyn_msdyn_taxcode_msdyn_rtv_TaxCode = "msdyn_msdyn_taxcode_msdyn_rtv_TaxCode"; public const string msdyn_msdyn_workorder_msdyn_rtv_WorkOrder = "msdyn_msdyn_workorder_msdyn_rtv_WorkOrder"; public const string msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy = "msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy"; public const string msdyn_systemuser_msdyn_rtv_ReturnedBy = "msdyn_systemuser_msdyn_rtv_ReturnedBy"; public const string team_msdyn_rtv = "team_msdyn_rtv"; public const string TransactionCurrency_msdyn_rtv = "TransactionCurrency_msdyn_rtv"; public const string user_msdyn_rtv = "user_msdyn_rtv"; } /// <summary> /// Default Constructor. /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public msdyn_rtv() : base(EntityLogicalName) { } public const string EntityLogicalName = "msdyn_rtv"; public const string PrimaryIdAttribute = "msdyn_rtvid"; public const string PrimaryNameAttribute = "msdyn_name"; public const int EntityTypeCode = 10163; public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanged(string propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanging(string propertyName) { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName)); } } /// <summary> /// Unique identifier of the user who created the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] public Microsoft.Xrm.Sdk.EntityReference CreatedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedBy"); this.SetAttributeValue("createdby", value); this.OnPropertyChanged("CreatedBy"); } } /// <summary> /// Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")] public System.Nullable<System.DateTime> CreatedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdon"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedOn"); this.SetAttributeValue("createdon", value); this.OnPropertyChanged("CreatedOn"); } } /// <summary> /// Shows who created the record on behalf of another user. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedOnBehalfBy"); this.SetAttributeValue("createdonbehalfby", value); this.OnPropertyChanged("CreatedOnBehalfBy"); } } /// <summary> /// Shows the exchange rate for the currency associated with the entity with respect to the base currency. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("exchangerate")] public System.Nullable<decimal> ExchangeRate { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<decimal>>("exchangerate"); } } /// <summary> /// Shows the sequence number of the import that created this record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("importsequencenumber")] public System.Nullable<int> ImportSequenceNumber { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("importsequencenumber"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ImportSequenceNumber"); this.SetAttributeValue("importsequencenumber", value); this.OnPropertyChanged("ImportSequenceNumber"); } } /// <summary> /// Unique identifier of the user who modified the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")] public Microsoft.Xrm.Sdk.EntityReference ModifiedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ModifiedBy"); this.SetAttributeValue("modifiedby", value); this.OnPropertyChanged("ModifiedBy"); } } /// <summary> /// Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")] public System.Nullable<System.DateTime> ModifiedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("modifiedon"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ModifiedOn"); this.SetAttributeValue("modifiedon", value); this.OnPropertyChanged("ModifiedOn"); } } /// <summary> /// Shows who last updated the record on behalf of another user. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")] public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedonbehalfby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ModifiedOnBehalfBy"); this.SetAttributeValue("modifiedonbehalfby", value); this.OnPropertyChanged("ModifiedOnBehalfBy"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_address1")] public string msdyn_Address1 { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_address1"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Address1"); this.SetAttributeValue("msdyn_address1", value); this.OnPropertyChanged("msdyn_Address1"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_address2")] public string msdyn_Address2 { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_address2"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Address2"); this.SetAttributeValue("msdyn_address2", value); this.OnPropertyChanged("msdyn_Address2"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_address3")] public string msdyn_Address3 { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_address3"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Address3"); this.SetAttributeValue("msdyn_address3", value); this.OnPropertyChanged("msdyn_Address3"); } } /// <summary> /// The user who approved or rejected this return /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_approveddeclinedby")] public Microsoft.Xrm.Sdk.EntityReference msdyn_ApprovedDeclinedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_approveddeclinedby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_ApprovedDeclinedBy"); this.SetAttributeValue("msdyn_approveddeclinedby", value); this.OnPropertyChanged("msdyn_ApprovedDeclinedBy"); } } /// <summary> /// Unique identifier for Resource Booking associated with RTV. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_booking")] public Microsoft.Xrm.Sdk.EntityReference msdyn_Booking { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_booking"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Booking"); this.SetAttributeValue("msdyn_booking", value); this.OnPropertyChanged("msdyn_Booking"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_city")] public string msdyn_City { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_city"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_City"); this.SetAttributeValue("msdyn_city", value); this.OnPropertyChanged("msdyn_City"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_country")] public string msdyn_Country { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_country"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Country"); this.SetAttributeValue("msdyn_country", value); this.OnPropertyChanged("msdyn_Country"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_latitude")] public System.Nullable<double> msdyn_Latitude { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<double>>("msdyn_latitude"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Latitude"); this.SetAttributeValue("msdyn_latitude", value); this.OnPropertyChanged("msdyn_Latitude"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_longitude")] public System.Nullable<double> msdyn_Longitude { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<double>>("msdyn_longitude"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Longitude"); this.SetAttributeValue("msdyn_longitude", value); this.OnPropertyChanged("msdyn_Longitude"); } } /// <summary> /// Shows the unique number for identifying this RTV record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_name")] public string msdyn_name { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_name"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_name"); this.SetAttributeValue("msdyn_name", value); this.OnPropertyChanged("msdyn_name"); } } /// <summary> /// Purchase Order from where items are originating /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_originalpurchaseorder")] public Microsoft.Xrm.Sdk.EntityReference msdyn_OriginalPurchaseOrder { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_originalpurchaseorder"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_OriginalPurchaseOrder"); this.SetAttributeValue("msdyn_originalpurchaseorder", value); this.OnPropertyChanged("msdyn_OriginalPurchaseOrder"); } } /// <summary> /// Originating RMA if items were returned from customer /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_originatingrma")] public Microsoft.Xrm.Sdk.EntityReference msdyn_OriginatingRMA { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_originatingrma"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_OriginatingRMA"); this.SetAttributeValue("msdyn_originatingrma", value); this.OnPropertyChanged("msdyn_OriginatingRMA"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_postalcode")] public string msdyn_PostalCode { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_postalcode"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_PostalCode"); this.SetAttributeValue("msdyn_postalcode", value); this.OnPropertyChanged("msdyn_PostalCode"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_referenceno")] public string msdyn_ReferenceNo { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_referenceno"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_ReferenceNo"); this.SetAttributeValue("msdyn_referenceno", value); this.OnPropertyChanged("msdyn_ReferenceNo"); } } /// <summary> /// Enter the date when return was requested. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_requestdate")] public System.Nullable<System.DateTime> msdyn_RequestDate { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("msdyn_requestdate"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_RequestDate"); this.SetAttributeValue("msdyn_requestdate", value); this.OnPropertyChanged("msdyn_RequestDate"); } } /// <summary> /// Enter the date items were returned to vendor. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_returndate")] public System.Nullable<System.DateTime> msdyn_ReturnDate { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("msdyn_returndate"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_ReturnDate"); this.SetAttributeValue("msdyn_returndate", value); this.OnPropertyChanged("msdyn_ReturnDate"); } } /// <summary> /// User processing this return /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_returnedby")] public Microsoft.Xrm.Sdk.EntityReference msdyn_ReturnedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_returnedby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_ReturnedBy"); this.SetAttributeValue("msdyn_returnedby", value); this.OnPropertyChanged("msdyn_ReturnedBy"); } } /// <summary> /// Shows the entity instances. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_rtvid")] public System.Nullable<System.Guid> msdyn_rtvId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("msdyn_rtvid"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtvId"); this.SetAttributeValue("msdyn_rtvid", value); if (value.HasValue) { base.Id = value.Value; } else { base.Id = System.Guid.Empty; } this.OnPropertyChanged("msdyn_rtvId"); } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_rtvid")] public override System.Guid Id { [System.Diagnostics.DebuggerNonUserCode()] get { return base.Id; } [System.Diagnostics.DebuggerNonUserCode()] set { this.msdyn_rtvId = value; } } /// <summary> /// Method of Shipment to Vendor /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_shipvia")] public Microsoft.Xrm.Sdk.EntityReference msdyn_ShipVia { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_shipvia"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_ShipVia"); this.SetAttributeValue("msdyn_shipvia", value); this.OnPropertyChanged("msdyn_ShipVia"); } } /// <summary> /// /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_stateorprovince")] public string msdyn_StateOrProvince { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_stateorprovince"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_StateOrProvince"); this.SetAttributeValue("msdyn_stateorprovince", value); this.OnPropertyChanged("msdyn_StateOrProvince"); } } /// <summary> /// RTV Sub-Status /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_substatus")] public Microsoft.Xrm.Sdk.EntityReference msdyn_SubStatus { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_substatus"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_SubStatus"); this.SetAttributeValue("msdyn_substatus", value); this.OnPropertyChanged("msdyn_SubStatus"); } } /// <summary> /// Enter the current status of the RTV. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_systemstatus")] public Microsoft.Xrm.Sdk.OptionSetValue msdyn_SystemStatus { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("msdyn_systemstatus"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_SystemStatus"); this.SetAttributeValue("msdyn_systemstatus", value); this.OnPropertyChanged("msdyn_SystemStatus"); } } /// <summary> /// Tax code vendor charges you /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_taxcode")] public Microsoft.Xrm.Sdk.EntityReference msdyn_TaxCode { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_taxcode"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_TaxCode"); this.SetAttributeValue("msdyn_taxcode", value); this.OnPropertyChanged("msdyn_TaxCode"); } } /// <summary> /// Shows the total Amount to be credited on this RTV. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_totalamount")] public Microsoft.Xrm.Sdk.Money msdyn_TotalAmount { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.Money>("msdyn_totalamount"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_TotalAmount"); this.SetAttributeValue("msdyn_totalamount", value); this.OnPropertyChanged("msdyn_TotalAmount"); } } /// <summary> /// Shows the value of the total amount in the base currency. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_totalamount_base")] public Microsoft.Xrm.Sdk.Money msdyn_totalamount_Base { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.Money>("msdyn_totalamount_base"); } } /// <summary> /// Vendor where items will be returned /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_vendor")] public Microsoft.Xrm.Sdk.EntityReference msdyn_Vendor { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_vendor"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_Vendor"); this.SetAttributeValue("msdyn_vendor", value); this.OnPropertyChanged("msdyn_Vendor"); } } /// <summary> /// Contact person at Vendor /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_vendorcontact")] public Microsoft.Xrm.Sdk.EntityReference msdyn_VendorContact { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_vendorcontact"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_VendorContact"); this.SetAttributeValue("msdyn_vendorcontact", value); this.OnPropertyChanged("msdyn_VendorContact"); } } /// <summary> /// RMA from Vendor /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_vendorrma")] public string msdyn_VendorRMA { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("msdyn_vendorrma"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_VendorRMA"); this.SetAttributeValue("msdyn_vendorrma", value); this.OnPropertyChanged("msdyn_VendorRMA"); } } /// <summary> /// Unique identifier for Work Order associated with RTV. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_workorder")] public Microsoft.Xrm.Sdk.EntityReference msdyn_WorkOrder { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_workorder"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_WorkOrder"); this.SetAttributeValue("msdyn_workorder", value); this.OnPropertyChanged("msdyn_WorkOrder"); } } /// <summary> /// Shows the date and time that the record was migrated. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overriddencreatedon")] public System.Nullable<System.DateTime> OverriddenCreatedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("overriddencreatedon"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("OverriddenCreatedOn"); this.SetAttributeValue("overriddencreatedon", value); this.OnPropertyChanged("OverriddenCreatedOn"); } } /// <summary> /// Owner Id /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("ownerid")] public Microsoft.Xrm.Sdk.EntityReference OwnerId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("ownerid"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("OwnerId"); this.SetAttributeValue("ownerid", value); this.OnPropertyChanged("OwnerId"); } } /// <summary> /// Unique identifier for the business unit that owns the record /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningbusinessunit")] public Microsoft.Xrm.Sdk.EntityReference OwningBusinessUnit { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owningbusinessunit"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("OwningBusinessUnit"); this.SetAttributeValue("owningbusinessunit", value); this.OnPropertyChanged("OwningBusinessUnit"); } } /// <summary> /// Unique identifier for the team that owns the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningteam")] public Microsoft.Xrm.Sdk.EntityReference OwningTeam { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owningteam"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("OwningTeam"); this.SetAttributeValue("owningteam", value); this.OnPropertyChanged("OwningTeam"); } } /// <summary> /// Unique identifier for the user that owns the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owninguser")] public Microsoft.Xrm.Sdk.EntityReference OwningUser { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owninguser"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("OwningUser"); this.SetAttributeValue("owninguser", value); this.OnPropertyChanged("OwningUser"); } } /// <summary> /// Status of the RTV /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statecode")] public System.Nullable<DLaB.Xrm.Entities.msdyn_rtvState> StateCode { [System.Diagnostics.DebuggerNonUserCode()] get { Microsoft.Xrm.Sdk.OptionSetValue optionSet = this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("statecode"); if ((optionSet != null)) { return ((DLaB.Xrm.Entities.msdyn_rtvState)(System.Enum.ToObject(typeof(DLaB.Xrm.Entities.msdyn_rtvState), optionSet.Value))); } else { return null; } } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("StateCode"); if ((value == null)) { this.SetAttributeValue("statecode", null); } else { this.SetAttributeValue("statecode", new Microsoft.Xrm.Sdk.OptionSetValue(((int)(value)))); } this.OnPropertyChanged("StateCode"); } } /// <summary> /// Reason for the status of the RTV /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statuscode")] public Microsoft.Xrm.Sdk.OptionSetValue StatusCode { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("statuscode"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("StatusCode"); this.SetAttributeValue("statuscode", value); this.OnPropertyChanged("StatusCode"); } } /// <summary> /// For internal use only. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("timezoneruleversionnumber")] public System.Nullable<int> TimeZoneRuleVersionNumber { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("timezoneruleversionnumber"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("TimeZoneRuleVersionNumber"); this.SetAttributeValue("timezoneruleversionnumber", value); this.OnPropertyChanged("TimeZoneRuleVersionNumber"); } } /// <summary> /// Unique identifier of the currency associated with the entity. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("transactioncurrencyid")] public Microsoft.Xrm.Sdk.EntityReference TransactionCurrencyId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("transactioncurrencyid"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("TransactionCurrencyId"); this.SetAttributeValue("transactioncurrencyid", value); this.OnPropertyChanged("TransactionCurrencyId"); } } /// <summary> /// Shows the time zone code that was in use when the record was created. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("utcconversiontimezonecode")] public System.Nullable<int> UTCConversionTimeZoneCode { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("utcconversiontimezonecode"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("UTCConversionTimeZoneCode"); this.SetAttributeValue("utcconversiontimezonecode", value); this.OnPropertyChanged("UTCConversionTimeZoneCode"); } } /// <summary> /// Version Number /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")] public System.Nullable<long> VersionNumber { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<long>>("versionnumber"); } } /// <summary> /// 1:N msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_rmareceiptproduct> msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_rmareceiptproduct>("msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV"); this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_rmareceiptproduct>("msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV", null, value); this.OnPropertyChanged("msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV"); } } /// <summary> /// 1:N msdyn_msdyn_rtv_msdyn_rtvproduct_RTV /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_rtv_msdyn_rtvproduct_RTV")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_rtvproduct> msdyn_msdyn_rtv_msdyn_rtvproduct_RTV { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_rtvproduct>("msdyn_msdyn_rtv_msdyn_rtvproduct_RTV", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_rtv_msdyn_rtvproduct_RTV"); this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_rtvproduct>("msdyn_msdyn_rtv_msdyn_rtvproduct_RTV", null, value); this.OnPropertyChanged("msdyn_msdyn_rtv_msdyn_rtvproduct_RTV"); } } /// <summary> /// 1:N msdyn_rtv_ActivityPointers /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_ActivityPointers")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.ActivityPointer> msdyn_rtv_ActivityPointers { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.ActivityPointer>("msdyn_rtv_ActivityPointers", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_ActivityPointers"); this.SetRelatedEntities<DLaB.Xrm.Entities.ActivityPointer>("msdyn_rtv_ActivityPointers", null, value); this.OnPropertyChanged("msdyn_rtv_ActivityPointers"); } } /// <summary> /// 1:N msdyn_rtv_Annotations /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_Annotations")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Annotation> msdyn_rtv_Annotations { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Annotation>("msdyn_rtv_Annotations", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_Annotations"); this.SetRelatedEntities<DLaB.Xrm.Entities.Annotation>("msdyn_rtv_Annotations", null, value); this.OnPropertyChanged("msdyn_rtv_Annotations"); } } /// <summary> /// 1:N msdyn_rtv_Appointments /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_Appointments")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Appointment> msdyn_rtv_Appointments { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Appointment>("msdyn_rtv_Appointments", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_Appointments"); this.SetRelatedEntities<DLaB.Xrm.Entities.Appointment>("msdyn_rtv_Appointments", null, value); this.OnPropertyChanged("msdyn_rtv_Appointments"); } } /// <summary> /// 1:N msdyn_rtv_AsyncOperations /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_AsyncOperations")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.AsyncOperation> msdyn_rtv_AsyncOperations { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.AsyncOperation>("msdyn_rtv_AsyncOperations", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_AsyncOperations"); this.SetRelatedEntities<DLaB.Xrm.Entities.AsyncOperation>("msdyn_rtv_AsyncOperations", null, value); this.OnPropertyChanged("msdyn_rtv_AsyncOperations"); } } /// <summary> /// 1:N msdyn_rtv_BulkDeleteFailures /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_BulkDeleteFailures")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.BulkDeleteFailure> msdyn_rtv_BulkDeleteFailures { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.BulkDeleteFailure>("msdyn_rtv_BulkDeleteFailures", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_BulkDeleteFailures"); this.SetRelatedEntities<DLaB.Xrm.Entities.BulkDeleteFailure>("msdyn_rtv_BulkDeleteFailures", null, value); this.OnPropertyChanged("msdyn_rtv_BulkDeleteFailures"); } } /// <summary> /// 1:N msdyn_rtv_connections1 /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_connections1")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Connection> msdyn_rtv_connections1 { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Connection>("msdyn_rtv_connections1", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_connections1"); this.SetRelatedEntities<DLaB.Xrm.Entities.Connection>("msdyn_rtv_connections1", null, value); this.OnPropertyChanged("msdyn_rtv_connections1"); } } /// <summary> /// 1:N msdyn_rtv_connections2 /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_connections2")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Connection> msdyn_rtv_connections2 { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Connection>("msdyn_rtv_connections2", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_connections2"); this.SetRelatedEntities<DLaB.Xrm.Entities.Connection>("msdyn_rtv_connections2", null, value); this.OnPropertyChanged("msdyn_rtv_connections2"); } } /// <summary> /// 1:N msdyn_rtv_DuplicateBaseRecord /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_DuplicateBaseRecord")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.DuplicateRecord> msdyn_rtv_DuplicateBaseRecord { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_rtv_DuplicateBaseRecord", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_DuplicateBaseRecord"); this.SetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_rtv_DuplicateBaseRecord", null, value); this.OnPropertyChanged("msdyn_rtv_DuplicateBaseRecord"); } } /// <summary> /// 1:N msdyn_rtv_DuplicateMatchingRecord /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_DuplicateMatchingRecord")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.DuplicateRecord> msdyn_rtv_DuplicateMatchingRecord { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_rtv_DuplicateMatchingRecord", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_DuplicateMatchingRecord"); this.SetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_rtv_DuplicateMatchingRecord", null, value); this.OnPropertyChanged("msdyn_rtv_DuplicateMatchingRecord"); } } /// <summary> /// 1:N msdyn_rtv_Emails /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_Emails")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Email> msdyn_rtv_Emails { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Email>("msdyn_rtv_Emails", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_Emails"); this.SetRelatedEntities<DLaB.Xrm.Entities.Email>("msdyn_rtv_Emails", null, value); this.OnPropertyChanged("msdyn_rtv_Emails"); } } /// <summary> /// 1:N msdyn_rtv_Faxes /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_Faxes")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Fax> msdyn_rtv_Faxes { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Fax>("msdyn_rtv_Faxes", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_Faxes"); this.SetRelatedEntities<DLaB.Xrm.Entities.Fax>("msdyn_rtv_Faxes", null, value); this.OnPropertyChanged("msdyn_rtv_Faxes"); } } /// <summary> /// 1:N msdyn_rtv_Letters /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_Letters")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Letter> msdyn_rtv_Letters { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Letter>("msdyn_rtv_Letters", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_Letters"); this.SetRelatedEntities<DLaB.Xrm.Entities.Letter>("msdyn_rtv_Letters", null, value); this.OnPropertyChanged("msdyn_rtv_Letters"); } } /// <summary> /// 1:N msdyn_rtv_MailboxTrackingFolders /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_MailboxTrackingFolders")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.MailboxTrackingFolder> msdyn_rtv_MailboxTrackingFolders { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.MailboxTrackingFolder>("msdyn_rtv_MailboxTrackingFolders", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_MailboxTrackingFolders"); this.SetRelatedEntities<DLaB.Xrm.Entities.MailboxTrackingFolder>("msdyn_rtv_MailboxTrackingFolders", null, value); this.OnPropertyChanged("msdyn_rtv_MailboxTrackingFolders"); } } /// <summary> /// 1:N msdyn_rtv_msdyn_approvals /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_msdyn_approvals")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_approval> msdyn_rtv_msdyn_approvals { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_approval>("msdyn_rtv_msdyn_approvals", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_msdyn_approvals"); this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_approval>("msdyn_rtv_msdyn_approvals", null, value); this.OnPropertyChanged("msdyn_rtv_msdyn_approvals"); } } /// <summary> /// 1:N msdyn_rtv_msdyn_bookingalerts /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_msdyn_bookingalerts")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_bookingalert> msdyn_rtv_msdyn_bookingalerts { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_bookingalert>("msdyn_rtv_msdyn_bookingalerts", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_msdyn_bookingalerts"); this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_bookingalert>("msdyn_rtv_msdyn_bookingalerts", null, value); this.OnPropertyChanged("msdyn_rtv_msdyn_bookingalerts"); } } /// <summary> /// 1:N msdyn_rtv_PhoneCalls /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_PhoneCalls")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.PhoneCall> msdyn_rtv_PhoneCalls { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.PhoneCall>("msdyn_rtv_PhoneCalls", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_PhoneCalls"); this.SetRelatedEntities<DLaB.Xrm.Entities.PhoneCall>("msdyn_rtv_PhoneCalls", null, value); this.OnPropertyChanged("msdyn_rtv_PhoneCalls"); } } /// <summary> /// 1:N msdyn_rtv_PrincipalObjectAttributeAccesses /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_PrincipalObjectAttributeAccesses")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.PrincipalObjectAttributeAccess> msdyn_rtv_PrincipalObjectAttributeAccesses { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.PrincipalObjectAttributeAccess>("msdyn_rtv_PrincipalObjectAttributeAccesses", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_PrincipalObjectAttributeAccesses"); this.SetRelatedEntities<DLaB.Xrm.Entities.PrincipalObjectAttributeAccess>("msdyn_rtv_PrincipalObjectAttributeAccesses", null, value); this.OnPropertyChanged("msdyn_rtv_PrincipalObjectAttributeAccesses"); } } /// <summary> /// 1:N msdyn_rtv_ProcessSession /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_ProcessSession")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.ProcessSession> msdyn_rtv_ProcessSession { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.ProcessSession>("msdyn_rtv_ProcessSession", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_ProcessSession"); this.SetRelatedEntities<DLaB.Xrm.Entities.ProcessSession>("msdyn_rtv_ProcessSession", null, value); this.OnPropertyChanged("msdyn_rtv_ProcessSession"); } } /// <summary> /// 1:N msdyn_rtv_RecurringAppointmentMasters /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_RecurringAppointmentMasters")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.RecurringAppointmentMaster> msdyn_rtv_RecurringAppointmentMasters { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.RecurringAppointmentMaster>("msdyn_rtv_RecurringAppointmentMasters", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_RecurringAppointmentMasters"); this.SetRelatedEntities<DLaB.Xrm.Entities.RecurringAppointmentMaster>("msdyn_rtv_RecurringAppointmentMasters", null, value); this.OnPropertyChanged("msdyn_rtv_RecurringAppointmentMasters"); } } /// <summary> /// 1:N msdyn_rtv_ServiceAppointments /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_ServiceAppointments")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.ServiceAppointment> msdyn_rtv_ServiceAppointments { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.ServiceAppointment>("msdyn_rtv_ServiceAppointments", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_ServiceAppointments"); this.SetRelatedEntities<DLaB.Xrm.Entities.ServiceAppointment>("msdyn_rtv_ServiceAppointments", null, value); this.OnPropertyChanged("msdyn_rtv_ServiceAppointments"); } } /// <summary> /// 1:N msdyn_rtv_SharePointDocumentLocations /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_SharePointDocumentLocations")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.SharePointDocumentLocation> msdyn_rtv_SharePointDocumentLocations { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.SharePointDocumentLocation>("msdyn_rtv_SharePointDocumentLocations", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_SharePointDocumentLocations"); this.SetRelatedEntities<DLaB.Xrm.Entities.SharePointDocumentLocation>("msdyn_rtv_SharePointDocumentLocations", null, value); this.OnPropertyChanged("msdyn_rtv_SharePointDocumentLocations"); } } /// <summary> /// 1:N msdyn_rtv_SharePointDocuments /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_SharePointDocuments")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.SharePointDocument> msdyn_rtv_SharePointDocuments { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.SharePointDocument>("msdyn_rtv_SharePointDocuments", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_SharePointDocuments"); this.SetRelatedEntities<DLaB.Xrm.Entities.SharePointDocument>("msdyn_rtv_SharePointDocuments", null, value); this.OnPropertyChanged("msdyn_rtv_SharePointDocuments"); } } /// <summary> /// 1:N msdyn_rtv_SocialActivities /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_SocialActivities")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.SocialActivity> msdyn_rtv_SocialActivities { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.SocialActivity>("msdyn_rtv_SocialActivities", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_SocialActivities"); this.SetRelatedEntities<DLaB.Xrm.Entities.SocialActivity>("msdyn_rtv_SocialActivities", null, value); this.OnPropertyChanged("msdyn_rtv_SocialActivities"); } } /// <summary> /// 1:N msdyn_rtv_SyncErrors /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_SyncErrors")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.SyncError> msdyn_rtv_SyncErrors { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.SyncError>("msdyn_rtv_SyncErrors", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_SyncErrors"); this.SetRelatedEntities<DLaB.Xrm.Entities.SyncError>("msdyn_rtv_SyncErrors", null, value); this.OnPropertyChanged("msdyn_rtv_SyncErrors"); } } /// <summary> /// 1:N msdyn_rtv_Tasks /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_Tasks")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Task> msdyn_rtv_Tasks { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.Task>("msdyn_rtv_Tasks", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_Tasks"); this.SetRelatedEntities<DLaB.Xrm.Entities.Task>("msdyn_rtv_Tasks", null, value); this.OnPropertyChanged("msdyn_rtv_Tasks"); } } /// <summary> /// 1:N msdyn_rtv_UserEntityInstanceDatas /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_rtv_UserEntityInstanceDatas")] public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.UserEntityInstanceData> msdyn_rtv_UserEntityInstanceDatas { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<DLaB.Xrm.Entities.UserEntityInstanceData>("msdyn_rtv_UserEntityInstanceDatas", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_rtv_UserEntityInstanceDatas"); this.SetRelatedEntities<DLaB.Xrm.Entities.UserEntityInstanceData>("msdyn_rtv_UserEntityInstanceDatas", null, value); this.OnPropertyChanged("msdyn_rtv_UserEntityInstanceDatas"); } } /// <summary> /// N:1 business_unit_msdyn_rtv /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningbusinessunit")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("business_unit_msdyn_rtv")] public DLaB.Xrm.Entities.BusinessUnit business_unit_msdyn_rtv { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.BusinessUnit>("business_unit_msdyn_rtv", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("business_unit_msdyn_rtv"); this.SetRelatedEntity<DLaB.Xrm.Entities.BusinessUnit>("business_unit_msdyn_rtv", null, value); this.OnPropertyChanged("business_unit_msdyn_rtv"); } } /// <summary> /// N:1 lk_msdyn_rtv_createdby /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_rtv_createdby")] public DLaB.Xrm.Entities.SystemUser lk_msdyn_rtv_createdby { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_createdby", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("lk_msdyn_rtv_createdby"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_createdby", null, value); this.OnPropertyChanged("lk_msdyn_rtv_createdby"); } } /// <summary> /// N:1 lk_msdyn_rtv_createdonbehalfby /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_rtv_createdonbehalfby")] public DLaB.Xrm.Entities.SystemUser lk_msdyn_rtv_createdonbehalfby { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_createdonbehalfby", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("lk_msdyn_rtv_createdonbehalfby"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_createdonbehalfby", null, value); this.OnPropertyChanged("lk_msdyn_rtv_createdonbehalfby"); } } /// <summary> /// N:1 lk_msdyn_rtv_modifiedby /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_rtv_modifiedby")] public DLaB.Xrm.Entities.SystemUser lk_msdyn_rtv_modifiedby { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_modifiedby", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("lk_msdyn_rtv_modifiedby"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_modifiedby", null, value); this.OnPropertyChanged("lk_msdyn_rtv_modifiedby"); } } /// <summary> /// N:1 lk_msdyn_rtv_modifiedonbehalfby /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_rtv_modifiedonbehalfby")] public DLaB.Xrm.Entities.SystemUser lk_msdyn_rtv_modifiedonbehalfby { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_modifiedonbehalfby", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("lk_msdyn_rtv_modifiedonbehalfby"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_rtv_modifiedonbehalfby", null, value); this.OnPropertyChanged("lk_msdyn_rtv_modifiedonbehalfby"); } } /// <summary> /// N:1 msdyn_account_msdyn_rtv_Vendor /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_vendor")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_account_msdyn_rtv_Vendor")] public DLaB.Xrm.Entities.Account msdyn_account_msdyn_rtv_Vendor { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.Account>("msdyn_account_msdyn_rtv_Vendor", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_account_msdyn_rtv_Vendor"); this.SetRelatedEntity<DLaB.Xrm.Entities.Account>("msdyn_account_msdyn_rtv_Vendor", null, value); this.OnPropertyChanged("msdyn_account_msdyn_rtv_Vendor"); } } /// <summary> /// N:1 msdyn_bookableresourcebooking_msdyn_rtv_Booking /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_booking")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_bookableresourcebooking_msdyn_rtv_Booking")] public DLaB.Xrm.Entities.BookableResourceBooking msdyn_bookableresourcebooking_msdyn_rtv_Booking { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.BookableResourceBooking>("msdyn_bookableresourcebooking_msdyn_rtv_Booking", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_bookableresourcebooking_msdyn_rtv_Booking"); this.SetRelatedEntity<DLaB.Xrm.Entities.BookableResourceBooking>("msdyn_bookableresourcebooking_msdyn_rtv_Booking", null, value); this.OnPropertyChanged("msdyn_bookableresourcebooking_msdyn_rtv_Booking"); } } /// <summary> /// N:1 msdyn_contact_msdyn_rtv_VendorContact /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_vendorcontact")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_contact_msdyn_rtv_VendorContact")] public DLaB.Xrm.Entities.Contact msdyn_contact_msdyn_rtv_VendorContact { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.Contact>("msdyn_contact_msdyn_rtv_VendorContact", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_contact_msdyn_rtv_VendorContact"); this.SetRelatedEntity<DLaB.Xrm.Entities.Contact>("msdyn_contact_msdyn_rtv_VendorContact", null, value); this.OnPropertyChanged("msdyn_contact_msdyn_rtv_VendorContact"); } } /// <summary> /// N:1 msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_originalpurchaseorder")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO")] public DLaB.Xrm.Entities.msdyn_purchaseorder msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.msdyn_purchaseorder>("msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO"); this.SetRelatedEntity<DLaB.Xrm.Entities.msdyn_purchaseorder>("msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO", null, value); this.OnPropertyChanged("msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO"); } } /// <summary> /// N:1 msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_originatingrma")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA")] public DLaB.Xrm.Entities.msdyn_rma msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.msdyn_rma>("msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA"); this.SetRelatedEntity<DLaB.Xrm.Entities.msdyn_rma>("msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA", null, value); this.OnPropertyChanged("msdyn_msdyn_rma_msdyn_rtv_OriginatingRMA"); } } /// <summary> /// N:1 msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_substatus")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus")] public DLaB.Xrm.Entities.msdyn_rtvsubstatus msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.msdyn_rtvsubstatus>("msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus"); this.SetRelatedEntity<DLaB.Xrm.Entities.msdyn_rtvsubstatus>("msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus", null, value); this.OnPropertyChanged("msdyn_msdyn_rtvsubstatus_msdyn_rtv_SubStatus"); } } /// <summary> /// N:1 msdyn_msdyn_shipvia_msdyn_rtv_ShipVia /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_shipvia")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_shipvia_msdyn_rtv_ShipVia")] public DLaB.Xrm.Entities.msdyn_shipvia msdyn_msdyn_shipvia_msdyn_rtv_ShipVia { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.msdyn_shipvia>("msdyn_msdyn_shipvia_msdyn_rtv_ShipVia", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_shipvia_msdyn_rtv_ShipVia"); this.SetRelatedEntity<DLaB.Xrm.Entities.msdyn_shipvia>("msdyn_msdyn_shipvia_msdyn_rtv_ShipVia", null, value); this.OnPropertyChanged("msdyn_msdyn_shipvia_msdyn_rtv_ShipVia"); } } /// <summary> /// N:1 msdyn_msdyn_taxcode_msdyn_rtv_TaxCode /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_taxcode")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_taxcode_msdyn_rtv_TaxCode")] public DLaB.Xrm.Entities.msdyn_taxcode msdyn_msdyn_taxcode_msdyn_rtv_TaxCode { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.msdyn_taxcode>("msdyn_msdyn_taxcode_msdyn_rtv_TaxCode", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_taxcode_msdyn_rtv_TaxCode"); this.SetRelatedEntity<DLaB.Xrm.Entities.msdyn_taxcode>("msdyn_msdyn_taxcode_msdyn_rtv_TaxCode", null, value); this.OnPropertyChanged("msdyn_msdyn_taxcode_msdyn_rtv_TaxCode"); } } /// <summary> /// N:1 msdyn_msdyn_workorder_msdyn_rtv_WorkOrder /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_workorder")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_workorder_msdyn_rtv_WorkOrder")] public DLaB.Xrm.Entities.msdyn_workorder msdyn_msdyn_workorder_msdyn_rtv_WorkOrder { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.msdyn_workorder>("msdyn_msdyn_workorder_msdyn_rtv_WorkOrder", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_msdyn_workorder_msdyn_rtv_WorkOrder"); this.SetRelatedEntity<DLaB.Xrm.Entities.msdyn_workorder>("msdyn_msdyn_workorder_msdyn_rtv_WorkOrder", null, value); this.OnPropertyChanged("msdyn_msdyn_workorder_msdyn_rtv_WorkOrder"); } } /// <summary> /// N:1 msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_approveddeclinedby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy")] public DLaB.Xrm.Entities.SystemUser msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy", null, value); this.OnPropertyChanged("msdyn_systemuser_msdyn_rtv_ApprovedDeclinedBy"); } } /// <summary> /// N:1 msdyn_systemuser_msdyn_rtv_ReturnedBy /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_returnedby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_systemuser_msdyn_rtv_ReturnedBy")] public DLaB.Xrm.Entities.SystemUser msdyn_systemuser_msdyn_rtv_ReturnedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("msdyn_systemuser_msdyn_rtv_ReturnedBy", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("msdyn_systemuser_msdyn_rtv_ReturnedBy"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("msdyn_systemuser_msdyn_rtv_ReturnedBy", null, value); this.OnPropertyChanged("msdyn_systemuser_msdyn_rtv_ReturnedBy"); } } /// <summary> /// N:1 team_msdyn_rtv /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningteam")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_msdyn_rtv")] public DLaB.Xrm.Entities.Team team_msdyn_rtv { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.Team>("team_msdyn_rtv", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("team_msdyn_rtv"); this.SetRelatedEntity<DLaB.Xrm.Entities.Team>("team_msdyn_rtv", null, value); this.OnPropertyChanged("team_msdyn_rtv"); } } /// <summary> /// N:1 TransactionCurrency_msdyn_rtv /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("transactioncurrencyid")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("TransactionCurrency_msdyn_rtv")] public DLaB.Xrm.Entities.TransactionCurrency TransactionCurrency_msdyn_rtv { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.TransactionCurrency>("TransactionCurrency_msdyn_rtv", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("TransactionCurrency_msdyn_rtv"); this.SetRelatedEntity<DLaB.Xrm.Entities.TransactionCurrency>("TransactionCurrency_msdyn_rtv", null, value); this.OnPropertyChanged("TransactionCurrency_msdyn_rtv"); } } /// <summary> /// N:1 user_msdyn_rtv /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owninguser")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("user_msdyn_rtv")] public DLaB.Xrm.Entities.SystemUser user_msdyn_rtv { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("user_msdyn_rtv", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("user_msdyn_rtv"); this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("user_msdyn_rtv", null, value); this.OnPropertyChanged("user_msdyn_rtv"); } } /// <summary> /// Constructor for populating via LINQ queries given a LINQ anonymous type /// <param name="anonymousType">LINQ anonymous type.</param> /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public msdyn_rtv(object anonymousType) : this() { foreach (var p in anonymousType.GetType().GetProperties()) { var value = p.GetValue(anonymousType, null); var name = p.Name.ToLower(); if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum)) { value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value); name = name.Remove(name.Length - "enum".Length); } switch (name) { case "id": base.Id = (System.Guid)value; Attributes["msdyn_rtvid"] = base.Id; break; case "msdyn_rtvid": var id = (System.Nullable<System.Guid>) value; if(id == null){ continue; } base.Id = id.Value; Attributes[name] = base.Id; break; case "formattedvalues": // Add Support for FormattedValues FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value); break; default: Attributes[name] = value; break; } } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_systemstatus")] public virtual msdyn_RTVSystemStatus? msdyn_SystemStatusEnum { [System.Diagnostics.DebuggerNonUserCode()] get { return ((msdyn_RTVSystemStatus?)(EntityOptionSetEnum.GetEnum(this, "msdyn_systemstatus"))); } [System.Diagnostics.DebuggerNonUserCode()] set { msdyn_SystemStatus = value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null; } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statuscode")] public virtual msdyn_rtv_StatusCode? StatusCodeEnum { [System.Diagnostics.DebuggerNonUserCode()] get { return ((msdyn_rtv_StatusCode?)(EntityOptionSetEnum.GetEnum(this, "statuscode"))); } [System.Diagnostics.DebuggerNonUserCode()] set { StatusCode = value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null; } } } }
33.903855
156
0.740119
[ "MIT" ]
ScottColson/XrmUnitTest
DLaB.Xrm.Entities/msdyn_rtv.cs
72,995
C#
namespace DataStore.Models.PureFunctions.Extensions { using System; internal static class Dates { public static DateTime ConvertFromMillisecondsEpochTime(this double src) => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(src); public static DateTime ConvertFromSecondsEpochTime(this double src) => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(src); public static double ConvertToMillisecondsEpochTime(this DateTime src) => (src - new DateTime(1970, 1, 1)).TotalMilliseconds; } }
35
133
0.685714
[ "MIT-feh" ]
anavarro9731/datastore
src/DataStore.Models/PureFunctions/Extensions/Dates.cs
597
C#
/* Sniperkit-Bot - Status: analyzed */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TaxonomyLib; namespace TaxonomyWpf { public class NamespaceItem { public Namespace Namespace { get; } private Lazy<ICollection<Tag>> tags = new Lazy<ICollection<Tag>>(() => { return new ObservableCollection<Tag>(); }); public ICollection<Tag> Tags => tags.Value; public NamespaceItem(Namespace ns) { Namespace = ns; } } }
16.727273
72
0.719203
[ "MIT" ]
sniperkit/Taxonomy
TaxonomyWpf/NamespaceItem.cs
554
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ISUF.Storage.Enum { /// <summary> /// Enum of database changes /// </summary> public enum DbTypeOfChange { Add, Edit, Remove, CreateTable, UpdateTable, RemoveTable } }
16.727273
33
0.608696
[ "Apache-2.0" ]
JanRajnoha/ISUF
src/ISUF.Storage/Enum/DbTypeOfChange.cs
370
C#
using tictactoe.IO; namespace tictactoe.Players.Creation { public sealed class SecondHumanCreation : IPlayerCreation { private const string AcceptedInputFormat = "^[^{0}]$"; private const string PromptLineFormat = "Player Two: Select a single character (other than {0}) for your mark:"; private readonly IFormattedValidInput<IPlayer> _formatedValidInput; public SecondHumanCreation() : this(new FormattedValidInput<IPlayer>(AcceptedInputFormat, PromptLineFormat, new HumanPlayerValidInputResponseAction())) { } public SecondHumanCreation(IFormattedValidInput<IPlayer> formatedValidInput) => _formatedValidInput = formatedValidInput; public IPlayer Player(string mark) { _formatedValidInput.AddPatternArg(mark); _formatedValidInput.AddPromptArg(mark); return _formatedValidInput.ValidInput().Response(); } } }
40.26087
163
0.719222
[ "MIT" ]
Fyzxs/MicroObjectTicTacToe
TicTacToe/Players/Creation/SecondHumanCreation.cs
928
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HyoutaTools.Trophy.Viewer { public class GameFolder { public List<TrophyConfNode> TrophyLists; public GameFolder( String Folder ) { String[] Games = System.IO.Directory.GetDirectories( Folder ); TrophyLists = new List<TrophyConfNode>(); foreach ( String Game in Games ) { String TropConf = Game + "/TROPCONF.SFM"; String TropUsr = Game + "/TROPUSR.DAT"; if ( System.IO.File.Exists( TropConf ) && System.IO.File.Exists( TropUsr ) ) { TrophyConfNode TROPSFM = TrophyConfNode.ReadTropSfmWithFolder( Game, "TROPCONF.SFM" ); TrophyLists.Add( TROPSFM ); } } TrophyLists.TrimExcess(); return; } } }
25.866667
92
0.667526
[ "MIT" ]
LinkOFF7/HyoutaTools
Trophy/Viewer/GameFolder.cs
778
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class SceneChangeManager : Singleton<SceneChangeManager> { [SerializeField] GameObject loadingPanel; [SerializeField] Image loadingBar; private void Start() { SceneManager.activeSceneChanged += OnLoadFirstLvl; } public void LoadLevel(int i) { if (i == 1) { StartCoroutine(LoadAsync(i)); } else if (i == 2) { StartCoroutine(LoadAsync(i)); InitManagers(); } else if (i == 3) { SceneManager.LoadScene("Nivel3"); InitManagers(); } } public void LoadMenu() { SceneManager.LoadScene("MainMenu"); } public void SetLoadingPanelActive(bool active) { loadingPanel?.SetActive(active); } public void SetLoadingBarFillAmount(float value) { loadingBar.fillAmount = value; } IEnumerator LoadAsync(int i) { AsyncOperation op; if (i == 1) { op = SceneManager.LoadSceneAsync("Nivel1"); } else if (i == 2) { op = SceneManager.LoadSceneAsync("Nivel2"); } else { op = SceneManager.LoadSceneAsync("Nivel3"); } SetLoadingPanelActive(true); while (!op.isDone) { float progress = Mathf.Clamp01(op.progress / 0.9f); SetLoadingBarFillAmount(progress); yield return null; } } private void OnLoadFirstLvl(Scene current, Scene next) { if (next.name == "Nivel1") { InitManagers(); } else if (next.name == "MainMenu") { OnLoadMenu(); } SetLoadingPanelActive(false); } private static void InitManagers() { GameManager.Instance.Init(); InputManager.Instance.Init(); WeaponPrefabsLists.Instance.Init(); WaveManager.Instance.Init(); WeaponManager.Instance._player.Init(); } private void OnLoadMenu() { Destroy(FindObjectOfType<WaveManager>().gameObject); Destroy(FindObjectOfType<WeaponPrefabsLists>().gameObject); //Destroy(FindObjectOfType<InputManager>().gameObject); InputManager.Instance.ResetInit(); GameManager.Instance.ResetInit(); WeaponManager.Instance._player.Unsubscribe(); //Destroy(FindObjectOfType<GameManager>().gameObject); Destroy(FindObjectOfType<WeaponManager>().gameObject); Destroy(FindObjectOfType<EnemiesManager>().gameObject); Destroy(FindObjectOfType<CanvasDDOL>().gameObject); } public void ExitGame() { Application.Quit(); } }
23.858333
67
0.581558
[ "CC0-1.0" ]
jorgar17/REPO__FPS---Proyectos-IV
FPS - Proyectos IV/Assets/Scripts/General Managers/SceneChangeManager.cs
2,865
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class RegionKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public RegionKeywordRecommender() : base(SyntaxKind.RegionKeyword, isValidInPreprocessorContext: true, shouldFormatOnCommit: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
36.391304
126
0.767025
[ "MIT" ]
333fred/roslyn
src/Features/CSharp/Portable/Completion/KeywordRecommenders/RegionKeywordRecommender.cs
839
C#
/* Copyright (c) 2018 Convergence Systems Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSLibrary { public partial class RFIDReader { //private void StartInventory() //{ // _deviceHandler.SendAsync(0, 0, DOWNLINKCMD.RFIDCMD, PacketData(0xf000, (UInt32)HST_CMD.INV), HighLevelInterface.BTWAITCOMMANDRESPONSETYPE.WAIT_BTAPIRESPONSE); //_deviceHandler.rfid._dataBuffer.Clear(); /* // Create a timer that waits one second, then invokes every second. Xamarin.Forms.Device.StartTimer(TimeSpan.FromMilliseconds(2000), () => { _deviceHandler.SendAsync(0, 0, DOWNLINKCMD.RFIDCMD, PacketData(0, 0xf000, 0x000f), (UInt32)SENDREMARK.INVENTORY); return true; }); */ //} private void TagRangingThreadProc() { _tagRangingParms = m_rdr_opt_parms.TagRanging.Clone(); uint Value = 0; CSLibrary.Structures.InternalTagRangingParms parms = new CSLibrary.Structures.InternalTagRangingParms(); parms.flags = m_rdr_opt_parms.TagRanging.flags; parms.tagStopCount = m_rdr_opt_parms.TagRanging.tagStopCount; // Set MultiBanks Info MacReadRegister(MACREGISTER.HST_INV_CFG, ref Value); Value &= 0xfff5fcff; if (m_rdr_opt_parms.TagRanging.multibanks != 0) Value |= (m_rdr_opt_parms.TagRanging.multibanks & (uint)0x03) << 16; if (m_rdr_opt_parms.TagRanging.QTMode == true) Value |= 0x00080000; // bit 19 Value &= ~(0x03f00000U); // Set delay time to 0 if (m_rdr_opt_parms.TagRanging.compactmode) { Value |= _INVENTORYDELAYTIME; Value |= (1 << 26); // bit 26 MacWriteRegister(MACREGISTER.INV_CYCLE_DELAY, _InventoryCycleDelay); } else { Value |= (30 << 20); Value &= ~(1U << 26); // bit 26 MacWriteRegister(MACREGISTER.INV_CYCLE_DELAY, 0); } MacWriteRegister(MACREGISTER.HST_INV_CFG, Value); Value = 0; if (m_rdr_opt_parms.TagRanging.focus) Value |= 0x10; if (m_rdr_opt_parms.TagRanging.fastid) Value |= 0x20; MacWriteRegister(MACREGISTER.HST_IMPINJ_EXTENSIONS, Value); // Set up the access bank register Value = (UInt32)(m_rdr_opt_parms.TagRanging.bank1) | (UInt32)(((int)m_rdr_opt_parms.TagRanging.bank2) << 2); MacWriteRegister(MACREGISTER.HST_TAGACC_BANK, Value); // Set up the access pointer register (tells the offset) Value = (UInt32)((m_rdr_opt_parms.TagRanging.offset1 & 0xffff) | ((m_rdr_opt_parms.TagRanging.offset2 & 0xffff) << 16)); MacWriteRegister(MACREGISTER.HST_TAGACC_PTR, Value); // Set up the access count register (i.e., number values to read) Value = (UInt32)((0xFF & m_rdr_opt_parms.TagRanging.count1) | ((0xFF & m_rdr_opt_parms.TagRanging.count2) << 8)); MacWriteRegister(MACREGISTER.HST_TAGACC_CNT, Value); // Set up the access password Value = (UInt32)(m_rdr_opt_parms.TagRanging.accessPassword); MacWriteRegister(MACREGISTER.HST_TAGACC_ACCPWD, Value); // Set Toggle off, if QT Mode. if (m_rdr_opt_parms.TagRanging.QTMode == true) { uint RegValue = 0; for (uint cnt = 0; cnt < 4; cnt++) { MacWriteRegister(MACREGISTER.HST_INV_SEL, cnt); MacReadRegister(MACREGISTER.HST_INV_ALG_PARM_2, ref RegValue); Value &= 0xfffffffe; MacWriteRegister(MACREGISTER.HST_INV_ALG_PARM_2, Value); } } Start18K6CRequest(m_rdr_opt_parms.TagRanging.tagStopCount, parms.flags); _deviceHandler.SendAsync(0, 0, DOWNLINKCMD.RFIDCMD, PacketData(0xf000, (UInt32)HST_CMD.INV), HighLevelInterface.BTWAITCOMMANDRESPONSETYPE.WAIT_BTAPIRESPONSE); //m_Result = COMM_HostCommand(HST_CMD.INV); } private CSLibrary.Structures.TagRangingParms _tagRangingParms; private void PreTagRangingThreadProc() { _tagRangingParms = m_rdr_opt_parms.TagRanging.Clone(); uint Value = 0; CSLibrary.Structures.InternalTagRangingParms parms = new CSLibrary.Structures.InternalTagRangingParms(); parms.flags = m_rdr_opt_parms.TagRanging.flags; parms.tagStopCount = m_rdr_opt_parms.TagRanging.tagStopCount; // Set MultiBanks Info MacReadRegister(MACREGISTER.HST_INV_CFG, ref Value); Value &= 0xfff0fcff; Value |= (1 << 18); // enable CRC checking if (m_rdr_opt_parms.TagRanging.multibanks != 0) Value |= (m_rdr_opt_parms.TagRanging.multibanks & (uint)0x03) << 16; if (m_rdr_opt_parms.TagRanging.QTMode == true) Value |= (1 << 19); // bit 19 Value &= ~(0x03f00000U); // Set delay time to 0 if (m_rdr_opt_parms.TagRanging.compactmode) { Value |= _INVENTORYDELAYTIME; Value |= (1 << 26); // bit 26 MacWriteRegister(MACREGISTER.INV_CYCLE_DELAY, _InventoryCycleDelay); } else { Value |= (30 << 20); Value &= ~(1U << 26); // bit 26 MacWriteRegister(MACREGISTER.INV_CYCLE_DELAY, 0); } MacWriteRegister(MACREGISTER.HST_INV_CFG, Value); Value = 0; if (m_rdr_opt_parms.TagRanging.focus) Value |= 0x10; if (m_rdr_opt_parms.TagRanging.fastid) Value |= 0x20; MacWriteRegister(MACREGISTER.HST_IMPINJ_EXTENSIONS, Value); // Set up the access bank register Value = (UInt32)(m_rdr_opt_parms.TagRanging.bank1) | (UInt32)(((int)m_rdr_opt_parms.TagRanging.bank2) << 2); MacWriteRegister(MACREGISTER.HST_TAGACC_BANK, Value); // Set up the access pointer register (tells the offset) Value = (UInt32)((m_rdr_opt_parms.TagRanging.offset1 & 0xffff) | ((m_rdr_opt_parms.TagRanging.offset2 & 0xffff) << 16)); MacWriteRegister(MACREGISTER.HST_TAGACC_PTR, Value); // Set up the access count register (i.e., number values to read) Value = (UInt32)((0xFF & m_rdr_opt_parms.TagRanging.count1) | ((0xFF & m_rdr_opt_parms.TagRanging.count2) << 8)); MacWriteRegister(MACREGISTER.HST_TAGACC_CNT, Value); // Set up the access password Value = (UInt32)(m_rdr_opt_parms.TagRanging.accessPassword); MacWriteRegister(MACREGISTER.HST_TAGACC_ACCPWD, Value); // Set Toggle off, if QT Mode. if (m_rdr_opt_parms.TagRanging.QTMode == true) { uint RegValue = 0; for (uint cnt = 0; cnt < 4; cnt++) { MacWriteRegister(MACREGISTER.HST_INV_SEL, cnt); MacReadRegister(MACREGISTER.HST_INV_ALG_PARM_2, ref RegValue); Value &= 0xfffffffe; MacWriteRegister(MACREGISTER.HST_INV_ALG_PARM_2, Value); } } Start18K6CRequest(m_rdr_opt_parms.TagRanging.tagStopCount, parms.flags); } private void ExeTagRangingThreadProc() { _deviceHandler.SendAsync(0, 0, DOWNLINKCMD.RFIDCMD, PacketData(0xf000, (UInt32)HST_CMD.INV), HighLevelInterface.BTWAITCOMMANDRESPONSETYPE.WAIT_BTAPIRESPONSE); } private void TagSearchOneTagThreadProc() { // FireStateChangedEvent(RFState.BUSY); UInt32 Value = 0; // disable compact mode MacReadRegister(MACREGISTER.HST_INV_CFG, ref Value); Value &= ~(0x03f00000U); // Set delay time to 0 Value |= (30 << 20); Value &= ~(1U << 26); // bit 26 MacWriteRegister(MACREGISTER.INV_CYCLE_DELAY, 0); MacWriteRegister(MACREGISTER.HST_INV_CFG, Value); CSLibrary.Structures.InternalTagSearchOneParms parms = new CSLibrary.Structures.InternalTagSearchOneParms(); parms.avgRssi = m_rdr_opt_parms.TagSearchOne.avgRssi; // m_Result = TagSearchOne(parms); Start18K6CRequest(0, CSLibrary.Constants.SelectFlags.SELECT); _deviceHandler.SendAsync(0, 0, DOWNLINKCMD.RFIDCMD, PacketData(0xf000, (UInt32)HST_CMD.INV), HighLevelInterface.BTWAITCOMMANDRESPONSETYPE.WAIT_BTAPIRESPONSE); // FireStateChangedEvent(RFState.IDLE); } private void PreTagSearchOneTagThreadProc() { UInt32 Value = 0; // disable compact mode MacReadRegister(MACREGISTER.HST_INV_CFG, ref Value); Value &= ~(0x03f00000U); // Set delay time to 0 Value |= (30 << 20); Value &= ~(1U << 26); // bit 26 MacWriteRegister(MACREGISTER.INV_CYCLE_DELAY, 0); MacWriteRegister(MACREGISTER.HST_INV_CFG, Value); CSLibrary.Structures.InternalTagSearchOneParms parms = new CSLibrary.Structures.InternalTagSearchOneParms(); parms.avgRssi = m_rdr_opt_parms.TagSearchOne.avgRssi; // m_Result = TagSearchOne(parms); Start18K6CRequest(0, CSLibrary.Constants.SelectFlags.SELECT); } private void ExeTagSearchOneTagThreadProc() { _deviceHandler.SendAsync(0, 0, DOWNLINKCMD.RFIDCMD, PacketData(0xf000, (UInt32)HST_CMD.INV), HighLevelInterface.BTWAITCOMMANDRESPONSETYPE.WAIT_BTAPIRESPONSE); } } }
41.439394
173
0.627605
[ "MIT" ]
cslrfid/CS108-Mobile-CSharp-DotNetStd-App
Library/CSLibrary/RFIDReader/ClassRFID.Private.Inventory.cs
10,942
C#
using Alloy.Mvc._1.Models.Pages; namespace Alloy.Mvc._1.Models.ViewModels; public class SearchContentModel : PageViewModel<SearchPage> { public SearchContentModel(SearchPage currentPage) : base(currentPage) { } public bool SearchServiceDisabled { get; set; } public string SearchedQuery { get; set; } public int NumberOfHits { get; set; } public IEnumerable<SearchHit> Hits { get; set; } public class SearchHit { public string Title { get; set; } public string Url { get; set; } public string Excerpt { get; set; } } }
20.689655
59
0.655
[ "Apache-2.0" ]
episerver/content-templates
templates/Alloy.Mvc/Models/ViewModels/SearchContentModel.cs
600
C#
// // System.Buffer.cs // // Authors: // Paolo Molaro (lupus@ximian.com) // Dan Lewis (dihlewis@yahoo.co.uk) // // (C) 2001 Ximian, Inc. http://www.ximian.com // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Morph { public static class Buffer { public unsafe static int ByteLength (System.Array array) { // note: the other methods in this class also use ByteLength to test for // null and non-primitive arguments as a side-effect. if (array == null) { //throw new ArgumentNullException ("array"); } int length = (int)clrcore.GarbageCollector.garbageCollectorGetObjectSize(Morph.Imports.convert(array)); if (length < 0) { //throw new ArgumentException (Locale.GetText ("Object must be an array of primitives.")); } return length; } public static byte GetByte (System.Array array, int index) { if (index < 0 || index >= ByteLength(array)) { //throw new ArgumentOutOfRangeException ("index", Locale.GetText("Value must be non-negative and less than the size of the collection.")); } return ((byte[])array)[index]; } public static void SetByte (System.Array array, int index, byte value) { if (index < 0 || index >= ByteLength(array)) { //throw new ArgumentOutOfRangeException ("index", Locale.GetText("Value must be non-negative and less than the size of the collection.")); } ((byte[])array)[index] = value; } public unsafe static void BlockCopy(System.Array src, int srcOffset, System.Array dst, int dstOffset, int count) { if (src == null) { //throw new ArgumentNullException ("src"); } if (dst == null) { //throw new ArgumentNullException ("dst"); } if (srcOffset < 0) { //throw new ArgumentOutOfRangeException ("srcOffset", Locale.GetText("Non-negative number required.")); } if (dstOffset < 0) { //throw new ArgumentOutOfRangeException ("dstOffset", Locale.GetText ("Non-negative number required.")); } if (count < 0) { //throw new ArgumentOutOfRangeException ("count", Locale.GetText ("Non-negative number required.")); } // We do the checks in unmanaged code for performance reasons object o = src; Morph.Array src_array = (Morph.Array)o; o = dst; Morph.Array dst_array = (Morph.Array)o; clrcore.Memory.memcpy(dst_array.internalGetBuffer() + dstOffset, src_array.internalGetBuffer() + srcOffset, (uint)count); } } }
34.719298
154
0.619505
[ "BSD-3-Clause" ]
eladraz/morph
netcore/clr/clrcore/IO/Buffer.cs
3,958
C#
using System; using System.Collections.Generic; using System.Text; using ReactiveUI; using System.Reactive; using System.Collections.ObjectModel; using CourseScheduler.Avalonia.VMInfrastructures; using System.Net.Http; using CourseScheduler.Core.DataStrucures; using CourseScheduler.Avalonia.Model; using System.Linq; using CourseScheduler.Core; using System.Collections.Specialized; using System.Drawing.Text; using System.Threading.Tasks; using System.Threading; using Avalonia.Media; using CourseScheduler.Avalonia.Views; using UIEngine.Core; using UIEngine; namespace CourseScheduler.Avalonia.ViewModels { public class MainPageViewModel : ViewModelBase { public MainPageViewModel() { CourseSet.CollectionChanged += (s, e) => { if (e.Action == NotifyCollectionChangedAction.Add) { ExpandInstructorsFilter(e.NewItems[0] as Course); } else if (e.Action == NotifyCollectionChangedAction.Remove) { ShrinkInstructorsFilter(e.OldItems[0] as Course); } else if (e.Action == NotifyCollectionChangedAction.Reset) { InstructorsFilter.Clear(); } }; var semesterInfo = SemesterCodeHelper.GetSemesterList(); SemesterList = semesterInfo.Item2; SelectedSemester = semesterInfo.Item1; CourseSet.CollectionChanged += (s, e) => UpdateCombinations(); this.PropertyChanged += (s, e) => AnyThesePropertiesChanged(e.PropertyName); ObservableTuple<bool, string>.GenericHandler += (s, e) => UpdateCombinations(); ObservableTuple<bool, ClassSpan>.GenericHandler += (s, e) => UpdateCombinations(); TimePeriodsFilter = new ObservableCollection<ObservableTuple<bool, ClassSpan>> { (false,new ClassSpan(new Time(6, 0), new Time(7, 0))), (false,new ClassSpan(new Time(7, 0), new Time(8, 0))), (false,new ClassSpan(new Time(8, 0), new Time(9, 0))), (false,new ClassSpan(new Time(9, 0), new Time(10, 0))), (false,new ClassSpan(new Time(10, 0), new Time(11, 0))), (false,new ClassSpan(new Time(11, 0), new Time(12, 0))), (false,new ClassSpan(new Time(12, 0), new Time(13, 0))), (false,new ClassSpan(new Time(13, 0), new Time(14, 0))), (false,new ClassSpan(new Time(17, 0), new Time(18, 0))), (false,new ClassSpan(new Time(18, 0), new Time(19, 0))), (false,new ClassSpan(new Time(19, 0), new Time(21, 0))) }; #if DEBUG //AddCourseToCourseSetAndCache("cmsc216"); //AddCourseToCourseSetAndCache("cmsc430"); #endif } private string _InputCourseName; public string InputCourseName { get => _InputCourseName; set => this.RaiseAndSetIfChanged(ref _InputCourseName, value); } private bool _IsOpenSectionOnly = false; public bool IsOpenSectionOnly { get => _IsOpenSectionOnly; set => this.RaiseAndSetIfChanged(ref _IsOpenSectionOnly, value); } private bool _DoesShowFC = false; public bool DoesShowFC { get => _DoesShowFC; set => this.RaiseAndSetIfChanged(ref _DoesShowFC, value); } private string _SelectedSemester = "Fall 2020"; public string SelectedSemester { get => _SelectedSemester; set => this.RaiseAndSetIfChanged(ref _SelectedSemester, value); } private List<Section> _SelectedCombination; public List<Section> SelectedCombination { get => _SelectedCombination; set => this.RaiseAndSetIfChanged(ref _SelectedCombination, value); } private List<List<Section>> _Combinations = new List<List<Section>>(); public List<List<Section>> Combinations { get => _Combinations; set => this.RaiseAndSetIfChanged(ref _Combinations, value); } private IEnumerable<string> _CombinationPanelHeader = new List<string>(); public IEnumerable<string> CombinationPanelHeader { get => _CombinationPanelHeader; set => this.RaiseAndSetIfChanged(ref _CombinationPanelHeader, value); } public ObservableCollection<ObservableTuple<bool, string>> InstructorsFilter { get; } = new ObservableCollection<ObservableTuple<bool, string>>(); public ObservableCollection<ObservableTuple<bool, ClassSpan>> TimePeriodsFilter { get; } public Dictionary<string, string> SemesterList { get; } public ObservableSet<Course> CourseSet => DomainModel.CourseSet; public async void AddCourse() => await AddCourseToCourseSetAndCache(InputCourseName); public void RemoveCourse(Course course) => CourseSet.Remove(course); public void UpdateCombinations() { var blockedTimePeriods = TimePeriodsFilter.Where(t => t.E1).Select(t => t.E2); var blockedInstructors = InstructorsFilter.Where(t => t.E1).Select(t => t.E2); Combinations = Algorithm.GetPossibleCombinations (CourseSet.ToArray(), blockedTimePeriods, blockedInstructors, IsOpenSectionOnly, DoesShowFC); CombinationPanelHeader = CourseSet.Select(c => c.Name); } internal async Task AddCourseToCourseSetAndCache(string rawName) { if (string.IsNullOrWhiteSpace(rawName)) { return; } MainWindowViewModel.Instance.SetLoadingState(true); var courseName = rawName.ToUpper(); if (string.IsNullOrWhiteSpace(courseName)) { return; } if (!CourseSet.Has(courseName)) { Course course = null; if (DomainModel.CourseSetCache.Has(courseName)) { course = DomainModel.CourseSetCache.Get(courseName); } else { try { course = await Crawler.GetCourse(courseName, SemesterList[SelectedSemester]); DomainModel.CourseSetCache.Add(course); } catch (Exception e) { MainWindowViewModel.Instance.SetLoadingState(false); ShowMessage(e); } } CourseSet.Add(course); } MainWindowViewModel.Instance.SetLoadingState(false); return; } private void AnyThesePropertiesChanged(string propertyName) { switch (propertyName) { case nameof(DoesShowFC): case nameof(IsOpenSectionOnly): UpdateCombinations(); break; case nameof(SelectedCombination): MainPageView.ScheduleTimeTable(SelectedCombination); break; case nameof(SelectedSemester): CourseSet.Clear(); DomainModel.CourseSetCache.Clear(); break; default: break; } } private void ExpandInstructorsFilter(Course newCourse) { if (newCourse != null) { foreach (var ins in newCourse.Instructors) { InstructorsFilter.Add((false, ins)); } } } private void ShrinkInstructorsFilter(Course oldCourse) { foreach (var ins in oldCourse.Instructors) { var tup = InstructorsFilter.First(t => t.E2 == ins); InstructorsFilter.Remove(tup); } } private void ShowMessage(Exception exception) { if (exception is HttpRequestException) { MainWindowViewModel.ShowMessageBox( "Connection error", "Testudo may be under maintenance. \nPlease retry later.\n\n" + exception.Message ); } else if (exception is AggregateException) { foreach (var e in (exception as AggregateException).InnerExceptions) { ShowMessage(e); } } else if (exception is InvalidOperationException) { MainWindowViewModel.ShowMessageBox( "Invalid input", "Unable to get the course info\nPlease check if there is any typo in course name. \n\n" + exception.Message ); } else { MainWindowViewModel.ShowMessageBox( "Error", exception.Message ); } } } }
27.896552
112
0.706222
[ "MIT" ]
Quantumzhao/CourseScheduler
CourseScheduler.Avalonia/ViewModels/MainPageViewModel.cs
7,283
C#
/* *所有关于Personal_Certificates类的业务代码接口应在此处编写 */ using VOL.Core.BaseProvider; using VOL.Entity.DomainModels; using VOL.Core.Utilities; using System.Linq.Expressions; namespace Business.IServices { public partial interface IPersonal_CertificatesService { } }
19.214286
58
0.791822
[ "MIT" ]
suxuanning/Vue.NetCore
Vue.Net/Business/IServices/Archives/Partial/IPersonal_CertificatesService.cs
305
C#
using Engine.Shared.Base; using Engine.Shared.Interfaces; using FarseerPhysics; using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Joints; using FarseerPhysics.Factories; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; namespace Game.Shared.Base { /// <summary> The physics world that will control all physics objects </summary> public class PhysicsWorld : IUpdatable, IDisposable { /// <summary> The list of bodies in the physics world </summary> private readonly List<Body> _BodyList = new List<Body>(); /// <summary> The list of joints in the scene </summary> private readonly List<Joint> _JointList = new List<Joint>(); /// <summary> The instance of the physics world </summary> private World _World; /// <summary> The gravity for the world </summary> private Vector2 _Gravity; /// <summary> The instance of the physics world </summary> private static PhysicsWorld _Instance; /// <summary> The instance of the world </summary> public static PhysicsWorld Instance => _Instance ?? (_Instance = new PhysicsWorld()); /// <summary> The instance of the physics world </summary> public World World { get { return _World; } } /// <summary> The gravity of the world </summary> public Vector2 Gravity { get { return _Gravity; } set { _Gravity = value; _World.Gravity = value; } } /// <summary> Whether or not physics are enabled for the world </summary> public Boolean Enabled { get; set; } public PhysicsWorld() { ConvertUnits.SetDisplayUnitToSimUnitRatio(350); _Gravity = new Vector2(0, -9.81f); _World = new World(_Gravity); UpdateManager.Instance.AddUpdatable(this); } /// <summary> Creates a rectangle in the position given with the size given </summary> /// <param name="centerPosition"></param> /// <param name="size"></param> /// <param name="density"></param> /// <returns></returns> public Body CreateRectangle(Vector2 centerPosition, Vector2 size, Single density) { Body rectangle = BodyFactory.CreateRectangle(_World, ConvertUnits.ToSimUnits(size.X), ConvertUnits.ToSimUnits(size.Y), density); rectangle.Position = ConvertUnits.ToSimUnits(centerPosition); _BodyList.Add(rectangle); return rectangle; } /// <summary> Creates a circle with the given center position and radius </summary> /// <param name="centerPosition"></param> /// <param name="radius"></param> /// <param name="density"></param> /// <returns></returns> public Body CreateCircle(Vector2 centerPosition, Single radius, Single density) { Body circle = BodyFactory.CreateCircle(_World, ConvertUnits.ToSimUnits(radius), density); circle.Position = ConvertUnits.ToSimUnits(centerPosition); _BodyList.Add(circle); return circle; } /// <summary> Creates a revolute joint between 2 given bodies - this joint ensures that the 2 bodies are always in the same place </summary> /// <param name="bodyA"></param> /// <param name="bodyB"></param> /// <param name="position"></param> /// <returns></returns> public RevoluteJoint CreateRevoluteJoint(Body bodyA, Body bodyB, Vector2 position) { RevoluteJoint joint = JointFactory.CreateRevoluteJoint(_World, bodyA, bodyB, ConvertUnits.ToSimUnits(position)); _JointList.Add(joint); return joint; } /// <summary> Removes the body from the world </summary> /// <param name="body"></param> public void RemoveBody(Body body) { body.Dispose(); body.UserData = null; body.CollidesWith = Category.None; _BodyList.Remove(body); } /// <summary> Removes the joint </summary> /// <param name="joint"></param> public void RemoveJoint(Joint joint) { _World.RemoveJoint(joint); _JointList.Remove(joint); } /// <summary> Updates the physics world </summary> /// <param name="timeSinceUpdate"></param> public void Update(TimeSpan timeSinceUpdate) { _World.Step((Single)timeSinceUpdate.TotalSeconds); } /// <summary> Disposes of the physics world </summary> public void Dispose() { foreach (Body body in _BodyList) body.Dispose(); _BodyList.Clear(); foreach (Joint joint in _JointList.ToList()) RemoveJoint(joint); _JointList.Clear(); UpdateManager.Instance.RemoveUpdatable(this); _Instance = null; } /// <summary> Whether or not the physics can be updated </summary> /// <returns></returns> public bool CanUpdate() { return Enabled; } } }
36.680556
148
0.593715
[ "MIT" ]
PacktPublishing/Create-and-Monetize-your-C-Games-on-iOS-and-Android
Source Code/Game.Shared/Base/PhysicsWorld.cs
5,284
C#
using Microsoft.AspNetCore.Mvc.RazorPages; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebSortAlgorithms.Pages.SortViews { public class ModelCardSortView : PageModel { public string Title { get; set; } } }
20.785714
46
0.745704
[ "MIT" ]
walonso/SortAlgorithms
WebSortAlgorithms/Pages/SortViews/ModelCardSortView.cs
293
C#
using System; using System.Numerics; using Microsoft.Xna.Framework.Graphics; using Myre.Extensions; using Myre.Graphics.Materials; using Myre.Graphics.PostProcessing; using Color = Microsoft.Xna.Framework.Color; namespace Myre.Graphics.Deferred { public class ToneMapComponent : RendererComponent { readonly Quad _quad; readonly Material _calculateLuminance; readonly Material _readLuminance; readonly Material _adaptLuminance; readonly Material _toneMap; readonly Effect _bloom; readonly Gaussian _gaussian; readonly RenderTarget2D[] _adaptedLuminance; RenderTarget2D _averageLuminance; int _current = 0; int _previous = -1; public RenderTarget2D AdaptedLuminance { get { return _adaptedLuminance[_current]; } } public ToneMapComponent(GraphicsDevice device) { _quad = new Quad(device); var effect = Content.Load<Effect>("CalculateLuminance"); _calculateLuminance = new Material(effect.Clone(), "ExtractLuminance"); _adaptLuminance = new Material(effect.Clone(), "AdaptLuminance"); _readLuminance = new Material(effect.Clone(), "ReadLuminance"); _toneMap = new Material(Content.Load<Effect>("ToneMap"), null); _bloom = Content.Load<Effect>("Bloom"); _gaussian = new Gaussian(device); _adaptedLuminance = new RenderTarget2D[2]; _adaptedLuminance[0] = new RenderTarget2D(device, 1, 1, false, SurfaceFormat.Single, DepthFormat.None); _adaptedLuminance[1] = new RenderTarget2D(device, 1, 1, false, SurfaceFormat.Single, DepthFormat.None); } public override void Initialise(Renderer renderer, ResourceContext context) { // define settings var settings = renderer.Settings; settings.Add("hdr_adaptionrate", "The rate at which the cameras' exposure adapts to changes in the scene luminance.", 1f); settings.Add("hdr_bloomthreshold", "The under-exposure applied during bloom thresholding.", 6f); settings.Add("hdr_bloommagnitude", "The overall brightness of the bloom effect.", 3f); settings.Add("hdr_bloomblurammount", "The amount to blur the bloom target.", 2.2f); settings.Add("hdr_minexposure", "The minimum exposure the camera can adapt to.", -1.1f); settings.Add("hdr_maxexposure", "The maximum exposure the camera can adapt to.", 1.1f); // define inputs context.DefineInput("lightbuffer"); // define outputs //context.DefineOutput("luminancemap", isLeftSet: false, width: 1024, height: 1024, surfaceFormat: SurfaceFormat.Single); context.DefineOutput("luminance", isLeftSet: false, width: 1, height: 1, surfaceFormat: SurfaceFormat.Single); context.DefineOutput("bloom", isLeftSet: false, surfaceFormat: SurfaceFormat.Rgba64); context.DefineOutput("tonemapped", isLeftSet: true, surfaceFormat: SurfaceFormat.Color, depthFormat: DepthFormat.Depth24Stencil8); base.Initialise(renderer, context); } public override void Draw(Renderer renderer) { var metadata = renderer.Data; var device = renderer.Device; var lightBuffer = metadata.GetValue(new TypedName<Texture2D>("lightbuffer")); var resolution = metadata.GetValue(new TypedName<Vector2>("resolution")); CalculateLuminance(renderer, resolution, device, lightBuffer); Bloom(renderer, resolution, device, lightBuffer); ToneMap(renderer, resolution, device, lightBuffer); } private void CalculateLuminance(Renderer renderer, Vector2 resolution, GraphicsDevice device, Texture2D lightBuffer) { if (_previous == -1) { _previous = 1; device.SetRenderTarget(_adaptedLuminance[_previous]); device.Clear(Color.Transparent); device.SetRenderTarget(null); } var tmp = _previous; _previous = _current; _current = tmp; // calculate luminance map var luminanceMap = RenderTargetManager.GetTarget(device, 1024, 1024, SurfaceFormat.Single, mipMap: true, name: "luminance map", usage: RenderTargetUsage.DiscardContents); device.SetRenderTarget(luminanceMap); device.BlendState = BlendState.Opaque; device.Clear(Color.Transparent); _calculateLuminance.Parameters["Texture"].SetValue(lightBuffer); _quad.Draw(_calculateLuminance, renderer.Data); Output("luminance", luminanceMap); // read bottom mipmap to find average luminance _averageLuminance = RenderTargetManager.GetTarget(device, 1, 1, SurfaceFormat.Single, name: "average luminance", usage: RenderTargetUsage.DiscardContents); device.SetRenderTarget(_averageLuminance); _readLuminance.Parameters["Texture"].SetValue(luminanceMap); _quad.Draw(_readLuminance, renderer.Data); // adapt towards the current luminance device.SetRenderTarget(_adaptedLuminance[_current]); _adaptLuminance.Parameters["Texture"].SetValue(_averageLuminance); _adaptLuminance.Parameters["PreviousAdaption"].SetValue(_adaptedLuminance[_previous]); _quad.Draw(_adaptLuminance, renderer.Data); RenderTargetManager.RecycleTarget(_averageLuminance); } private void Bloom(Renderer renderer, Vector2 resolution, GraphicsDevice device, Texture2D lightBuffer) { var screenResolution = resolution; var halfResolution = screenResolution / 2; var quarterResolution = halfResolution / 2; // downsample the light buffer to half resolution, and threshold at the same time var thresholded = RenderTargetManager.GetTarget(device, (int)halfResolution.X, (int)halfResolution.Y, SurfaceFormat.Rgba64, name: "bloom thresholded", usage: RenderTargetUsage.DiscardContents); device.SetRenderTarget(thresholded); _bloom.Parameters["Resolution"].SetValue(halfResolution); _bloom.Parameters["Threshold"].SetValue(renderer.Data.GetValue(new TypedName<float>("hdr_bloomthreshold"))); _bloom.Parameters["MinExposure"].SetValue(renderer.Data.GetValue(new TypedName<float>("hdr_minexposure"))); _bloom.Parameters["MaxExposure"].SetValue(renderer.Data.GetValue(new TypedName<float>("hdr_maxexposure"))); _bloom.Parameters["Texture"].SetValue(lightBuffer); _bloom.Parameters["Luminance"].SetValue(_adaptedLuminance[_current]); _bloom.CurrentTechnique = _bloom.Techniques["ThresholdDownsample2X"]; _quad.Draw(_bloom); // downsample again to quarter resolution var downsample = RenderTargetManager.GetTarget(device, (int)quarterResolution.X, (int)quarterResolution.Y, SurfaceFormat.Rgba64, name: "bloom downsampled", usage: RenderTargetUsage.DiscardContents); device.SetRenderTarget(downsample); _bloom.Parameters["Resolution"].SetValue(quarterResolution); _bloom.Parameters["Texture"].SetValue(thresholded); _bloom.CurrentTechnique = _bloom.Techniques["Scale"]; _quad.Draw(_bloom); // blur the target var blurred = RenderTargetManager.GetTarget(device, (int)quarterResolution.X, (int)quarterResolution.Y, SurfaceFormat.Rgba64, name: "bloom blurred", usage: RenderTargetUsage.DiscardContents); _gaussian.Blur(downsample, blurred, renderer.Data.GetValue(new TypedName<float>("hdr_bloomblurammount"))); // upscale back to half resolution device.SetRenderTarget(thresholded); _bloom.Parameters["Resolution"].SetValue(halfResolution); _bloom.Parameters["Texture"].SetValue(blurred); _quad.Draw(_bloom); // output result Output("bloom", thresholded); // cleanup temp render targets RenderTargetManager.RecycleTarget(downsample); RenderTargetManager.RecycleTarget(blurred); } private void ToneMap(Renderer renderer, Vector2 resolution, GraphicsDevice device, Texture2D lightBuffer) { var toneMapped = RenderTargetManager.GetTarget(device, (int)resolution.X, (int)resolution.Y, SurfaceFormat.Color, depthFormat: DepthFormat.Depth24Stencil8, name: "tone mapped", usage: RenderTargetUsage.DiscardContents); device.SetRenderTarget(toneMapped); device.Clear(Color.Transparent); device.DepthStencilState = DepthStencilState.None; device.BlendState = BlendState.Opaque; _toneMap.Parameters["Texture"].SetValue(lightBuffer); _toneMap.Parameters["Luminance"].SetValue(_adaptedLuminance[_current]); _toneMap.Parameters["MinExposure"].SetValue(renderer.Data.GetValue(new TypedName<float>("hdr_minexposure"))); _toneMap.Parameters["MaxExposure"].SetValue(renderer.Data.GetValue(new TypedName<float>("hdr_maxexposure"))); _quad.Draw(_toneMap, renderer.Data); Output("tonemapped", toneMapped); } #region Tone Mapping Math Functions public static Vector3 ToneMap(Vector3 colour, float adaptedLuminance) { return ToneMapFilmic(CalcExposedColor(colour, adaptedLuminance)); } // From http://mynameismjp.wordpress.com/2010/04/30/a-closer-look-at-tone-mapping // Applies the filmic curve from John Hable's presentation private static Vector3 ToneMapFilmic(Vector3 color) { color = Vector3.Max(Vector3.Zero, color - new Vector3(0.004f)); color = (color * (6.2f * color + new Vector3(0.5f))) / (color * (6.2f * color + new Vector3(1.7f)) + new Vector3(0.06f)); return color; } public static Vector3 InverseToneMap(Vector3 colour, float adaptedLuminance) { return InverseExposedColour(InverseToneMapFilmic(colour), adaptedLuminance); } private static Vector3 InverseToneMapFilmic(Vector3 colour) { return new Vector3( InverseToneMapFilmic(colour.X), InverseToneMapFilmic(colour.Y), InverseToneMapFilmic(colour.Z)); } private static float InverseToneMapFilmic(float x) { var numerator = Math.Sqrt(5) * Math.Sqrt(701 * x * x - 106 * x + 125) - 856 * x + 25; var denumerator = 620 * (x - 1); return (float)Math.Abs(numerator / denumerator) + 0.004f; } // Determines the color based on exposure settings public static Vector3 CalcExposedColor(Vector3 color, float avgLuminance) { // Use geometric mean avgLuminance = Math.Max(avgLuminance, 0.001f); float keyValue = 1.03f - (2.0f / (2 + (float)Math.Log10(avgLuminance + 1))); float linearExposure = (keyValue / avgLuminance); float exposure = Math.Max(linearExposure, 0.0001f); return exposure * color; } public static Vector3 InverseExposedColour(Vector3 colour, float avgLuminance) { avgLuminance = Math.Max(avgLuminance, 0.001f); float keyValue = 1.03f - (2.0f / (2 + (float)Math.Log10(avgLuminance + 1))); float linearExposure = (keyValue / avgLuminance); float exposure = Math.Max(linearExposure, 0.0001f); return colour / exposure; } #endregion } }
47.875
231
0.652657
[ "MIT" ]
martindevans/Myre
Myre/Myre.Graphics/Deferred/ToneMapComponent.cs
11,875
C#
using Meadow.Foundation.Sensors.Gnss; using Meadow.Hardware; namespace Meadow.Foundation.FeatherWings { public class GPSWing : Mt3339 { public GPSWing(ISerialMessagePort serialMessagePort) : base(serialMessagePort) { } } }
21.076923
60
0.660584
[ "Apache-2.0" ]
WildernessLabs/Meadow.Foundation
Source/Meadow.Foundation.Peripherals/FeatherWings.GPSWing/Driver/FeatherWings.GPSWing/GPSWing.cs
276
C#
//----------------------------------------------------------------------- // <copyright file="<file>.cs" company="The Outercurve Foundation"> // Copyright (c) 2011, The Outercurve Foundation. // // Licensed under the MIT License (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.opensource.org/licenses/mit-license.php // // 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. // </copyright> // <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author> // <website>https://github.com/facebook-csharp-sdk/simple-json</website> //----------------------------------------------------------------------- namespace SimpleJsonTests.PocoJsonSerializerTests { using System; #if NUNIT using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using ClassCleanup = NUnit.Framework.TestFixtureTearDownAttribute; using ClassInitialize = NUnit.Framework.TestFixtureSetUpAttribute; using NUnit.Framework; #else #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif #endif [TestClass] public class NullableSerializeTests { [TestMethod] public void Test() { DateTime? obj = null; var json = SimpleJson.SimpleJson.SerializeObject(obj); Assert.AreEqual("null", json); } [TestMethod] public void TestWithValue() { DateTime? obj = new DateTime(2004, 1, 20, 5, 3, 6, 12, DateTimeKind.Utc); var json = SimpleJson.SimpleJson.SerializeObject(obj); Assert.AreEqual("\"2004-01-20T05:03:06.012Z\"", json); } [TestMethod] public void TestNullDateTimeOffset() { DateTimeOffset? obj = null; var json = SimpleJson.SimpleJson.SerializeObject(obj); Assert.AreEqual("null", json); } [TestMethod] public void TestDateTimeOffsetWithValue() { DateTimeOffset? obj = new DateTimeOffset(2004, 1, 20, 5, 3, 6, 12, TimeSpan.Zero); var json = SimpleJson.SimpleJson.SerializeObject(obj); Assert.AreEqual("\"2004-01-20T05:03:06.012Z\"", json); } [TestMethod] public void SerializeNullableTypeThatIsNotNull() { var obj = new NullableTypeClass(); obj.Value = null; var json = SimpleJson.SimpleJson.SerializeObject(obj); Assert.AreEqual("{\"Value\":null}", json); } [TestMethod] public void SerializeNullableTypeThatIsNull() { var obj = new NullableTypeClass(); obj.Value = 4; var json = SimpleJson.SimpleJson.SerializeObject(obj); Assert.AreEqual("{\"Value\":4}", json); } public class NullableTypeClass { public int? Value { get; set; } } } }
32.810811
114
0.593355
[ "MIT" ]
MihaMarkic/simple-json
src/SimpleJson.Tests/PocoJsonSerializerTests/NullableSerializeTests.cs
3,644
C#