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.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("03. ReadFileContents")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03. ReadFileContents")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("9afcbb01-ee4c-4cf8-a913-e2f109903ae3")]
// 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.745223 | [
"MIT"
] | dimanov/Exception-Handling | 03. ReadFileContents/Properties/AssemblyInfo.cs | 1,416 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:e1aa27513bdb58756eebe8fac5380629db0edb4eb471c2372f71c64c201bcfce
size 618
| 32 | 75 | 0.882813 | [
"MIT"
] | Vakuzar/Multithreaded-Blood-Sim | Blood/Library/PackageCache/com.unity.burst@1.3.0-preview.12/Runtime/CompilerServices/Loop.cs | 128 | 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("Sign of Integer Number")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sign of Integer Number")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("543a8e7e-046c-44fa-949d-7ba9b7af803c")]
// 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.297297 | 84 | 0.744531 | [
"MIT"
] | RAstardzhiev/SoftUni-C- | Programming Fundamentals/Methods and Debugging - Lab/2. Sign of Integer Number/Properties/AssemblyInfo.cs | 1,420 | C# |
using FilterLists.Directory.Infrastructure.Persistence.Queries.Context;
using FilterLists.SharedKernel.Logging;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
#if DEBUG
using Microsoft.Extensions.Logging;
#endif
namespace FilterLists.Directory.Infrastructure;
public static class ConfigurationExtensions
{
public static IHostBuilder ConfigureInfrastructure(this IHostBuilder hostBuilder)
{
return hostBuilder.ConfigureLogging();
}
public static void AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
services.AddSharedKernelLogging(configuration);
services.AddDbContextPool<QueryDbContext>(o =>
{
o.UseNpgsql(configuration.GetConnectionString("DirectoryConnection"),
po => po.MigrationsAssembly("FilterLists.Directory.Infrastructure.Migrations"))
.UseSnakeCaseNamingConvention()
#if DEBUG
.LogTo(Console.WriteLine, LogLevel.Information);
o.EnableSensitiveDataLogging();
#else
;
#endif
});
services.AddScoped<IQueryContext, QueryContext>();
}
public static void UseInfrastructure(this IApplicationBuilder app)
{
app.UseLogging();
}
}
| 32 | 104 | 0.732244 | [
"MIT"
] | scafroglia93/FilterLists | services/Directory/FilterLists.Directory.Infrastructure/ConfigurationExtensions.cs | 1,410 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Ics.OpenApi.Extensions
{
/// <summary>
/// 泛型扩展
/// </summary>
public static class GenericExtensions
{
private static Dictionary<Type, Dictionary<string, Delegate>> ToDictionaryCache = new Dictionary<Type, Dictionary<string, Delegate>>();
/// <summary>
/// 转换为字典
/// </summary>
/// <typeparam name="TObject"></typeparam>
/// <param name="object"></param>
/// <param name="includeNonPublic">包含非公有属性</param>
/// <returns></returns>
public static Dictionary<string, object> ToDictionary<TObject>(this TObject @object, bool includeNonPublic = false)
{
Dictionary<string, object> result = new Dictionary<string, object>();
var obejctType = typeof(TObject);
Dictionary<string, Delegate> tObjectDelegateCache;
if (ToDictionaryCache.ContainsKey(obejctType))
{
tObjectDelegateCache = ToDictionaryCache[obejctType];
}
else
{
tObjectDelegateCache = new Dictionary<string, Delegate>();
var bindingFlasg = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public;
if (includeNonPublic)
{
bindingFlasg |= System.Reflection.BindingFlags.NonPublic;
}
foreach (var propertyInfo in obejctType.GetProperties(bindingFlasg))
{
if (!propertyInfo.CanRead) continue;
if (propertyInfo.GetMethod.GetParameters().Length > 0) continue;
var param = Expression.Parameter(obejctType, "param");
var param_propertyInfo = Expression.MakeMemberAccess(param, propertyInfo);
var lambda = Expression.Lambda(
delegateType: typeof(Func<,>).MakeGenericType(obejctType, propertyInfo.PropertyType),
body: param_propertyInfo,
parameters: new[] { param }
);
var @delegate = lambda.Compile(
#if !NETFRAMEWORK
true
#endif
);
tObjectDelegateCache.Add(propertyInfo.Name, @delegate);
}
ToDictionaryCache.Add(obejctType, tObjectDelegateCache);
}
foreach (var item in tObjectDelegateCache)
{
var value = item.Value.DynamicInvoke(@object);
var key = item.Key;
result.Add(key, value);
}
return result;
}
/// <summary>
/// 转换为字符串字典
/// </summary>
/// <typeparam name="TObject"></typeparam>
/// <param name="object"></param>
/// <param name="includeNonPublic">包含非公有属性</param>
/// <returns></returns>
public static Dictionary<string, string> ToStringDictionary<TObject>(this TObject @object, bool includeNonPublic = false)
{
var dict = @object.ToDictionary<TObject>(includeNonPublic);
var strDict = dict.ToDictionary(ks => ks.Key, es => es.Value switch { null => null, _ => Convert.ToString(es.Value) });
return strDict;
}
}
}
| 39.534884 | 143 | 0.558824 | [
"MIT"
] | SimTsai/ics-dotnet-sdk | Ics.OpenApi/Extensions/GenericExtensions.cs | 3,464 | C# |
using Microsoft.VisualBasic.ApplicationServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhotoStoreDemo
{
public class SingleInstanceManager : WindowsFormsApplicationBase
{
private SingleInstanceApplication _application;
private System.Collections.ObjectModel.ReadOnlyCollection<string> _commandLine;
public SingleInstanceManager()
{
base.IsSingleInstance = true;
}
protected override bool OnStartup(StartupEventArgs e)
{
// First time _application is launched
_commandLine = e.CommandLine;
_application = new SingleInstanceApplication();
_application.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
{
// Subsequent launches
base.OnStartupNextInstance(e);
_commandLine = e.CommandLine;
_application.Activate();
}
}
public class SingleInstanceApplication
{
App app;
public void Run()
{
app = new App();
app.Run();
}
public void Activate()
{
app.Activate();
}
}
}
| 25.685185 | 87 | 0.59553 | [
"MIT"
] | Bhaskers-Blu-Org2/AppModelSamples | Samples/SparsePackages/PhotoStoreDemo/SingleInstanceManager.cs | 1,389 | C# |
namespace BaristaLabs.ChromeDevTools.Runtime.HeapProfiler
{
using Newtonsoft.Json;
/// <summary>
/// GetSamplingProfile
/// </summary>
public sealed class GetSamplingProfileCommand : ICommand
{
private const string ChromeRemoteInterface_CommandName = "HeapProfiler.getSamplingProfile";
[JsonIgnore]
public string CommandName
{
get { return ChromeRemoteInterface_CommandName; }
}
}
public sealed class GetSamplingProfileCommandResponse : ICommandResponse<GetSamplingProfileCommand>
{
/// <summary>
/// Return the sampling profile being collected.
///</summary>
[JsonProperty("profile")]
public SamplingHeapProfile Profile
{
get;
set;
}
}
} | 25.6875 | 103 | 0.620438 | [
"MIT"
] | BaristaLabs/chrome-dev-tools-runtime | BaristaLabs.ChromeDevTools.Runtime/HeapProfiler/GetSamplingProfileCommand.cs | 822 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Contents.Text
{
public abstract class IndexCommand
{
public NamedId<DomainId> AppId { get; set; }
public NamedId<DomainId> SchemaId { get; set; }
public string DocId { get; set; }
}
}
| 31.47619 | 78 | 0.441755 | [
"MIT"
] | Appleseed/squidex | backend/src/Squidex.Domain.Apps.Entities/Contents/Text/IndexCommand.cs | 663 | C# |
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class EventBus : MonoBehaviour
{
private readonly Dictionary<string, List<EventListenerBase>> Listeners = new Dictionary<string, List<EventListenerBase>>();
public EventBus()
{
Listeners = new Dictionary<string, List<EventListenerBase>>();
}
public void AddEventListener(string eventName,ReflectEventListener listener)
{
if (!Listeners.ContainsKey(eventName))
Listeners[eventName] = new List<EventListenerBase>();
Listeners[eventName].Add(listener);
}
public void AddEventListener<T>(string eventName, Action<T> listener)
{
if (!Listeners.ContainsKey(eventName))
Listeners[eventName] = new List<EventListenerBase>();
Listeners[eventName].Add(new ActionEventListener<T>(listener));
}
public void AddEventListener(string eventName, Action listener)
{
AddEventListener<object>(eventName, (obj) => listener());
}
public void RemoveEventListener(string eventName, EventListenerBase listener)
{
if (Listeners.ContainsKey(eventName))
Listeners[eventName].Remove(listener);
}
public void Dispatch(string eventName,params object[] args)
{
if(Listeners.ContainsKey(eventName))
{
Listeners[eventName].ForEach(listener => listener.Invoke(args));
//Listeners[eventName].ForEach(listener => listener.Method.Invoke(listener.Object, args));
/*try
{
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}*/
}
}
}
| 33.75 | 128 | 0.626211 | [
"MIT"
] | SardineFish/TheLastOne | Assets/Script/Event/EventBus.cs | 1,757 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace Korduene.UI.WPF.Converters
{
public class WorkspaceItemTypeToVisibilityConverter : MarkupExtension, IValueConverter
{
public bool All { get; set; }
public bool Solution { get; set; }
public bool Project { get; set; }
public bool Folder { get; set; }
public bool File { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is WorkspaceItemType workspaceItemType))
{
return Visibility.Collapsed;
}
if (All)
{
return Visibility.Visible;
}
else if (Solution && workspaceItemType == WorkspaceItemType.Solution)
{
return Visibility.Visible;
}
else if (Project && workspaceItemType == WorkspaceItemType.Project)
{
return Visibility.Visible;
}
else if (Folder && workspaceItemType == WorkspaceItemType.Folder)
{
return Visibility.Visible;
}
else if (File && workspaceItemType == WorkspaceItemType.File)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
| 27.984127 | 103 | 0.568917 | [
"MIT"
] | Flippo24/Korduene | Korduene.UI.WPF/Converters/WorkspaceItemTypeToVisibilityConverter.cs | 1,765 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <auto-generated>
// Generated using OBeautifulCode.CodeGen.ModelObject (1.0.169.0)
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Slack.Domain.Test
{
using global::System;
using global::System.CodeDom.Compiler;
using global::System.Collections.Concurrent;
using global::System.Collections.Generic;
using global::System.Collections.ObjectModel;
using global::System.Diagnostics.CodeAnalysis;
using global::System.Globalization;
using global::System.Linq;
using global::System.Reflection;
using global::FakeItEasy;
using global::OBeautifulCode.Assertion.Recipes;
using global::OBeautifulCode.AutoFakeItEasy;
using global::OBeautifulCode.CodeGen.ModelObject.Recipes;
using global::OBeautifulCode.Equality.Recipes;
using global::OBeautifulCode.Math.Recipes;
using global::OBeautifulCode.Reflection.Recipes;
using global::OBeautifulCode.Representation.System;
using global::OBeautifulCode.Serialization;
using global::OBeautifulCode.Serialization.Recipes;
using global::OBeautifulCode.Type;
using global::Xunit;
using static global::System.FormattableString;
public static partial class SendSlackMessageRequestBaseTest
{
private static readonly SendSlackMessageRequestBase ReferenceObjectForEquatableTestScenarios = A.Dummy<SendSlackMessageRequestBase>();
private static readonly EquatableTestScenarios<SendSlackMessageRequestBase> EquatableTestScenarios = new EquatableTestScenarios<SendSlackMessageRequestBase>()
.AddScenario(() =>
new EquatableTestScenario<SendSlackMessageRequestBase>
{
Name = "Default Code Generated Scenario",
ReferenceObject = ReferenceObjectForEquatableTestScenarios,
ObjectsThatAreEqualToButNotTheSameAsReferenceObject = new SendSlackMessageRequestBase[]
{
ReferenceObjectForEquatableTestScenarios.DeepClone(),
},
ObjectsThatAreNotEqualToReferenceObject = new SendSlackMessageRequestBase[]
{
// DeepCloneWith___() methods implemented in concrete derivates throw NotSupportedException
// when the derivative's constructor in-use (by code gen) does not have a parameter that
// corresponds with the property who's value is provided in the DeepCloneWith___() method.
// We do not know in advance if this will happen. As such, the following objects are commented out.
// ReferenceObjectForEquatableTestScenarios.DeepCloneWithChannel(A.Dummy<SendSlackMessageRequestBase>().Whose(_ => !_.Channel.IsEqualTo(ReferenceObjectForEquatableTestScenarios.Channel)).Channel),
// ReferenceObjectForEquatableTestScenarios.DeepCloneWithMessageAuthorIconOverride(A.Dummy<SendSlackMessageRequestBase>().Whose(_ => !_.MessageAuthorIconOverride.IsEqualTo(ReferenceObjectForEquatableTestScenarios.MessageAuthorIconOverride)).MessageAuthorIconOverride),
// ReferenceObjectForEquatableTestScenarios.DeepCloneWithMessageAuthorUsernameOverride(A.Dummy<SendSlackMessageRequestBase>().Whose(_ => !_.MessageAuthorUsernameOverride.IsEqualTo(ReferenceObjectForEquatableTestScenarios.MessageAuthorUsernameOverride)).MessageAuthorUsernameOverride),
},
ObjectsThatAreNotOfTheSameTypeAsReferenceObject = new object[]
{
A.Dummy<object>(),
A.Dummy<string>(),
A.Dummy<int>(),
A.Dummy<int?>(),
A.Dummy<Guid>(),
},
});
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Structural
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void SendSlackMessageRequestBase___Should_implement_IModel_of_SendSlackMessageRequestBase___When_reflecting()
{
// Arrange
var type = typeof(SendSlackMessageRequestBase);
var expectedModelMethods = typeof(IModel<SendSlackMessageRequestBase>).GetInterfaceDeclaredAndImplementedMethods();
var expectedModelMethodHashes = expectedModelMethods.Select(_ => _.GetSignatureHash());
// Act
var actualInterfaces = type.GetInterfaces();
var actualModelMethods = type.GetMethodsFiltered(MemberRelationships.DeclaredOrInherited, MemberOwners.Instance, MemberAccessModifiers.Public).ToList();
var actualModelMethodHashes = actualModelMethods.Select(_ => _.GetSignatureHash());
// Assert
actualInterfaces.AsTest().Must().ContainElement(typeof(IModel<SendSlackMessageRequestBase>));
expectedModelMethodHashes.Except(actualModelMethodHashes).AsTest().Must().BeEmptyEnumerable();
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void SendSlackMessageRequestBase___Should_be_attributed_with_Serializable____When_reflecting()
{
// Arrange
var type = typeof(SendSlackMessageRequestBase);
// Act
var actualAttributes = type.GetCustomAttributes(typeof(SerializableAttribute), false);
// Assert
actualAttributes.AsTest().Must().NotBeEmptyEnumerable();
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Cloning
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Clone___Should_clone_object___When_called()
{
// Arrange
var systemUnderTest = A.Dummy<SendSlackMessageRequestBase>();
// Act
var actual = (SendSlackMessageRequestBase)systemUnderTest.Clone();
// Assert
actual.AsTest().Must().BeEqualTo(systemUnderTest);
actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void DeepClone___Should_deep_clone_object___When_called()
{
// Arrange
var systemUnderTest = A.Dummy<SendSlackMessageRequestBase>();
// Act
var actual = systemUnderTest.DeepClone();
// Assert
actual.AsTest().Must().BeEqualTo(systemUnderTest);
actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest);
if (systemUnderTest.MessageAuthorIconOverride == null)
{
actual.MessageAuthorIconOverride.AsTest().Must().BeNull();
}
else if (!actual.MessageAuthorIconOverride.GetType().IsValueType)
{
// When the declared type is a reference type, we still have to check the runtime type.
// The object could be a boxed value type, which will fail this asseration because
// a deep clone of a value type object is the same object.
actual.MessageAuthorIconOverride.AsTest().Must().NotBeSameReferenceAs(systemUnderTest.MessageAuthorIconOverride);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Serialization
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcBsonSerializer()
{
// Arrange
var expected = A.Dummy<SendSlackMessageRequestBase>();
var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.String };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcBsonSerializer()
{
// Arrange
var expected = A.Dummy<SendSlackMessageRequestBase>();
var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.Binary };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcJsonSerializer()
{
// Arrange
var expected = A.Dummy<SendSlackMessageRequestBase>();
var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.String };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcJsonSerializer()
{
// Arrange
var expected = A.Dummy<SendSlackMessageRequestBase>();
var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.Binary };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Equality
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_true___When_both_sides_of_operator_are_null()
{
// Arrange
SendSlackMessageRequestBase systemUnderTest1 = null;
SendSlackMessageRequestBase systemUnderTest2 = null;
// Act
var actual = systemUnderTest1 == systemUnderTest2;
// Assert
actual.AsTest().Must().BeTrue();
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_false___When_one_side_of_operator_is_null_and_the_other_side_is_not_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
SendSlackMessageRequestBase systemUnderTest = null;
// Act
var actual1 = systemUnderTest == scenario.ReferenceObject;
var actual2 = scenario.ReferenceObject == systemUnderTest;
// Assert
actual1.AsTest().Must().BeFalse(because: scenario.Id);
actual2.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_true___When_same_object_is_on_both_sides_of_operator()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
#pragma warning disable CS1718 // Comparison made to same variable
var actual = scenario.ReferenceObject == scenario.ReferenceObject;
#pragma warning restore CS1718 // Comparison made to same variable
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_false___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList();
var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList();
var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList();
var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id);
actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_false___When_both_sides_of_operator_are_null()
{
// Arrange
SendSlackMessageRequestBase systemUnderTest1 = null;
SendSlackMessageRequestBase systemUnderTest2 = null;
// Act
var actual = systemUnderTest1 != systemUnderTest2;
// Assert
actual.AsTest().Must().BeFalse();
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_true___When_one_side_of_operator_is_null_and_the_other_side_is_not_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
SendSlackMessageRequestBase systemUnderTest = null;
// Act
var actual1 = systemUnderTest != scenario.ReferenceObject;
var actual2 = scenario.ReferenceObject != systemUnderTest;
// Assert
actual1.AsTest().Must().BeTrue(because: scenario.Id);
actual2.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_false___When_same_object_is_on_both_sides_of_operator()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
#pragma warning disable CS1718 // Comparison made to same variable
var actual = scenario.ReferenceObject != scenario.ReferenceObject;
#pragma warning restore CS1718 // Comparison made to same variable
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList();
var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id);
actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList();
var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id);
actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_false___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList();
var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_SendSlackMessageRequestBase___Should_return_false___When_parameter_other_is_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
SendSlackMessageRequestBase systemUnderTest = null;
// Act
var actual = scenario.ReferenceObject.Equals(systemUnderTest);
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_SendSlackMessageRequestBase___Should_return_true___When_parameter_other_is_same_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals(scenario.ReferenceObject);
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_SendSlackMessageRequestBase___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_SendSlackMessageRequestBase___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_SendSlackMessageRequestBase___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_false___When_parameter_other_is_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals((object)null);
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_false___When_parameter_other_is_not_of_the_same_type()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
var actuals2 = scenario.ObjectsThatAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_true___When_parameter_other_is_same_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals((object)scenario.ReferenceObject);
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Hashing
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void GetHashCode___Should_not_be_equal_for_two_objects___When_objects_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var unexpected = scenario.ReferenceObject.GetHashCode();
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _.GetHashCode()).ToList();
// Assert
actuals.AsTest().Must().NotContainElement(unexpected, because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void GetHashCode___Should_be_equal_for_two_objects___When_objects_have_the_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var expected = scenario.ReferenceObject.GetHashCode();
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _.GetHashCode()).ToList();
// Assert
actuals.AsTest().Must().Each().BeEqualTo(expected, because: scenario.Id);
}
}
}
}
} | 66.819404 | 308 | 0.682399 | [
"MIT"
] | NaosProject/Naos.Slack | Naos.Slack.Domain.Test/Models/Classes/Message/SendSlackMessageRequestBaseTest.designer.cs | 69,561 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace APILibrary.Models
{
public class ShortRate
{
/// <summary>
/// Internal code (внутренний код)
/// </summary>
public int Cur_ID { get; set; }
/// <summary>
/// Date (дата, на которую запрашивается курс)
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Rate (курс)
/// </summary>
public decimal Cur_OfficialRate { get; set; }
}
}
| 21.44 | 54 | 0.539179 | [
"MIT"
] | Mazepin/TMS-DotNet-Mazepin | Mazepin.Homework12 Nbrb/TMS.Homework.Nbrb/APILibrary/Models/ShortRate.cs | 585 | C# |
#pragma checksum "..\..\..\..\Views\Windows\MsgWindow.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "F6618B2A22ED005DD55344B04189E9DBDE52BAA2FE91879F9FEBA5534359BF8E"
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using BLL.Template.Converters;
using BLL.Template.Converters.Msg;
using HandyControl.Controls;
using HandyControl.Data;
using HandyControl.Expression.Media;
using HandyControl.Expression.Shapes;
using HandyControl.Interactivity;
using HandyControl.Media.Animation;
using HandyControl.Media.Effects;
using HandyControl.Properties.Langs;
using HandyControl.Themes;
using HandyControl.Tools;
using HandyControl.Tools.Converter;
using HandyControl.Tools.Extension;
using MaterialDesignThemes.Wpf;
using MaterialDesignThemes.Wpf.Converters;
using MaterialDesignThemes.Wpf.Transitions;
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.Interactivity;
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 WPF.UIL.Template.ViewModels.Windows;
using WPF.UIL.Template.Views.Windows;
namespace WPF.UIL.Template.Views.Windows {
/// <summary>
/// MsgWindow
/// </summary>
public partial class MsgWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {
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;
System.Uri resourceLocater = new System.Uri("/WPF.UIL.Template;component/views/windows/msgwindow.xaml", System.UriKind.Relative);
#line 1 "..\..\..\..\Views\Windows\MsgWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
| 38.273684 | 168 | 0.703245 | [
"MIT"
] | WuPan001/Wp.Helper | WPF.UIL.Template/obj/Debug/Views/Windows/MsgWindow.g.cs | 3,744 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Rendering;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Forums;
using Nop.Core.Domain.Gdpr;
using Nop.Core.Domain.Media;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Security;
using Nop.Core.Domain.Tax;
using Nop.Core.Domain.Vendors;
using Nop.Services.Authentication.External;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Gdpr;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Media;
using Nop.Services.Messages;
using Nop.Services.Orders;
using Nop.Services.Seo;
using Nop.Services.Stores;
using Nop.Web.Models.Common;
using Nop.Web.Models.Customer;
namespace Nop.Web.Factories
{
/// <summary>
/// Represents the customer model factory
/// </summary>
public partial class CustomerModelFactory : ICustomerModelFactory
{
#region Fields
private readonly AddressSettings _addressSettings;
private readonly CaptchaSettings _captchaSettings;
private readonly CatalogSettings _catalogSettings;
private readonly CommonSettings _commonSettings;
private readonly CustomerSettings _customerSettings;
private readonly DateTimeSettings _dateTimeSettings;
private readonly ExternalAuthenticationSettings _externalAuthenticationSettings;
private readonly ForumSettings _forumSettings;
private readonly GdprSettings _gdprSettings;
private readonly IAddressModelFactory _addressModelFactory;
private readonly IAuthenticationPluginManager _authenticationPluginManager;
private readonly ICountryService _countryService;
private readonly ICustomerAttributeParser _customerAttributeParser;
private readonly ICustomerAttributeService _customerAttributeService;
private readonly IDateTimeHelper _dateTimeHelper;
private readonly IDownloadService _downloadService;
private readonly IGdprService _gdprService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ILocalizationService _localizationService;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly IOrderService _orderService;
private readonly IPictureService _pictureService;
private readonly IReturnRequestService _returnRequestService;
private readonly IStateProvinceService _stateProvinceService;
private readonly IStoreContext _storeContext;
private readonly IStoreMappingService _storeMappingService;
private readonly IUrlRecordService _urlRecordService;
private readonly IWorkContext _workContext;
private readonly MediaSettings _mediaSettings;
private readonly OrderSettings _orderSettings;
private readonly RewardPointsSettings _rewardPointsSettings;
private readonly SecuritySettings _securitySettings;
private readonly TaxSettings _taxSettings;
private readonly VendorSettings _vendorSettings;
#endregion
#region Ctor
public CustomerModelFactory(AddressSettings addressSettings,
CaptchaSettings captchaSettings,
CatalogSettings catalogSettings,
CommonSettings commonSettings,
CustomerSettings customerSettings,
DateTimeSettings dateTimeSettings,
ExternalAuthenticationSettings externalAuthenticationSettings,
ForumSettings forumSettings,
GdprSettings gdprSettings,
IAddressModelFactory addressModelFactory,
IAuthenticationPluginManager authenticationPluginManager,
ICountryService countryService,
ICustomerAttributeParser customerAttributeParser,
ICustomerAttributeService customerAttributeService,
IDateTimeHelper dateTimeHelper,
IDownloadService downloadService,
IGdprService gdprService,
IGenericAttributeService genericAttributeService,
ILocalizationService localizationService,
INewsLetterSubscriptionService newsLetterSubscriptionService,
IOrderService orderService,
IPictureService pictureService,
IReturnRequestService returnRequestService,
IStateProvinceService stateProvinceService,
IStoreContext storeContext,
IStoreMappingService storeMappingService,
IUrlRecordService urlRecordService,
IWorkContext workContext,
MediaSettings mediaSettings,
OrderSettings orderSettings,
RewardPointsSettings rewardPointsSettings,
SecuritySettings securitySettings,
TaxSettings taxSettings,
VendorSettings vendorSettings)
{
_addressSettings = addressSettings;
_captchaSettings = captchaSettings;
_catalogSettings = catalogSettings;
_commonSettings = commonSettings;
_customerSettings = customerSettings;
_dateTimeSettings = dateTimeSettings;
_externalAuthenticationSettings = externalAuthenticationSettings;
_forumSettings = forumSettings;
_gdprSettings = gdprSettings;
_addressModelFactory = addressModelFactory;
_authenticationPluginManager = authenticationPluginManager;
_countryService = countryService;
_customerAttributeParser = customerAttributeParser;
_customerAttributeService = customerAttributeService;
_dateTimeHelper = dateTimeHelper;
_downloadService = downloadService;
_gdprService = gdprService;
_genericAttributeService = genericAttributeService;
_localizationService = localizationService;
_newsLetterSubscriptionService = newsLetterSubscriptionService;
_orderService = orderService;
_pictureService = pictureService;
_returnRequestService = returnRequestService;
_stateProvinceService = stateProvinceService;
_storeContext = storeContext;
_storeMappingService = storeMappingService;
_urlRecordService = urlRecordService;
_workContext = workContext;
_mediaSettings = mediaSettings;
_orderSettings = orderSettings;
_rewardPointsSettings = rewardPointsSettings;
_securitySettings = securitySettings;
_taxSettings = taxSettings;
_vendorSettings = vendorSettings;
}
#endregion
#region Utilities
protected virtual GdprConsentModel PrepareGdprConsentModel(GdprConsent consent, bool accepted)
{
if (consent == null)
throw new ArgumentNullException(nameof(consent));
var requiredMessage = _localizationService.GetLocalized(consent, x => x.RequiredMessage);
return new GdprConsentModel
{
Id = consent.Id,
Message = _localizationService.GetLocalized(consent, x => x.Message),
IsRequired = consent.IsRequired,
RequiredMessage = !string.IsNullOrEmpty(requiredMessage) ? requiredMessage : $"'{consent.Message}' is required",
Accepted = accepted
};
}
#endregion
#region Methods
/// <summary>
/// Prepare the custom customer attribute models
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="overrideAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param>
/// <returns>List of the customer attribute model</returns>
public virtual IList<CustomerAttributeModel> PrepareCustomCustomerAttributes(Customer customer, string overrideAttributesXml = "")
{
if (customer == null)
throw new ArgumentNullException(nameof(customer));
var result = new List<CustomerAttributeModel>();
var customerAttributes = _customerAttributeService.GetAllCustomerAttributes();
foreach (var attribute in customerAttributes)
{
var attributeModel = new CustomerAttributeModel
{
Id = attribute.Id,
Name = _localizationService.GetLocalized(attribute, x => x.Name),
IsRequired = attribute.IsRequired,
AttributeControlType = attribute.AttributeControlType,
};
if (attribute.ShouldHaveValues())
{
//values
var attributeValues = _customerAttributeService.GetCustomerAttributeValues(attribute.Id);
foreach (var attributeValue in attributeValues)
{
var valueModel = new CustomerAttributeValueModel
{
Id = attributeValue.Id,
Name = _localizationService.GetLocalized(attributeValue, x => x.Name),
IsPreSelected = attributeValue.IsPreSelected
};
attributeModel.Values.Add(valueModel);
}
}
//set already selected attributes
var selectedAttributesXml = !string.IsNullOrEmpty(overrideAttributesXml) ?
overrideAttributesXml :
_genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.CustomCustomerAttributes);
switch (attribute.AttributeControlType)
{
case AttributeControlType.DropdownList:
case AttributeControlType.RadioList:
case AttributeControlType.Checkboxes:
{
if (!string.IsNullOrEmpty(selectedAttributesXml))
{
//clear default selection
foreach (var item in attributeModel.Values)
item.IsPreSelected = false;
//select new values
var selectedValues = _customerAttributeParser.ParseCustomerAttributeValues(selectedAttributesXml);
foreach (var attributeValue in selectedValues)
foreach (var item in attributeModel.Values)
if (attributeValue.Id == item.Id)
item.IsPreSelected = true;
}
}
break;
case AttributeControlType.ReadonlyCheckboxes:
{
//do nothing
//values are already pre-set
}
break;
case AttributeControlType.TextBox:
case AttributeControlType.MultilineTextbox:
{
if (!string.IsNullOrEmpty(selectedAttributesXml))
{
var enteredText = _customerAttributeParser.ParseValues(selectedAttributesXml, attribute.Id);
if (enteredText.Any())
attributeModel.DefaultValue = enteredText[0];
}
}
break;
case AttributeControlType.ColorSquares:
case AttributeControlType.ImageSquares:
case AttributeControlType.Datepicker:
case AttributeControlType.FileUpload:
default:
//not supported attribute control types
break;
}
result.Add(attributeModel);
}
return result;
}
/// <summary>
/// Prepare the customer info model
/// </summary>
/// <param name="model">Customer info model</param>
/// <param name="customer">Customer</param>
/// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
/// <param name="overrideCustomCustomerAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param>
/// <returns>Customer info model</returns>
public virtual CustomerInfoModel PrepareCustomerInfoModel(CustomerInfoModel model, Customer customer,
bool excludeProperties, string overrideCustomCustomerAttributesXml = "")
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (customer == null)
throw new ArgumentNullException(nameof(customer));
model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone;
foreach (var tzi in _dateTimeHelper.GetSystemTimeZones())
model.AvailableTimeZones.Add(new SelectListItem { Text = tzi.DisplayName, Value = tzi.Id, Selected = (excludeProperties ? tzi.Id == model.TimeZoneId : tzi.Id == _dateTimeHelper.CurrentTimeZone.Id) });
if (!excludeProperties)
{
model.VatNumber = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.VatNumberAttribute);
model.FirstName = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.FirstNameAttribute);
model.LastName = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.LastNameAttribute);
model.Gender = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.GenderAttribute);
var dateOfBirth = _genericAttributeService.GetAttribute<DateTime?>(customer, NopCustomerDefaults.DateOfBirthAttribute);
if (dateOfBirth.HasValue)
{
model.DateOfBirthDay = dateOfBirth.Value.Day;
model.DateOfBirthMonth = dateOfBirth.Value.Month;
model.DateOfBirthYear = dateOfBirth.Value.Year;
}
model.Company = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.CompanyAttribute);
model.StreetAddress = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.StreetAddressAttribute);
model.StreetAddress2 = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.StreetAddress2Attribute);
model.ZipPostalCode = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute);
model.City = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.CityAttribute);
model.County = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.CountyAttribute);
model.CountryId = _genericAttributeService.GetAttribute<int>(customer, NopCustomerDefaults.CountryIdAttribute);
model.StateProvinceId = _genericAttributeService.GetAttribute<int>(customer, NopCustomerDefaults.StateProvinceIdAttribute);
model.Phone = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.PhoneAttribute);
model.Fax = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.FaxAttribute);
//newsletter
var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, _storeContext.CurrentStore.Id);
model.Newsletter = newsletter != null && newsletter.Active;
model.Signature = _genericAttributeService.GetAttribute<string>(customer, NopCustomerDefaults.SignatureAttribute);
model.Email = customer.Email;
model.Username = customer.Username;
}
else
{
if (_customerSettings.UsernamesEnabled && !_customerSettings.AllowUsersToChangeUsernames)
model.Username = customer.Username;
}
if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
model.EmailToRevalidate = customer.EmailToRevalidate;
//countries and states
if (_customerSettings.CountryEnabled)
{
model.AvailableCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries(_workContext.WorkingLanguage.Id))
{
model.AvailableCountries.Add(new SelectListItem
{
Text = _localizationService.GetLocalized(c, x => x.Name),
Value = c.Id.ToString(),
Selected = c.Id == model.CountryId
});
}
if (_customerSettings.StateProvinceEnabled)
{
//states
var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId, _workContext.WorkingLanguage.Id).ToList();
if (states.Any())
{
model.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource("Address.SelectState"), Value = "0" });
foreach (var s in states)
{
model.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetLocalized(s, x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId) });
}
}
else
{
var anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
model.AvailableStates.Add(new SelectListItem
{
Text = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
Value = "0"
});
}
}
}
model.DisplayVatNumber = _taxSettings.EuVatEnabled;
model.VatNumberStatusNote = _localizationService.GetLocalizedEnum((VatNumberStatus)_genericAttributeService
.GetAttribute<int>(customer, NopCustomerDefaults.VatNumberStatusIdAttribute));
model.GenderEnabled = _customerSettings.GenderEnabled;
model.DateOfBirthEnabled = _customerSettings.DateOfBirthEnabled;
model.DateOfBirthRequired = _customerSettings.DateOfBirthRequired;
model.CompanyEnabled = _customerSettings.CompanyEnabled;
model.CompanyRequired = _customerSettings.CompanyRequired;
model.StreetAddressEnabled = _customerSettings.StreetAddressEnabled;
model.StreetAddressRequired = _customerSettings.StreetAddressRequired;
model.StreetAddress2Enabled = _customerSettings.StreetAddress2Enabled;
model.StreetAddress2Required = _customerSettings.StreetAddress2Required;
model.ZipPostalCodeEnabled = _customerSettings.ZipPostalCodeEnabled;
model.ZipPostalCodeRequired = _customerSettings.ZipPostalCodeRequired;
model.CityEnabled = _customerSettings.CityEnabled;
model.CityRequired = _customerSettings.CityRequired;
model.CountyEnabled = _customerSettings.CountyEnabled;
model.CountyRequired = _customerSettings.CountyRequired;
model.CountryEnabled = _customerSettings.CountryEnabled;
model.CountryRequired = _customerSettings.CountryRequired;
model.StateProvinceEnabled = _customerSettings.StateProvinceEnabled;
model.StateProvinceRequired = _customerSettings.StateProvinceRequired;
model.PhoneEnabled = _customerSettings.PhoneEnabled;
model.PhoneRequired = _customerSettings.PhoneRequired;
model.FaxEnabled = _customerSettings.FaxEnabled;
model.FaxRequired = _customerSettings.FaxRequired;
model.NewsletterEnabled = _customerSettings.NewsletterEnabled;
model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
model.AllowUsersToChangeUsernames = _customerSettings.AllowUsersToChangeUsernames;
model.CheckUsernameAvailabilityEnabled = _customerSettings.CheckUsernameAvailabilityEnabled;
model.SignatureEnabled = _forumSettings.ForumsEnabled && _forumSettings.SignaturesEnabled;
//external authentication
model.AllowCustomersToRemoveAssociations = _externalAuthenticationSettings.AllowCustomersToRemoveAssociations;
model.NumberOfExternalAuthenticationProviders = _authenticationPluginManager
.LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id)
.Count;
foreach (var record in customer.ExternalAuthenticationRecords)
{
var authMethod = _authenticationPluginManager.LoadPluginBySystemName(record.ProviderSystemName);
if (!_authenticationPluginManager.IsPluginActive(authMethod))
continue;
model.AssociatedExternalAuthRecords.Add(new CustomerInfoModel.AssociatedExternalAuthModel
{
Id = record.Id,
Email = record.Email,
ExternalIdentifier = !string.IsNullOrEmpty(record.ExternalDisplayIdentifier)
? record.ExternalDisplayIdentifier : record.ExternalIdentifier,
AuthMethodName = _localizationService.GetLocalizedFriendlyName(authMethod, _workContext.WorkingLanguage.Id)
});
}
//custom customer attributes
var customAttributes = PrepareCustomCustomerAttributes(customer, overrideCustomCustomerAttributesXml);
foreach (var attribute in customAttributes)
model.CustomerAttributes.Add(attribute);
//GDPR
if (_gdprSettings.GdprEnabled)
{
var consents = _gdprService.GetAllConsents().Where(consent => consent.DisplayOnCustomerInfoPage).ToList();
foreach (var consent in consents)
{
var accepted = _gdprService.IsConsentAccepted(consent.Id, _workContext.CurrentCustomer.Id);
model.GdprConsents.Add(PrepareGdprConsentModel(consent, accepted.HasValue && accepted.Value));
}
}
return model;
}
/// <summary>
/// Prepare the customer register model
/// </summary>
/// <param name="model">Customer register model</param>
/// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
/// <param name="overrideCustomCustomerAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param>
/// <param name="setDefaultValues">Whether to populate model properties by default values</param>
/// <returns>Customer register model</returns>
public virtual RegisterModel PrepareRegisterModel(RegisterModel model, bool excludeProperties,
string overrideCustomCustomerAttributesXml = "", bool setDefaultValues = false)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone;
foreach (var tzi in _dateTimeHelper.GetSystemTimeZones())
model.AvailableTimeZones.Add(new SelectListItem { Text = tzi.DisplayName, Value = tzi.Id, Selected = (excludeProperties ? tzi.Id == model.TimeZoneId : tzi.Id == _dateTimeHelper.CurrentTimeZone.Id) });
model.DisplayVatNumber = _taxSettings.EuVatEnabled;
//form fields
model.GenderEnabled = _customerSettings.GenderEnabled;
model.DateOfBirthEnabled = _customerSettings.DateOfBirthEnabled;
model.DateOfBirthRequired = _customerSettings.DateOfBirthRequired;
model.CompanyEnabled = _customerSettings.CompanyEnabled;
model.CompanyRequired = _customerSettings.CompanyRequired;
model.StreetAddressEnabled = _customerSettings.StreetAddressEnabled;
model.StreetAddressRequired = _customerSettings.StreetAddressRequired;
model.StreetAddress2Enabled = _customerSettings.StreetAddress2Enabled;
model.StreetAddress2Required = _customerSettings.StreetAddress2Required;
model.ZipPostalCodeEnabled = _customerSettings.ZipPostalCodeEnabled;
model.ZipPostalCodeRequired = _customerSettings.ZipPostalCodeRequired;
model.CityEnabled = _customerSettings.CityEnabled;
model.CityRequired = _customerSettings.CityRequired;
model.CountyEnabled = _customerSettings.CountyEnabled;
model.CountyRequired = _customerSettings.CountyRequired;
model.CountryEnabled = _customerSettings.CountryEnabled;
model.CountryRequired = _customerSettings.CountryRequired;
model.StateProvinceEnabled = _customerSettings.StateProvinceEnabled;
model.StateProvinceRequired = _customerSettings.StateProvinceRequired;
model.PhoneEnabled = _customerSettings.PhoneEnabled;
model.PhoneRequired = _customerSettings.PhoneRequired;
model.FaxEnabled = _customerSettings.FaxEnabled;
model.FaxRequired = _customerSettings.FaxRequired;
model.NewsletterEnabled = _customerSettings.NewsletterEnabled;
model.AcceptPrivacyPolicyEnabled = _customerSettings.AcceptPrivacyPolicyEnabled;
model.AcceptPrivacyPolicyPopup = _commonSettings.PopupForTermsOfServiceLinks;
model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
model.CheckUsernameAvailabilityEnabled = _customerSettings.CheckUsernameAvailabilityEnabled;
model.HoneypotEnabled = _securitySettings.HoneypotEnabled;
model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage;
model.EnteringEmailTwice = _customerSettings.EnteringEmailTwice;
if (setDefaultValues)
{
//enable newsletter by default
model.Newsletter = _customerSettings.NewsletterTickedByDefault;
}
//countries and states
if (_customerSettings.CountryEnabled)
{
model.AvailableCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" });
foreach (var c in _countryService.GetAllCountries(_workContext.WorkingLanguage.Id))
{
model.AvailableCountries.Add(new SelectListItem
{
Text = _localizationService.GetLocalized(c, x => x.Name),
Value = c.Id.ToString(),
Selected = c.Id == model.CountryId
});
}
if (_customerSettings.StateProvinceEnabled)
{
//states
var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId, _workContext.WorkingLanguage.Id).ToList();
if (states.Any())
{
model.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource("Address.SelectState"), Value = "0" });
foreach (var s in states)
{
model.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetLocalized(s, x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId) });
}
}
else
{
var anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
model.AvailableStates.Add(new SelectListItem
{
Text = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
Value = "0"
});
}
}
}
//custom customer attributes
var customAttributes = PrepareCustomCustomerAttributes(_workContext.CurrentCustomer, overrideCustomCustomerAttributesXml);
foreach (var attribute in customAttributes)
model.CustomerAttributes.Add(attribute);
//GDPR
if (_gdprSettings.GdprEnabled)
{
var consents = _gdprService.GetAllConsents().Where(consent => consent.DisplayDuringRegistration).ToList();
foreach (var consent in consents)
{
model.GdprConsents.Add(PrepareGdprConsentModel(consent, false));
}
}
return model;
}
/// <summary>
/// Prepare the login model
/// </summary>
/// <param name="checkoutAsGuest">Whether to checkout as guest is enabled</param>
/// <returns>Login model</returns>
public virtual LoginModel PrepareLoginModel(bool? checkoutAsGuest)
{
var model = new LoginModel
{
UsernamesEnabled = _customerSettings.UsernamesEnabled,
RegistrationType = _customerSettings.UserRegistrationType,
CheckoutAsGuest = checkoutAsGuest.GetValueOrDefault(),
DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage
};
return model;
}
/// <summary>
/// Prepare the password recovery model
/// </summary>
/// <returns>Password recovery model</returns>
public virtual PasswordRecoveryModel PreparePasswordRecoveryModel()
{
var model = new PasswordRecoveryModel
{
DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnForgotPasswordPage
};
return model;
}
/// <summary>
/// Prepare the password recovery confirm model
/// </summary>
/// <returns>Password recovery confirm model</returns>
public virtual PasswordRecoveryConfirmModel PreparePasswordRecoveryConfirmModel()
{
var model = new PasswordRecoveryConfirmModel();
return model;
}
/// <summary>
/// Prepare the register result model
/// </summary>
/// <param name="resultId">Value of UserRegistrationType enum</param>
/// <returns>Register result model</returns>
public virtual RegisterResultModel PrepareRegisterResultModel(int resultId)
{
var resultText = "";
switch ((UserRegistrationType)resultId)
{
case UserRegistrationType.Disabled:
resultText = _localizationService.GetResource("Account.Register.Result.Disabled");
break;
case UserRegistrationType.Standard:
resultText = _localizationService.GetResource("Account.Register.Result.Standard");
break;
case UserRegistrationType.AdminApproval:
resultText = _localizationService.GetResource("Account.Register.Result.AdminApproval");
break;
case UserRegistrationType.EmailValidation:
resultText = _localizationService.GetResource("Account.Register.Result.EmailValidation");
break;
default:
break;
}
var model = new RegisterResultModel
{
Result = resultText
};
return model;
}
/// <summary>
/// Prepare the customer navigation model
/// </summary>
/// <param name="selectedTabId">Identifier of the selected tab</param>
/// <returns>Customer navigation model</returns>
public virtual CustomerNavigationModel PrepareCustomerNavigationModel(int selectedTabId = 0)
{
var model = new CustomerNavigationModel();
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerInfo",
Title = _localizationService.GetResource("Account.CustomerInfo"),
Tab = CustomerNavigationEnum.Info,
ItemClass = "customer-info"
});
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerAddresses",
Title = _localizationService.GetResource("Account.CustomerAddresses"),
Tab = CustomerNavigationEnum.Addresses,
ItemClass = "customer-addresses"
});
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerOrders",
Title = _localizationService.GetResource("Account.CustomerOrders"),
Tab = CustomerNavigationEnum.Orders,
ItemClass = "customer-orders"
});
if (_orderSettings.ReturnRequestsEnabled &&
_returnRequestService.SearchReturnRequests(_storeContext.CurrentStore.Id,
_workContext.CurrentCustomer.Id, pageIndex: 0, pageSize: 1).Any())
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerReturnRequests",
Title = _localizationService.GetResource("Account.CustomerReturnRequests"),
Tab = CustomerNavigationEnum.ReturnRequests,
ItemClass = "return-requests"
});
}
if (!_customerSettings.HideDownloadableProductsTab)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerDownloadableProducts",
Title = _localizationService.GetResource("Account.DownloadableProducts"),
Tab = CustomerNavigationEnum.DownloadableProducts,
ItemClass = "downloadable-products"
});
}
if (!_customerSettings.HideBackInStockSubscriptionsTab)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerBackInStockSubscriptions",
Title = _localizationService.GetResource("Account.BackInStockSubscriptions"),
Tab = CustomerNavigationEnum.BackInStockSubscriptions,
ItemClass = "back-in-stock-subscriptions"
});
}
if (_rewardPointsSettings.Enabled)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerRewardPoints",
Title = _localizationService.GetResource("Account.RewardPoints"),
Tab = CustomerNavigationEnum.RewardPoints,
ItemClass = "reward-points"
});
}
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerChangePassword",
Title = _localizationService.GetResource("Account.ChangePassword"),
Tab = CustomerNavigationEnum.ChangePassword,
ItemClass = "change-password"
});
if (_customerSettings.AllowCustomersToUploadAvatars)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerAvatar",
Title = _localizationService.GetResource("Account.Avatar"),
Tab = CustomerNavigationEnum.Avatar,
ItemClass = "customer-avatar"
});
}
if (_forumSettings.ForumsEnabled && _forumSettings.AllowCustomersToManageSubscriptions)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerForumSubscriptions",
Title = _localizationService.GetResource("Account.ForumSubscriptions"),
Tab = CustomerNavigationEnum.ForumSubscriptions,
ItemClass = "forum-subscriptions"
});
}
if (_catalogSettings.ShowProductReviewsTabOnAccountPage)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerProductReviews",
Title = _localizationService.GetResource("Account.CustomerProductReviews"),
Tab = CustomerNavigationEnum.ProductReviews,
ItemClass = "customer-reviews"
});
}
if (_vendorSettings.AllowVendorsToEditInfo && _workContext.CurrentVendor != null)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CustomerVendorInfo",
Title = _localizationService.GetResource("Account.VendorInfo"),
Tab = CustomerNavigationEnum.VendorInfo,
ItemClass = "customer-vendor-info"
});
}
if (_gdprSettings.GdprEnabled)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "GdprTools",
Title = _localizationService.GetResource("Account.Gdpr"),
Tab = CustomerNavigationEnum.GdprTools,
ItemClass = "customer-gdpr"
});
}
if (_captchaSettings.Enabled && _customerSettings.AllowCustomersToCheckGiftCardBalance)
{
model.CustomerNavigationItems.Add(new CustomerNavigationItemModel
{
RouteName = "CheckGiftCardBalance",
Title = _localizationService.GetResource("CheckGiftCardBalance"),
Tab = CustomerNavigationEnum.CheckGiftCardBalance,
ItemClass = "customer-check-gift-card-balance"
});
}
model.SelectedTab = (CustomerNavigationEnum)selectedTabId;
return model;
}
/// <summary>
/// Prepare the customer address list model
/// </summary>
/// <returns>Customer address list model</returns>
public virtual CustomerAddressListModel PrepareCustomerAddressListModel()
{
var addresses = _workContext.CurrentCustomer.Addresses
//enabled for the current store
.Where(a => a.Country == null || _storeMappingService.Authorize(a.Country))
.ToList();
var model = new CustomerAddressListModel();
foreach (var address in addresses)
{
var addressModel = new AddressModel();
_addressModelFactory.PrepareAddressModel(addressModel,
address: address,
excludeProperties: false,
addressSettings: _addressSettings,
loadCountries: () => _countryService.GetAllCountries(_workContext.WorkingLanguage.Id));
model.Addresses.Add(addressModel);
}
return model;
}
/// <summary>
/// Prepare the customer downloadable products model
/// </summary>
/// <returns>Customer downloadable products model</returns>
public virtual CustomerDownloadableProductsModel PrepareCustomerDownloadableProductsModel()
{
var model = new CustomerDownloadableProductsModel();
var items = _orderService.GetDownloadableOrderItems(_workContext.CurrentCustomer.Id);
foreach (var item in items)
{
var itemModel = new CustomerDownloadableProductsModel.DownloadableProductsModel
{
OrderItemGuid = item.OrderItemGuid,
OrderId = item.OrderId,
CustomOrderNumber = item.Order.CustomOrderNumber,
CreatedOn = _dateTimeHelper.ConvertToUserTime(item.Order.CreatedOnUtc, DateTimeKind.Utc),
ProductName = _localizationService.GetLocalized(item.Product, x => x.Name),
ProductSeName = _urlRecordService.GetSeName(item.Product),
ProductAttributes = item.AttributeDescription,
ProductId = item.ProductId
};
model.Items.Add(itemModel);
if (_downloadService.IsDownloadAllowed(item))
itemModel.DownloadId = item.Product.DownloadId;
if (_downloadService.IsLicenseDownloadAllowed(item))
itemModel.LicenseId = item.LicenseDownloadId.HasValue ? item.LicenseDownloadId.Value : 0;
}
return model;
}
/// <summary>
/// Prepare the user agreement model
/// </summary>
/// <param name="orderItem">Order item</param>
/// <param name="product">Product</param>
/// <returns>User agreement model</returns>
public virtual UserAgreementModel PrepareUserAgreementModel(OrderItem orderItem, Product product)
{
if (orderItem == null)
throw new ArgumentNullException(nameof(orderItem));
if (product == null)
throw new ArgumentNullException(nameof(product));
var model = new UserAgreementModel
{
UserAgreementText = product.UserAgreementText,
OrderItemGuid = orderItem.OrderItemGuid
};
return model;
}
/// <summary>
/// Prepare the change password model
/// </summary>
/// <returns>Change password model</returns>
public virtual ChangePasswordModel PrepareChangePasswordModel()
{
var model = new ChangePasswordModel();
return model;
}
/// <summary>
/// Prepare the customer avatar model
/// </summary>
/// <param name="model">Customer avatar model</param>
/// <returns>Customer avatar model</returns>
public virtual CustomerAvatarModel PrepareCustomerAvatarModel(CustomerAvatarModel model)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
model.AvatarUrl = _pictureService.GetPictureUrl(
_genericAttributeService.GetAttribute<int>(_workContext.CurrentCustomer, NopCustomerDefaults.AvatarPictureIdAttribute),
_mediaSettings.AvatarPictureSize,
false);
return model;
}
/// <summary>
/// Prepare the GDPR tools model
/// </summary>
/// <returns>GDPR tools model</returns>
public virtual GdprToolsModel PrepareGdprToolsModel()
{
var model = new GdprToolsModel();
return model;
}
/// <summary>
/// Prepare the check gift card balance madel
/// </summary>
/// <returns>Check gift card balance madel</returns>
public virtual CheckGiftCardBalanceModel PrepareCheckGiftCardBalanceModel()
{
var model = new CheckGiftCardBalanceModel();
return model;
}
#endregion
}
} | 48.739414 | 216 | 0.618704 | [
"MIT"
] | EvaSRGitHub/NopCommerce-HomePageNewProductsPlugin | src/Presentation/Nop.Web/Factories/CustomerModelFactory.cs | 44,891 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
using System;
using System.Collections.Generic;
using System.Text;
namespace NPOI.HSSF.Record.Chart
{
/// <summary>
/// The YMult record specifies properties of the value multiplier for a value axis and
/// that specifies the beginning of a collection of records as defined by the Chart Sheet
/// substream ABNF. The collection of records specifies a display units label.
/// </summary>
/// <remarks>
/// author: Antony liu (antony.apollo at gmail.com)
/// </remarks>
public class YMultRecord : RowDataRecord
{
public const short sid = 0x857;
public YMultRecord(RecordInputStream ris)
: base(ris)
{
}
protected override int DataSize
{
get
{
return base.DataSize;
}
}
public override void Serialize(NPOI.Util.ILittleEndianOutput out1)
{
base.Serialize(out1);
}
public override short Sid
{
get { return sid; }
}
}
}
| 35.912281 | 95 | 0.595017 | [
"Apache-2.0"
] | sunshinele/npoi | main/HSSF/Record/Chart/YMultRecord.cs | 2,049 | C# |
namespace Kritikos.Sphinx.Web.Server.Controllers
{
using Kritikos.Sphinx.Data.Persistence.Identity;
using Kritikos.Sphinx.Web.Server.Helpers;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
[Route("api/account")]
public class AccountController : BaseController<AccountController>
{
private readonly IDataProtector dataProtector;
private readonly UserManager<SphinxUser> userManager;
private readonly RoleManager<SphinxRole> roleManager;
private readonly RazorToStringRenderer razor;
public AccountController(
IDataProtectionProvider protectionProvider,
RazorToStringRenderer razorRenderer,
UserManager<SphinxUser> usersManager,
RoleManager<SphinxRole> rolesManager,
ILogger<AccountController> logger)
: base(logger)
{
dataProtector = protectionProvider.CreateProtector(DataProtectionPurposes.UserManagement);
userManager = usersManager;
roleManager = rolesManager;
razor = razorRenderer;
}
}
}
| 32.5 | 96 | 0.768326 | [
"Apache-2.0"
] | kritikos-io/Sphinx | src/Sphinx.Web.Server/Controllers/AccountController.cs | 1,105 | C# |
//******************************
// Written by Peter Golde
// Copyright (c) 2004-2005, Wintellect
//
// Use and restribution of this code is subject to the license agreement
// contained in the file "License.txt" accompanying this file.
//******************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Wintellect.PowerCollections
{
/// <summary>
/// MultiDictionaryBase is a base class that can be used to more easily implement a class
/// that associates multiple values to a single key. The class implements the generic
/// IDictionary<TKey, ICollection<TValue>> interface.
/// </summary>
/// <remarks>
/// <para>To use MultiDictionaryBase as a base class, the derived class must override
/// Count, Clear, Add, Remove(TKey), Remove(TKey,TValue), Contains(TKey,TValue),
/// EnumerateKeys, and TryEnumerateValuesForKey. </para>
/// <para>It may wish consider overriding CountValues, CountAllValues, ContainsKey,
/// and EqualValues, but these are not required.
/// </para>
/// </remarks>
/// <typeparam name="TKey">The key type of the dictionary.</typeparam>
/// <typeparam name="TValue">The value type of the dictionary.</typeparam>
[Serializable]
[DebuggerDisplay("{DebuggerDisplayString()}")]
public abstract class MultiDictionaryBase<TKey, TValue> : CollectionBase<KeyValuePair<TKey, ICollection<TValue>>>,
IDictionary<TKey, ICollection<TValue>>
{
/// <summary>
/// Creates a new MultiDictionaryBase.
/// </summary>
protected MultiDictionaryBase()
{
}
/// <summary>
/// Clears the dictionary. This method must be overridden in the derived class.
/// </summary>
public abstract override void Clear();
/// <summary>
/// Gets the number of keys in the dictionary. This property must be overridden
/// in the derived class.
/// </summary>
public abstract override int Count
{
get;
}
/// <summary>
/// Enumerate all the keys in the dictionary. This method must be overridden by a derived
/// class.
/// </summary>
/// <returns>An IEnumerator<TKey> that enumerates all of the keys in the collection that
/// have at least one value associated with them.</returns>
protected abstract IEnumerator<TKey> EnumerateKeys();
/// <summary>
/// Enumerate all of the values associated with a given key. This method must be overridden
/// by the derived class. If the key exists and has values associated with it, an enumerator for those
/// values is returned throught <paramref name="values"/>. If the key does not exist, false is returned.
/// </summary>
/// <param name="key">The key to get values for.</param>
/// <param name="values">If true is returned, this parameter receives an enumerators that
/// enumerates the values associated with that key.</param>
/// <returns>True if the key exists and has values associated with it. False otherwise.</returns>
protected abstract bool TryEnumerateValuesForKey(TKey key, out IEnumerator<TValue> values);
/// <summary>
/// Adds a key-value pair to the collection. The value part of the pair must be a collection
/// of values to associate with the key. If values are already associated with the given
/// key, the new values are added to the ones associated with that key.
/// </summary>
/// <param name="item">A KeyValuePair contains the Key and Value collection to add.</param>
public override void Add(KeyValuePair<TKey, ICollection<TValue>> item)
{
this.AddMany(item.Key, item.Value);
}
/// <summary>
/// Implements IDictionary<TKey, IEnumerable<TValue>>.Add. If the
/// key is already present, and ArgumentException is thrown. Otherwise, a
/// new key is added, and new values are associated with that key.
/// </summary>
/// <param name="key">Key to add.</param>
/// <param name="values">Values to associate with that key.</param>
/// <exception cref="ArgumentException">The key is already present in the dictionary.</exception>
void IDictionary<TKey, ICollection<TValue>>.Add(TKey key, ICollection<TValue> values)
{
if (ContainsKey(key))
{
throw new ArgumentException(Strings.KeyAlreadyPresent, "key");
}
else
{
AddMany(key, values);
}
}
/// <summary>
/// <para>Adds new values to be associated with a key. If duplicate values are permitted, this
/// method always adds new key-value pairs to the dictionary.</para>
/// <para>If duplicate values are not permitted, and <paramref name="key"/> already has a value
/// equal to one of <paramref name="values"/> associated with it, then that value is replaced,
/// and the number of values associate with <paramref name="key"/> is unchanged.</para>
/// </summary>
/// <param name="key">The key to associate with.</param>
/// <param name="values">A collection of values to associate with <paramref name="key"/>.</param>
public virtual void AddMany(TKey key, IEnumerable<TValue> values)
{
foreach (TValue value in values)
Add(key, value);
}
/// <summary>
/// Adds a new key-value pair to the dictionary. This method must be overridden in the derived class.
/// </summary>
/// <param name="key">Key to add.</param>
/// <param name="value">Value to associated with the key.</param>
/// <exception cref="ArgumentException">key is already present in the dictionary</exception>
public abstract void Add(TKey key, TValue value);
/// <summary>
/// Removes a key from the dictionary. This method must be overridden in the derived class.
/// </summary>
/// <param name="key">Key to remove from the dictionary.</param>
/// <returns>True if the key was found, false otherwise.</returns>
public abstract bool Remove(TKey key);
/// <summary>
/// Removes a key-value pair from the dictionary. This method must be overridden in the derived class.
/// </summary>
/// <param name="key">Key to remove from the dictionary.</param>
/// <param name="value">Associated value to remove from the dictionary.</param>
/// <returns>True if the key-value pair was found, false otherwise.</returns>
public abstract bool Remove(TKey key, TValue value);
/// <summary>
/// Removes a set of values from a given key. If all values associated with a key are
/// removed, then the key is removed also.
/// </summary>
/// <param name="pair">A KeyValuePair contains a key and a set of values to remove from that key.</param>
/// <returns>True if at least one values was found and removed.</returns>
public override bool Remove(KeyValuePair<TKey, ICollection<TValue>> pair)
{
return RemoveMany(pair.Key, pair.Value) > 0;
}
/// <summary>
/// Removes a collection of values from the values associated with a key. If the
/// last value is removed from a key, the key is removed also.
/// </summary>
/// <param name="key">A key to remove values from.</param>
/// <param name="values">A collection of values to remove.</param>
/// <returns>The number of values that were present and removed. </returns>
public virtual int RemoveMany(TKey key, IEnumerable<TValue> values)
{
int countRemoved = 0;
foreach (TValue val in values)
{
if (Remove(key, val))
++countRemoved;
}
return countRemoved;
}
/// <summary>
/// Remove all of the keys (and any associated values) in a collection
/// of keys. If a key is not present in the dictionary, nothing happens.
/// </summary>
/// <param name="keyCollection">A collection of key values to remove.</param>
/// <returns>The number of keys from the collection that were present and removed.</returns>
public int RemoveMany(IEnumerable<TKey> keyCollection)
{
int count = 0;
foreach (TKey key in keyCollection)
{
if (Remove(key))
++count;
}
return count;
}
/// <summary>
/// Determines if this dictionary contains a key equal to <paramref name="key"/>. If so, all the values
/// associated with that key are returned through the values parameter. This method must be
/// overridden by the derived class.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="values">Returns all values associated with key, if true was returned.</param>
/// <returns>True if the dictionary contains key. False if the dictionary does not contain key.</returns>
bool IDictionary<TKey, ICollection<TValue>>.TryGetValue(TKey key, out ICollection<TValue> values)
{
if (ContainsKey(key))
{
values = this[key];
return true;
}
else
{
values = null;
return false;
}
}
/// <summary>
/// Determines whether a given key is found in the dictionary.
/// </summary>
/// <remarks>The default implementation simply calls TryEnumerateValuesForKey.
/// It may be appropriate to override this method to
/// provide a more efficient implementation.</remarks>
/// <param name="key">Key to look for in the dictionary.</param>
/// <returns>True if the key is present in the dictionary.</returns>
public virtual bool ContainsKey(TKey key)
{
IEnumerator<TValue> values;
return TryEnumerateValuesForKey(key, out values);
}
/// <summary>
/// Determines if this dictionary contains a key-value pair equal to <paramref name="key"/> and
/// <paramref name="value"/>. The dictionary is not changed. This method must be overridden in the derived class.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="value">The value to search for.</param>
/// <returns>True if the dictionary has associated <paramref name="value"/> with <paramref name="key"/>.</returns>
public abstract bool Contains(TKey key, TValue value);
/// <summary>
/// Determines if this dictionary contains the given key and all of the values associated with that key..
/// </summary>
/// <param name="pair">A key and collection of values to search for.</param>
/// <returns>True if the dictionary has associated all of the values in <paramref name="pair"/>.Value with <paramref name="pair"/>.Key.</returns>
public override bool Contains(KeyValuePair<TKey, ICollection<TValue>> pair)
{
foreach (TValue val in pair.Value)
{
if (!Contains(pair.Key, val))
return false;
}
return true;
}
// Cache the equality comparer after we get it the first time.
private volatile IEqualityComparer<TValue> valueEqualityComparer;
/// <summary>
/// If the derived class does not use the default comparison for values, this
/// methods should be overridden to compare two values for equality. This is
/// used for the correct implementation of ICollection.Contains on the Values
/// and KeyValuePairs collections.
/// </summary>
/// <param name="value1">First value to compare.</param>
/// <param name="value2">Second value to compare.</param>
/// <returns>True if the values are equal.</returns>
protected virtual bool EqualValues(TValue value1, TValue value2)
{
if (valueEqualityComparer == null)
valueEqualityComparer = EqualityComparer<TValue>.Default;
return valueEqualityComparer.Equals(value1, value2);
}
/// <summary>
/// Gets a count of the number of values associated with a key. The
/// default implementation is slow; it enumerators all of the values
/// (using TryEnumerateValuesForKey) to count them. A derived class
/// may be able to supply a more efficient implementation.
/// </summary>
/// <param name="key">The key to count values for.</param>
/// <returns>The number of values associated with <paramref name="key"/>.</returns>
protected virtual int CountValues(TKey key)
{
int count = 0;
IEnumerator<TValue> enumValues;
if (TryEnumerateValuesForKey(key, out enumValues))
{
using (enumValues)
{
while (enumValues.MoveNext())
count += 1;
}
}
return count;
}
/// <summary>
/// Gets a total count of values in the collection. This default implementation
/// is slow; it enumerates all of the keys in the dictionary and calls CountValues on each.
/// A derived class may be able to supply a more efficient implementation.
/// </summary>
/// <returns>The total number of values associated with all keys in the dictionary.</returns>
protected virtual int CountAllValues()
{
int count = 0;
using (IEnumerator<TKey> enumKeys = EnumerateKeys())
{
while (enumKeys.MoveNext())
{
TKey key = enumKeys.Current;
count += CountValues(key);
}
}
return count;
}
/// <summary>
/// Gets a read-only collection all the keys in this dictionary.
/// </summary>
/// <value>An readonly ICollection<TKey> of all the keys in this dictionary.</value>
public virtual ICollection<TKey> Keys
{
get { return new KeysCollection(this); }
}
/// <summary>
/// Gets a read-only collection of all the values in the dictionary.
/// </summary>
/// <returns>A read-only ICollection<TValue> of all the values in the dictionary.</returns>
public virtual ICollection<TValue> Values
{
get { return new ValuesCollection(this); }
}
/// <summary>
/// Gets a read-only collection of all the value collections in the dictionary.
/// </summary>
/// <returns>A read-only ICollection<IEnumerable<TValue>> of all the values in the dictionary.</returns>
ICollection<ICollection<TValue>> IDictionary<TKey, ICollection<TValue>>.Values
{
get { return new EnumerableValuesCollection(this); }
}
/// <summary>
/// Gets a read-only collection of all key-value pairs in the dictionary. If a key has multiple
/// values associated with it, then a key-value pair is present for each value associated
/// with the key.
/// </summary>
public virtual ICollection<KeyValuePair<TKey, TValue>> KeyValuePairs
{
get { return new KeyValuePairsCollection(this); }
}
/// <summary>
/// Returns a collection of all of the values in the dictionary associated with <paramref name="key"/>,
/// or changes the set of values associated with <paramref name="key"/>.
/// If the key is not present in the dictionary, an ICollection enumerating no
/// values is returned. The returned collection of values is read-write, and can be used to
/// modify the collection of values associated with the key.
/// </summary>
/// <param name="key">The key to get the values associated with.</param>
/// <value>An ICollection<TValue> with all the values associated with <paramref name="key"/>.</value>
public virtual ICollection<TValue> this[TKey key]
{
get
{
return new ValuesForKeyCollection(this, key);
}
set
{
ReplaceMany(key, value);
}
}
/// <summary>
/// Gets a collection of all the values in the dictionary associated with <paramref name="key"/>,
/// or changes the set of values associated with <paramref name="key"/>.
/// If the key is not present in the dictionary, a KeyNotFound exception is thrown.
/// </summary>
/// <param name="key">The key to get the values associated with.</param>
/// <value>An IEnumerable<TValue> that enumerates all the values associated with <paramref name="key"/>.</value>
/// <exception cref="KeyNotFoundException">The given key is not present in the dictionary.</exception>
ICollection<TValue> IDictionary<TKey, ICollection<TValue>>.this[TKey key]
{
get
{
if (ContainsKey(key))
return new ValuesForKeyCollection(this, key);
else
throw new KeyNotFoundException(Strings.KeyNotFound);
}
set
{
ReplaceMany(key, value);
}
}
/// <summary>
/// Replaces all values associated with <paramref name="key"/> with the single value <paramref name="value"/>.
/// </summary>
/// <remarks>This implementation simply calls Remove, followed by Add.</remarks>
/// <param name="key">The key to associate with.</param>
/// <param name="value">The new values to be associated with <paramref name="key"/>.</param>
/// <returns>Returns true if some values were removed. Returns false if <paramref name="key"/> was not
/// present in the dictionary before Replace was called.</returns>
public virtual bool Replace(TKey key, TValue value)
{
bool removed = Remove(key);
Add(key, value);
return removed;
}
/// <summary>
/// Replaces all values associated with <paramref name="key"/> with a new collection
/// of values. If the collection does not permit duplicate values, and <paramref name="values"/> has duplicate
/// items, then only the last of duplicates is added.
/// </summary>
/// <param name="key">The key to associate with.</param>
/// <param name="values">The new values to be associated with <paramref name="key"/>.</param>
/// <returns>Returns true if some values were removed. Returns false if <paramref name="key"/> was not
/// present in the dictionary before Replace was called.</returns>
public bool ReplaceMany(TKey key, IEnumerable<TValue> values)
{
bool removed = Remove(key);
AddMany(key, values);
return removed;
}
/// <summary>
/// Shows the string representation of the dictionary. The string representation contains
/// a list of the mappings in the dictionary.
/// </summary>
/// <returns>The string representation of the dictionary.</returns>
public override string ToString()
{
bool firstItem = true;
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append("{");
// Call ToString on each item and put it in.
foreach (KeyValuePair<TKey, ICollection<TValue>> pair in this)
{
if (!firstItem)
builder.Append(", ");
if (pair.Key == null)
builder.Append("null");
else
builder.Append(pair.Key.ToString());
builder.Append("->");
// Put all values in a parenthesized list.
builder.Append('(');
bool firstValue = true;
foreach (TValue val in pair.Value)
{
if (!firstValue)
builder.Append(",");
if (val == null)
builder.Append("null");
else
builder.Append(val.ToString());
firstValue = false;
}
builder.Append(')');
firstItem = false;
}
builder.Append("}");
return builder.ToString();
}
/// <summary>
/// Display the contents of the dictionary in the debugger. This is intentionally private, it is called
/// only from the debugger due to the presence of the DebuggerDisplay attribute. It is similar
/// format to ToString(), but is limited to 250-300 characters or so, so as not to overload the debugger.
/// </summary>
/// <returns>The string representation of the items in the collection, similar in format to ToString().</returns>
new internal string DebuggerDisplayString()
{
const int MAXLENGTH = 250;
bool firstItem = true;
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append("{");
// Call ToString on each item and put it in.
foreach (KeyValuePair<TKey, ICollection<TValue>> pair in this)
{
if (builder.Length >= MAXLENGTH)
{
builder.Append(", ...");
break;
}
if (!firstItem)
builder.Append(", ");
if (pair.Key == null)
builder.Append("null");
else
builder.Append(pair.Key.ToString());
builder.Append("->");
// Put all values in a parenthesized list.
builder.Append('(');
bool firstValue = true;
foreach (TValue val in pair.Value)
{
if (!firstValue)
builder.Append(",");
if (val == null)
builder.Append("null");
else
builder.Append(val.ToString());
firstValue = false;
}
builder.Append(')');
firstItem = false;
}
builder.Append("}");
return builder.ToString();
}
/// <summary>
/// Enumerate all the keys in the dictionary, and for each key, the collection of values for that key.
/// </summary>
/// <returns>An enumerator to enumerate all the key, ICollection<value> pairs in the dictionary.</returns>
public override IEnumerator<KeyValuePair<TKey, ICollection<TValue>>> GetEnumerator()
{
using (IEnumerator<TKey> enumKeys = EnumerateKeys())
{
while (enumKeys.MoveNext())
{
TKey key = enumKeys.Current;
yield return new KeyValuePair<TKey, ICollection<TValue>>(key, new ValuesForKeyCollection(this, key));
}
}
}
#region Keys and Values collections
/// <summary>
/// A private class that provides the ICollection<TValue> for a particular key. This is the collection
/// that is returned from the indexer. The collections is read-write, live, and can be used to add, remove,
/// etc. values from the multi-dictionary.
/// </summary>
[Serializable]
private sealed class ValuesForKeyCollection : CollectionBase<TValue>
{
private MultiDictionaryBase<TKey, TValue> myDictionary;
private TKey key;
/// <summary>
/// Constructor. Initializes this collection.
/// </summary>
/// <param name="myDictionary">Dictionary we're using.</param>
/// <param name="key">The key we're looking at.</param>
public ValuesForKeyCollection(MultiDictionaryBase<TKey, TValue> myDictionary, TKey key)
{
this.myDictionary = myDictionary;
this.key = key;
}
/// <summary>
/// Remove the key and all values associated with it.
/// </summary>
public override void Clear()
{
myDictionary.Remove(key);
}
/// <summary>
/// Add a new values to this key.
/// </summary>
/// <param name="item">New values to add.</param>
public override void Add(TValue item)
{
myDictionary.Add(key, item);
}
/// <summary>
/// Remove a value currently associated with key.
/// </summary>
/// <param name="item">Value to remove.</param>
/// <returns>True if item was assocaited with key, false otherwise.</returns>
public override bool Remove(TValue item)
{
return myDictionary.Remove(key, item);
}
/// <summary>
/// Get the number of values associated with the key.
/// </summary>
public override int Count
{
get
{
return myDictionary.CountValues(key);
}
}
/// <summary>
/// A simple function that returns an IEnumerator<TValue> that
/// doesn't yield any values. A helper.
/// </summary>
/// <returns>An IEnumerator<TValue> that yields no values.</returns>
private IEnumerator<TValue> NoValues()
{
yield break;
}
/// <summary>
/// Enumerate all the values associated with key.
/// </summary>
/// <returns>An IEnumerator<TValue> that enumerates all the values associated with key.</returns>
public override IEnumerator<TValue> GetEnumerator()
{
IEnumerator<TValue> values;
if (myDictionary.TryEnumerateValuesForKey(key, out values))
return values;
else
return NoValues();
}
/// <summary>
/// Determines if the given values is associated with key.
/// </summary>
/// <param name="item">Value to check for.</param>
/// <returns>True if value is associated with key, false otherwise.</returns>
public override bool Contains(TValue item)
{
return myDictionary.Contains(key, item);
}
}
/// <summary>
/// A private class that implements ICollection<TKey> and ICollection for the
/// Keys collection. The collection is read-only.
/// </summary>
[Serializable]
private sealed class KeysCollection : ReadOnlyCollectionBase<TKey>
{
private MultiDictionaryBase<TKey, TValue> myDictionary;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="myDictionary">The dictionary this is associated with.</param>
public KeysCollection(MultiDictionaryBase<TKey, TValue> myDictionary)
{
this.myDictionary = myDictionary;
}
public override int Count
{
get { return myDictionary.Count; }
}
public override IEnumerator<TKey> GetEnumerator()
{
return myDictionary.EnumerateKeys();
}
public override bool Contains(TKey key)
{
return myDictionary.ContainsKey(key);
}
}
/// <summary>
/// A private class that implements ICollection<TValue> and ICollection for the
/// Values collection. The collection is read-only.
/// </summary>
[Serializable]
private sealed class ValuesCollection : ReadOnlyCollectionBase<TValue>
{
private MultiDictionaryBase<TKey, TValue> myDictionary;
public ValuesCollection(MultiDictionaryBase<TKey, TValue> myDictionary)
{
this.myDictionary = myDictionary;
}
public override int Count
{
get { return myDictionary.CountAllValues(); }
}
public override IEnumerator<TValue> GetEnumerator()
{
using (IEnumerator<TKey> enumKeys = myDictionary.EnumerateKeys())
{
while (enumKeys.MoveNext())
{
TKey key = enumKeys.Current;
IEnumerator<TValue> enumValues;
if (myDictionary.TryEnumerateValuesForKey(key, out enumValues))
{
using (enumValues)
{
while (enumValues.MoveNext())
yield return enumValues.Current;
}
}
}
}
}
public override bool Contains(TValue value)
{
foreach (TValue v in this)
{
if (myDictionary.EqualValues(v, value))
return true;
}
return false;
}
}
/// <summary>
/// A private class that implements ICollection<ICollection<TValue>> and ICollection for the
/// Values collection on IDictionary. The collection is read-only.
/// </summary>
[Serializable]
private sealed class EnumerableValuesCollection : ReadOnlyCollectionBase<ICollection<TValue>>
{
private MultiDictionaryBase<TKey, TValue> myDictionary;
public EnumerableValuesCollection(MultiDictionaryBase<TKey, TValue> myDictionary)
{
this.myDictionary = myDictionary;
}
public override int Count
{
get { return myDictionary.Count; }
}
public override IEnumerator<ICollection<TValue>> GetEnumerator()
{
using (IEnumerator<TKey> enumKeys = myDictionary.EnumerateKeys())
{
while (enumKeys.MoveNext())
{
TKey key = enumKeys.Current;
yield return new ValuesForKeyCollection(myDictionary, key);
}
}
}
public override bool Contains(ICollection<TValue> values)
{
if (values == null)
return false;
TValue[] valueArray = Algorithms.ToArray(values);
foreach (ICollection<TValue> v in this)
{
if (v.Count != valueArray.Length)
continue;
// First check in order for efficiency.
if (Algorithms.EqualCollections(v, values, myDictionary.EqualValues))
return true;
// Now check not in order. We can't use Algorithms.EqualSets, because we don't
// have an IEqualityComparer, just the ability to compare for equality. Unfortunately this is N squared,
// but there isn't a good choice here. We don't really expect this method to be used much.
bool[] found = new bool[valueArray.Length];
foreach (TValue x in v)
{
for (int i = 0; i < valueArray.Length; ++i)
{
if (!found[i] && myDictionary.EqualValues(x, valueArray[i]))
found[i] = true;
}
}
if (Array.IndexOf(found, false) < 0)
return true; // every item was found. The sets must be equal.
}
return false;
}
}
/// <summary>
/// A private class that implements ICollection<KeyValuePair<TKey,TValue>> and ICollection for the
/// KeyValuePairs collection. The collection is read-only.
/// </summary>
[Serializable]
private sealed class KeyValuePairsCollection : ReadOnlyCollectionBase<KeyValuePair<TKey, TValue>>
{
private MultiDictionaryBase<TKey, TValue> myDictionary;
public KeyValuePairsCollection(MultiDictionaryBase<TKey, TValue> myDictionary)
{
this.myDictionary = myDictionary;
}
public override int Count
{
get { return myDictionary.CountAllValues(); }
}
public override IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
using (IEnumerator<TKey> enumKeys = myDictionary.EnumerateKeys())
{
while (enumKeys.MoveNext())
{
TKey key = enumKeys.Current;
IEnumerator<TValue> enumValues;
if (myDictionary.TryEnumerateValuesForKey(key, out enumValues))
{
using (enumValues)
{
while (enumValues.MoveNext())
yield return new KeyValuePair<TKey, TValue>(key, enumValues.Current);
}
}
}
}
}
public override bool Contains(KeyValuePair<TKey, TValue> pair)
{
return myDictionary[pair.Key].Contains(pair.Value);
}
}
#endregion
}
}
| 40.62645 | 153 | 0.548943 | [
"MIT"
] | SOFAgh/CADability | CADability/MultiDictionaryBase.cs | 35,022 | 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 lex-models-2017-04-19.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.LexModelBuildingService.Model
{
/// <summary>
/// Container for the parameters to the CreateBotVersion operation.
/// 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>
public partial class CreateBotVersionRequest : AmazonLexModelBuildingServiceRequest
{
private string _checksum;
private string _name;
/// <summary>
/// Gets and sets the property Checksum.
/// <para>
/// Identifies a specific revision of the <code>$LATEST</code> version of the bot. If
/// you specify a checksum and the <code>$LATEST</code> version of the bot has a different
/// checksum, a <code>PreconditionFailedException</code> exception is returned and Amazon
/// Lex doesn't publish a new version. If you don't specify a checksum, Amazon Lex publishes
/// the <code>$LATEST</code> version.
/// </para>
/// </summary>
public string Checksum
{
get { return this._checksum; }
set { this._checksum = value; }
}
// Check to see if Checksum property is set
internal bool IsSetChecksum()
{
return this._checksum != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the bot that you want to create a new version of. The name is case sensitive.
///
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
}
} | 34.88 | 108 | 0.622993 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/LexModelBuildingService/Generated/Model/CreateBotVersionRequest.cs | 3,488 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum BetterResult
{
Left,
Right,
Neither,
Equal
}
internal sealed partial class OverloadResolution
{
private readonly Binder _binder;
public OverloadResolution(Binder binder)
{
_binder = binder;
}
private CSharpCompilation Compilation
{
get { return _binder.Compilation; }
}
private Conversions Conversions
{
get { return _binder.Conversions; }
}
// lazily compute if the compiler is in "strict" mode (rather than duplicating bugs for compatibility)
private bool? _strict;
private bool Strict
{
get
{
if (_strict.HasValue) return _strict.Value;
bool value = _binder.Compilation.FeatureStrictEnabled;
_strict = value;
return value;
}
}
// UNDONE: This List<MethodResolutionResult> deal should probably be its own datastructure.
// We need an indexable collection of mappings from method candidates to their up-to-date
// overload resolution status. It must be fast and memory efficient, but it will very often
// contain just 1 candidate.
private static int RemainingCandidatesCount<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> list)
where TMember : Symbol
{
var count = 0;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Result.IsValid)
{
count += 1;
}
}
return count;
}
// Perform overload resolution on the given method group, with the given arguments and
// names. The names can be null if no names were supplied to any arguments.
public void ObjectCreationOverloadResolution(ImmutableArray<MethodSymbol> constructors, AnalyzedArguments arguments, OverloadResolutionResult<MethodSymbol> result, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var results = result.ResultsBuilder;
// First, attempt overload resolution not getting complete results.
PerformObjectCreationOverloadResolution(results, constructors, arguments, false, ref useSiteDiagnostics);
if (!OverloadResolutionResultIsValid(results, arguments.HasDynamicArgument))
{
// We didn't get a single good result. Get full results of overload resolution and return those.
result.Clear();
PerformObjectCreationOverloadResolution(results, constructors, arguments, true, ref useSiteDiagnostics);
}
}
// Perform overload resolution on the given method group, with the given arguments and
// names. The names can be null if no names were supplied to any arguments.
public void MethodInvocationOverloadResolution(
ArrayBuilder<MethodSymbol> methods,
ArrayBuilder<TypeSymbol> typeArguments,
AnalyzedArguments arguments,
OverloadResolutionResult<MethodSymbol> result,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool isMethodGroupConversion = false,
bool allowRefOmittedArguments = false,
bool inferWithDynamic = false,
bool allowUnexpandedForm = true)
{
MethodOrPropertyOverloadResolution(
methods, typeArguments, arguments, result, isMethodGroupConversion,
allowRefOmittedArguments, ref useSiteDiagnostics, inferWithDynamic: inferWithDynamic,
allowUnexpandedForm: allowUnexpandedForm);
}
// Perform overload resolution on the given property group, with the given arguments and
// names. The names can be null if no names were supplied to any arguments.
public void PropertyOverloadResolution(
ArrayBuilder<PropertySymbol> indexers,
AnalyzedArguments arguments,
OverloadResolutionResult<PropertySymbol> result,
bool allowRefOmittedArguments,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
ArrayBuilder<TypeSymbol> typeArguments = ArrayBuilder<TypeSymbol>.GetInstance();
MethodOrPropertyOverloadResolution(indexers, typeArguments, arguments, result, isMethodGroupConversion: false, allowRefOmittedArguments: allowRefOmittedArguments, useSiteDiagnostics: ref useSiteDiagnostics);
typeArguments.Free();
}
internal void MethodOrPropertyOverloadResolution<TMember>(
ArrayBuilder<TMember> members,
ArrayBuilder<TypeSymbol> typeArguments,
AnalyzedArguments arguments,
OverloadResolutionResult<TMember> result,
bool isMethodGroupConversion,
bool allowRefOmittedArguments,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool inferWithDynamic = false,
bool allowUnexpandedForm = true)
where TMember : Symbol
{
var results = result.ResultsBuilder;
// First, attempt overload resolution not getting complete results.
PerformMemberOverloadResolution(
results, members, typeArguments, arguments, false, isMethodGroupConversion,
allowRefOmittedArguments, ref useSiteDiagnostics, inferWithDynamic: inferWithDynamic,
allowUnexpandedForm: allowUnexpandedForm);
if (!OverloadResolutionResultIsValid(results, arguments.HasDynamicArgument))
{
// We didn't get a single good result. Get full results of overload resolution and return those.
result.Clear();
PerformMemberOverloadResolution(results, members, typeArguments, arguments, true, isMethodGroupConversion,
allowRefOmittedArguments, ref useSiteDiagnostics, allowUnexpandedForm: allowUnexpandedForm);
}
}
private static bool OverloadResolutionResultIsValid<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, bool hasDynamicArgument)
where TMember : Symbol
{
// If there were no dynamic arguments then overload resolution succeeds if there is exactly one method
// that is applicable and not worse than another method.
//
// If there were dynamic arguments then overload resolution succeeds if there were one or more applicable
// methods; which applicable method that will be invoked, if any, will be worked out at runtime.
//
// Note that we could in theory do a better job of detecting situations that we know will fail. We do not
// treat methods that violate generic type constraints as inapplicable; rather, if such a method is chosen
// as the best method we give an error during the "final validation" phase. In the dynamic argument
// scenario there could be two methods, both applicable, ambiguous as to which is better, and neither
// would pass final validation. In that case we could give the error at compile time, but we do not.
if (hasDynamicArgument)
{
foreach (var curResult in results)
{
if (curResult.Result.IsApplicable)
{
return true;
}
}
return false;
}
bool oneValid = false;
foreach (var curResult in results)
{
if (curResult.Result.IsValid)
{
if (oneValid)
{
// We somehow have two valid results.
return false;
}
oneValid = true;
}
}
return oneValid;
}
// Perform method/indexer overload resolution, storing the results into "results". If
// completeResults is false, then invalid results don't have to be stored. The results will
// still contain all possible successful resolution.
private void PerformMemberOverloadResolution<TMember>(
ArrayBuilder<MemberResolutionResult<TMember>> results,
ArrayBuilder<TMember> members,
ArrayBuilder<TypeSymbol> typeArguments,
AnalyzedArguments arguments,
bool completeResults,
bool isMethodGroupConversion,
bool allowRefOmittedArguments,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool inferWithDynamic = false,
bool allowUnexpandedForm = true)
where TMember : Symbol
{
// SPEC: The binding-time processing of a method invocation of the form M(A), where M is a
// SPEC: method group (possibly including a type-argument-list), and A is an optional
// SPEC: argument-list, consists of the following steps:
// NOTE: We use a quadratic algorithm to determine which members override/hide
// each other (i.e. we compare them pairwise). We could move to a linear
// algorithm that builds the closure set of overridden/hidden members and then
// uses that set to filter the candidate, but that would still involve realizing
// a lot of PE symbols. Instead, we partition the candidates by containing type.
// With this information, we can efficiently skip checks where the (potentially)
// overriding or hiding member is not in a subtype of the type containing the
// (potentially) overridden or hidden member.
Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt = null;
if (members.Count > 50) // TODO: fine-tune this value
{
containingTypeMapOpt = PartitionMembersByContainingType(members);
}
// SPEC: The set of candidate methods for the method invocation is constructed.
for (int i = 0; i < members.Count; i++)
{
AddMemberToCandidateSet(
members[i], results, members, typeArguments, arguments, completeResults,
isMethodGroupConversion, allowRefOmittedArguments, containingTypeMapOpt, inferWithDynamic: inferWithDynamic,
useSiteDiagnostics: ref useSiteDiagnostics, allowUnexpandedForm: allowUnexpandedForm);
}
// CONSIDER: use containingTypeMapOpt for RemoveLessDerivedMembers?
ClearContainingTypeMap(ref containingTypeMapOpt);
// Remove methods that are inaccessible because their inferred type arguments are inaccessible.
// It is not clear from the spec how or where this is supposed to occur.
RemoveInaccessibleTypeArguments(results, ref useSiteDiagnostics);
// SPEC: The set of candidate methods is reduced to contain only methods from the most derived types.
RemoveLessDerivedMembers(results, ref useSiteDiagnostics);
// NB: As in dev12, we do this AFTER removing less derived members.
// Also note that less derived members are not actually removed - they are simply flagged.
ReportUseSiteDiagnostics(results, ref useSiteDiagnostics);
// SPEC: If the resulting set of candidate methods is empty, then further processing along the following steps are abandoned,
// SPEC: and instead an attempt is made to process the invocation as an extension method invocation. If this fails, then no
// SPEC: applicable methods exist, and a binding-time error occurs.
if (RemainingCandidatesCount(results) == 0)
{
// UNDONE: Extension methods!
return;
}
// SPEC: The best method of the set of candidate methods is identified. If a single best method cannot be identified,
// SPEC: the method invocation is ambiguous, and a binding-time error occurs.
RemoveWorseMembers(results, arguments, ref useSiteDiagnostics);
// Note, the caller is responsible for "final validation",
// as that is not part of overload resolution.
}
private static Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> PartitionMembersByContainingType<TMember>(ArrayBuilder<TMember> members) where TMember : Symbol
{
Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMap = new Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>>();
for (int i = 0; i < members.Count; i++)
{
TMember member = members[i];
NamedTypeSymbol containingType = member.ContainingType;
ArrayBuilder<TMember> builder;
if (!containingTypeMap.TryGetValue(containingType, out builder))
{
builder = ArrayBuilder<TMember>.GetInstance();
containingTypeMap[containingType] = builder;
}
builder.Add(member);
}
return containingTypeMap;
}
private static void ClearContainingTypeMap<TMember>(ref Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt) where TMember : Symbol
{
if ((object)containingTypeMapOpt != null)
{
foreach (ArrayBuilder<TMember> builder in containingTypeMapOpt.Values)
{
builder.Free();
}
containingTypeMapOpt = null;
}
}
private void AddConstructorToCandidateSet(MethodSymbol constructor, ArrayBuilder<MemberResolutionResult<MethodSymbol>> results,
AnalyzedArguments arguments, bool completeResults, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// Filter out constructors with unsupported metadata.
if (constructor.HasUnsupportedMetadata)
{
Debug.Assert(!MemberAnalysisResult.UnsupportedMetadata().HasUseSiteDiagnosticToReportFor(constructor));
if (completeResults)
{
results.Add(new MemberResolutionResult<MethodSymbol>(constructor, constructor, MemberAnalysisResult.UnsupportedMetadata()));
}
return;
}
var normalResult = IsConstructorApplicableInNormalForm(constructor, arguments, ref useSiteDiagnostics);
var result = normalResult;
if (!normalResult.IsValid)
{
if (IsValidParams(constructor))
{
var expandedResult = IsConstructorApplicableInExpandedForm(constructor, arguments, ref useSiteDiagnostics);
if (expandedResult.IsValid || completeResults)
{
result = expandedResult;
}
}
}
// If the constructor has a use site diagnostic, we don't want to discard it because we'll have to report the diagnostic later.
if (result.IsValid || completeResults || result.HasUseSiteDiagnosticToReportFor(constructor))
{
results.Add(new MemberResolutionResult<MethodSymbol>(constructor, constructor, result));
}
}
private MemberAnalysisResult IsConstructorApplicableInNormalForm(MethodSymbol constructor, AnalyzedArguments arguments, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var argumentAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: false); // Constructors are never involved in method group conversion.
if (!argumentAnalysis.IsValid)
{
return MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis);
}
// Check after argument analysis, but before more complicated type inference and argument type validation.
if (constructor.HasUseSiteError)
{
return MemberAnalysisResult.UseSiteError();
}
var effectiveParameters = GetEffectiveParametersInNormalForm(constructor, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, allowRefOmittedArguments: false);
return IsApplicable(constructor, effectiveParameters, arguments, argumentAnalysis.ArgsToParamsOpt, isVararg: constructor.IsVararg, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, useSiteDiagnostics: ref useSiteDiagnostics);
}
private MemberAnalysisResult IsConstructorApplicableInExpandedForm(MethodSymbol constructor, AnalyzedArguments arguments, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var argumentAnalysis = AnalyzeArguments(constructor, arguments, isMethodGroupConversion: false, expanded: true);
if (!argumentAnalysis.IsValid)
{
return MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis);
}
// Check after argument analysis, but before more complicated type inference and argument type validation.
if (constructor.HasUseSiteError)
{
return MemberAnalysisResult.UseSiteError();
}
var effectiveParameters = GetEffectiveParametersInExpandedForm(constructor, arguments.Arguments.Count, argumentAnalysis.ArgsToParamsOpt, arguments.RefKinds, allowRefOmittedArguments: false);
// A vararg ctor is never applicable in its expanded form because
// it is never a params method.
Debug.Assert(!constructor.IsVararg);
var result = IsApplicable(constructor, effectiveParameters, arguments, argumentAnalysis.ArgsToParamsOpt, isVararg: false, hasAnyRefOmittedArgument: false, ignoreOpenTypes: false, useSiteDiagnostics: ref useSiteDiagnostics);
return result.IsValid ? MemberAnalysisResult.ExpandedForm(result.ArgsToParamsOpt, result.ConversionsOpt, hasAnyRefOmittedArgument: false) : result;
}
private void AddMemberToCandidateSet<TMember>(
TMember member, // method or property
ArrayBuilder<MemberResolutionResult<TMember>> results,
ArrayBuilder<TMember> members,
ArrayBuilder<TypeSymbol> typeArguments,
AnalyzedArguments arguments,
bool completeResults,
bool isMethodGroupConversion,
bool allowRefOmittedArguments,
Dictionary<NamedTypeSymbol, ArrayBuilder<TMember>> containingTypeMapOpt,
bool inferWithDynamic,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool allowUnexpandedForm)
where TMember : Symbol
{
// SPEC VIOLATION:
//
// The specification states that the method group that resulted from member lookup has
// already had all the "override" methods removed; according to the spec, only the
// original declaring type declarations remain.
//
// However, for IDE purposes ("go to definition") we *want* member lookup and overload
// resolution to identify the overriding method. And the same for the purposes of code
// generation. (For example, if you have 123.ToString() then we want to make a call to
// Int32.ToString() directly, passing the int, rather than boxing and calling
// Object.ToString() on the boxed object.)
//
// Therefore, in member lookup we do *not* eliminate the "override" methods, even though
// the spec says to. When overload resolution is handed a method group, it contains both
// the overriding methods and the overridden methods.
//
// This is bad; it means that we're going to be doing a lot of extra work. We don't need
// to analyze every overload of every method to determine if it is applicable; we
// already know that if one of them is applicable then they all will be. And we don't
// want to be in a situation where we're comparing two identical methods for which is
// "better" either.
//
// What we'll do here is first eliminate all the "duplicate" overriding methods.
// However, because we want to give the result as the more derived method, we'll do the
// opposite of what the member lookup spec says; we'll eliminate the less-derived
// methods, not the more-derived overrides. This means that we'll have to be a bit more
// clever in filtering out methods from less-derived classes later, but we'll cross that
// bridge when we come to it.
if (members.Count < 2)
{
// No hiding or overriding possible.
}
else if (containingTypeMapOpt == null)
{
if (MemberGroupContainsOverride(members, member))
{
// Don't even add it to the result set. We'll add only the most-overriding members.
return;
}
if (MemberGroupHidesByName(members, member, ref useSiteDiagnostics))
{
return;
}
}
else if (containingTypeMapOpt.Count == 1)
{
// No hiding or overriding since all members are in the same type.
}
else
{
// NOTE: only check for overriding/hiding in subtypes of f.ContainingType.
NamedTypeSymbol memberContainingType = member.ContainingType;
foreach (var pair in containingTypeMapOpt)
{
NamedTypeSymbol otherType = pair.Key;
if (otherType.IsDerivedFrom(memberContainingType, ignoreDynamic: false, useSiteDiagnostics: ref useSiteDiagnostics))
{
ArrayBuilder<TMember> others = pair.Value;
if (MemberGroupContainsOverride(others, member))
{
// Don't even add it to the result set. We'll add only the most-overriding members.
return;
}
if (MemberGroupHidesByName(others, member, ref useSiteDiagnostics))
{
return;
}
}
}
}
var leastOverriddenMember = (TMember)member.GetLeastOverriddenMember(_binder.ContainingType);
// Filter out members with unsupported metadata.
if (member.HasUnsupportedMetadata)
{
Debug.Assert(!MemberAnalysisResult.UnsupportedMetadata().HasUseSiteDiagnosticToReportFor(member));
if (completeResults)
{
results.Add(new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UnsupportedMetadata()));
}
return;
}
// First deal with eliminating generic-arity mismatches.
// SPEC: If F is generic and M includes a type argument list, F is a candidate when:
// SPEC: * F has the same number of method type parameters as were supplied in the type argument list, and
//
// This is specifying an impossible condition; the member lookup algorithm has already filtered
// out methods from the method group that have the wrong generic arity.
Debug.Assert(typeArguments.Count == 0 || typeArguments.Count == member.GetMemberArity());
// Second, we need to determine if the method is applicable in its normal form or its expanded form.
var normalResult = (allowUnexpandedForm || !IsValidParams(leastOverriddenMember))
? IsMemberApplicableInNormalForm(member, leastOverriddenMember, typeArguments, arguments, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic, ref useSiteDiagnostics)
: default(MemberResolutionResult<TMember>);
var result = normalResult;
if (!normalResult.Result.IsValid)
{
// Whether a virtual method [indexer] is a "params" method [indexer] or not depends solely on how the
// *original* declaration was declared. There are a variety of C# or MSIL
// tricks you can pull to make overriding methods [indexers] inconsistent with overridden
// methods [indexers] (or implementing methods [indexers] inconsistent with interfaces).
if (!isMethodGroupConversion && IsValidParams(leastOverriddenMember))
{
var expandedResult = IsMemberApplicableInExpandedForm(member, leastOverriddenMember, typeArguments, arguments, allowRefOmittedArguments, ref useSiteDiagnostics);
if (PreferExpandedFormOverNormalForm(normalResult.Result, expandedResult.Result))
{
result = expandedResult;
}
}
}
// Retain candidates with use site diagnostics for later reporting.
if (result.Result.IsValid || completeResults || result.HasUseSiteDiagnosticToReport)
{
results.Add(result);
}
}
// If the normal form is invalid and the expanded form is valid then obviously we prefer
// the expanded form. However, there may be error-reporting situations where we
// prefer to report the error on the expanded form rather than the normal form.
// For example, if you have something like Foo<T>(params T[]) and a call
// Foo(1, "") then the error for the normal form is "too many arguments"
// and the error for the expanded form is "failed to infer T". Clearly the
// expanded form error is better.
private static bool PreferExpandedFormOverNormalForm(MemberAnalysisResult normalResult, MemberAnalysisResult expandedResult)
{
Debug.Assert(!normalResult.IsValid);
if (expandedResult.IsValid)
{
return true;
}
switch (normalResult.Kind)
{
case MemberResolutionKind.RequiredParameterMissing:
case MemberResolutionKind.NoCorrespondingParameter:
switch (expandedResult.Kind)
{
case MemberResolutionKind.BadArguments:
case MemberResolutionKind.NameUsedForPositional:
case MemberResolutionKind.TypeInferenceFailed:
case MemberResolutionKind.TypeInferenceExtensionInstanceArgument:
case MemberResolutionKind.ConstructedParameterFailedConstraintCheck:
case MemberResolutionKind.NoCorrespondingNamedParameter:
return true;
}
break;
}
return false;
}
// We need to know if this is a valid formal parameter list with a parameter array
// as the final formal parameter. We might be in an error recovery scenario
// where the params array is not an array type.
public static bool IsValidParams(Symbol member)
{
// A varargs method is never a valid params method.
if (member.GetIsVararg())
{
return false;
}
int paramCount = member.GetParameterCount();
if (paramCount == 0)
{
return false;
}
// Note: we need to confirm the "arrayness" on the original definition because
// it's possible that the type becomes an array as a result of substitution.
ParameterSymbol final = member.GetParameters().Last();
return final.IsParams && ((ParameterSymbol)final.OriginalDefinition).Type.IsArray();
}
private static bool IsOverride(Symbol overridden, Symbol overrider)
{
if (overridden.ContainingType == overrider.ContainingType ||
!MemberSignatureComparer.SloppyOverrideComparer.Equals(overridden, overrider))
{
// Easy out.
return false;
}
// Does overrider override overridden?
var current = overrider;
while (true)
{
if (!current.IsOverride)
{
return false;
}
current = current.GetOverriddenMember();
// We could be in error recovery.
if ((object)current == null)
{
return false;
}
if (current == overridden)
{
return true;
}
// Don't search beyond the overridden member.
if (current.ContainingType == overridden.ContainingType)
{
return false;
}
}
}
private static bool MemberGroupContainsOverride<TMember>(ArrayBuilder<TMember> members, TMember member)
where TMember : Symbol
{
if (!member.IsVirtual && !member.IsAbstract && !member.IsOverride)
{
return false;
}
for (var i = 0; i < members.Count; ++i)
{
if (IsOverride(member, members[i]))
{
return true;
}
}
return false;
}
private static bool MemberGroupHidesByName<TMember>(ArrayBuilder<TMember> members, TMember member, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
NamedTypeSymbol memberContainingType = member.ContainingType;
foreach (var otherMember in members)
{
NamedTypeSymbol otherContainingType = otherMember.ContainingType;
if (HidesByName(otherMember) && otherContainingType.IsDerivedFrom(memberContainingType, ignoreDynamic: false, useSiteDiagnostics: ref useSiteDiagnostics))
{
return true;
}
}
return false;
}
/// <remarks>
/// This is specifically a private helper function (rather than a public property or extension method)
/// because applying this predicate to a non-method member doesn't have a clear meaning. The goal was
/// simply to avoid repeating ad-hoc code in a group of related collections.
/// </remarks>
private static bool HidesByName(Symbol member)
{
switch (member.Kind)
{
case SymbolKind.Method:
return ((MethodSymbol)member).HidesBaseMethodsByName;
case SymbolKind.Property:
return ((PropertySymbol)member).HidesBasePropertiesByName;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
private void RemoveInaccessibleTypeArguments<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
for (int f = 0; f < results.Count; ++f)
{
var result = results[f];
if (result.Result.IsValid && !TypeArgumentsAccessible(result.Member.GetMemberTypeArgumentsNoUseSiteDiagnostics(), ref useSiteDiagnostics))
{
results[f] = new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.InaccessibleTypeArgument());
}
}
}
private bool TypeArgumentsAccessible(ImmutableArray<TypeSymbol> typeArguments, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
foreach (TypeSymbol arg in typeArguments)
{
if (!_binder.IsAccessible(arg, ref useSiteDiagnostics)) return false;
}
return true;
}
private static void RemoveLessDerivedMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
// 7.6.5.1 Method invocations
// SPEC: For each method C.F in the set, where C is the type in which the method F is declared,
// SPEC: all methods declared in a base type of C are removed from the set. Furthermore, if C
// SPEC: is a class type other than object, all methods declared in an interface type are removed
// SPEC: from the set. (This latter rule only has affect when the method group was the result of
// SPEC: a member lookup on a type parameter having an effective base class other than object
// SPEC: and a non-empty effective interface set.)
// This is going to get a bit complicated.
//
// Call the "original declaring type" of a method the type which first declares the
// method, rather than overriding it.
//
// The specification states that the method group that resulted from member lookup has
// already had all the "override" methods removed; according to the spec, only the
// original declaring type declarations remain. This means that when we do this
// filtering, we're not suppose to remove methods of a base class just because there was
// some override in a more derived class. Whether there is an override or not is an
// implementation detail of the derived class; it shouldn't affect overload resolution.
// The point of overload resolution is to determine the *slot* that is going to be
// invoked, not the specific overriding method body.
//
// However, for IDE purposes ("go to definition") we *want* member lookup and overload
// resolution to identify the overriding method. And the same for the purposes of code
// generation. (For example, if you have 123.ToString() then we want to make a call to
// Int32.ToString() directly, passing the int, rather than boxing and calling
// Object.ToString() on the boxed object.)
//
// Therefore, in member lookup we do *not* eliminate the "override" methods, even though
// the spec says to. When overload resolution is handed a method group, it contains both
// the overriding methods and the overridden methods. We eliminate the *overridden*
// methods during applicable candidate set construction.
//
// Let's look at an example. Suppose we have in the method group:
//
// virtual Animal.M(T1),
// virtual Mammal.M(T2),
// virtual Mammal.M(T3),
// override Giraffe.M(T1),
// override Giraffe.M(T2)
//
// According to the spec, the override methods should not even be there. But they are.
//
// When we constructed the applicable candidate set we already removed everything that
// was less-overridden. So the applicable candidate set contains:
//
// virtual Mammal.M(T3),
// override Giraffe.M(T1),
// override Giraffe.M(T2)
//
// Again, that is not what should be there; what should be there are the three non-
// overriding methods. For the purposes of removing more stuff, we need to behave as
// though that's what was there.
//
// The presence of Giraffe.M(T2) does *not* justify the removal of Mammal.M(T3); it is
// not to be considered a method of Giraffe, but rather a method of Mammal for the
// purposes of removing other methods.
//
// However, the presence of Mammal.M(T3) does justify the removal of Giraffe.M(T1). Why?
// Because the presence of Mammal.M(T3) justifies the removal of Animal.M(T1), and that
// is what is supposed to be in the set instead of Giraffe.M(T1).
//
// The resulting candidate set after the filtering according to the spec should be:
//
// virtual Mammal.M(T3), virtual Mammal.M(T2)
//
// But what we actually want to be there is:
//
// virtual Mammal.M(T3), override Giraffe.M(T2)
//
// So that a "go to definition" (should the latter be chosen as best) goes to the override.
//
// OK, so what are we going to do here?
//
// First, deal with this business about object and interfaces.
RemoveAllInterfaceMembers(results);
// Second, apply the rule that we eliminate any method whose *original declaring type*
// is a base type of the original declaring type of any other method.
// Note that this (and several of the other algorithms in overload resolution) is
// O(n^2). (We expect that n will be relatively small. Also, we're trying to do these
// algorithms without allocating hardly any additional memory, which pushes us towards
// walking data structures multiple times rather than caching information about them.)
for (int f = 0; f < results.Count; ++f)
{
var result = results[f];
// As in dev12, we want to drop use site errors from less-derived types.
// NOTE: Because of use site warnings, a result with a diagnostic to report
// might not have kind UseSiteError. This could result in a kind being
// switched to LessDerived (i.e. loss of information), but it is the most
// straightforward way to suppress use site diagnostics from less-derived
// members.
if (!(result.Result.IsValid || result.HasUseSiteDiagnosticToReport))
{
continue;
}
// Note that we are doing something which appears a bit dodgy here: we're modifying
// the validity of elements of the set while inside an outer loop which is filtering
// the set based on validity. This means that we could remove an item from the set
// that we ought to be processing later. However, because the "is a base type of"
// relationship is transitive, that's OK. For example, suppose we have members
// Cat.M, Mammal.M and Animal.M in the set. The first time through the outer loop we
// eliminate Mammal.M and Animal.M, and therefore we never process Mammal.M the
// second time through the outer loop. That's OK, because we have already done the
// work necessary to eliminate methods on base types of Mammal when we eliminated
// methods on base types of Cat.
if (IsLessDerivedThanAny(result.LeastOverriddenMember.ContainingType, results, ref useSiteDiagnostics))
{
results[f] = new MemberResolutionResult<TMember>(result.Member, result.LeastOverriddenMember, MemberAnalysisResult.LessDerived());
}
}
}
// Is this type a base type of any valid method on the list?
private static bool IsLessDerivedThanAny<TMember>(TypeSymbol type, ArrayBuilder<MemberResolutionResult<TMember>> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
for (int f = 0; f < results.Count; ++f)
{
var result = results[f];
if (!result.Result.IsValid)
{
continue;
}
var currentType = result.LeastOverriddenMember.ContainingType;
// For purposes of removing less-derived methods, object is considered to be a base
// type of any type other than itself.
// UNDONE: Do we also need to special-case System.Array being a base type of array,
// and so on?
if (type.SpecialType == SpecialType.System_Object && currentType.SpecialType != SpecialType.System_Object)
{
return true;
}
if (currentType.IsInterfaceType() && type.IsInterfaceType() && currentType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics).Contains((NamedTypeSymbol)type))
{
return true;
}
else if (currentType.IsClassType() && type.IsClassType() && currentType.IsDerivedFrom(type, ignoreDynamic: false, useSiteDiagnostics: ref useSiteDiagnostics))
{
return true;
}
}
return false;
}
private static void RemoveAllInterfaceMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results)
where TMember : Symbol
{
// Consider the following case:
//
// interface IFoo { string ToString(); }
// class C { public override string ToString() { whatever } }
// class D : C, IFoo
// {
// public override string ToString() { whatever }
// string IFoo.ToString() { whatever }
// }
// ...
// void M<U>(U u) where U : C, IFoo { u.ToString(); } // ???
// ...
// M(new D());
//
// What should overload resolution do on the call to u.ToString()?
//
// We will have IFoo.ToString and C.ToString (which is an override of object.ToString)
// in the candidate set. Does the rule apply to eliminate all interface methods? NO. The
// rule only applies if the candidate set contains a method which originally came from a
// class type other than object. The method C.ToString is the "slot" for
// object.ToString, so this counts as coming from object. M should call the explicit
// interface implementation.
//
// If, by contrast, that said
//
// class C { public new virtual string ToString() { whatever } }
//
// Then the candidate set contains a method ToString which comes from a class type other
// than object. The interface method should be eliminated and M should call virtual
// method C.ToString().
bool anyClassOtherThanObject = false;
for (int f = 0; f < results.Count; f++)
{
var result = results[f];
if (!result.Result.IsValid)
{
continue;
}
var type = result.LeastOverriddenMember.ContainingType;
if (type.IsClassType() && type.GetSpecialTypeSafe() != SpecialType.System_Object)
{
anyClassOtherThanObject = true;
break;
}
}
if (!anyClassOtherThanObject)
{
return;
}
for (int f = 0; f < results.Count; f++)
{
var result = results[f];
if (!result.Result.IsValid)
{
continue;
}
var member = result.Member;
if (member.ContainingType.IsInterfaceType())
{
results[f] = new MemberResolutionResult<TMember>(member, result.LeastOverriddenMember, MemberAnalysisResult.LessDerived());
}
}
}
// Perform instance constructor overload resolution, storing the results into "results". If
// completeResults is false, then invalid results don't have to be stored. The results will
// still contain all possible successful resolution.
private void PerformObjectCreationOverloadResolution(
ArrayBuilder<MemberResolutionResult<MethodSymbol>> results,
ImmutableArray<MethodSymbol> constructors,
AnalyzedArguments arguments,
bool completeResults,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// SPEC: The instance constructor to invoke is determined using the overload resolution
// SPEC: rules of 7.5.3. The set of candidate instance constructors consists of all
// SPEC: accessible instance constructors declared in T which are applicable with respect
// SPEC: to A (7.5.3.1). If the set of candidate instance constructors is empty, or if a
// SPEC: single best instance constructor cannot be identified, a binding-time error occurs.
foreach (MethodSymbol constructor in constructors)
{
AddConstructorToCandidateSet(constructor, results, arguments, completeResults, ref useSiteDiagnostics);
}
ReportUseSiteDiagnostics(results, ref useSiteDiagnostics);
// The best method of the set of candidate methods is identified. If a single best
// method cannot be identified, the method invocation is ambiguous, and a binding-time
// error occurs.
RemoveWorseMembers(results, arguments, ref useSiteDiagnostics);
return;
}
private static void ReportUseSiteDiagnostics<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
foreach (MemberResolutionResult<TMember> result in results)
{
if (result.HasUseSiteDiagnosticToReport)
{
useSiteDiagnostics = useSiteDiagnostics ?? new HashSet<DiagnosticInfo>();
useSiteDiagnostics.Add(result.Member.GetUseSiteDiagnostic());
}
}
}
private void RemoveWorseMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
// SPEC: Given the set of applicable candidate function members, the best function member in
// SPEC: that set is located. Otherwise, the best function member is the one function member
// SPEC: that is better than all other function members with respect to the given argument
// SPEC: list.
// Note that the above rules require that the best member be *better* than all other
// applicable candidates. Consider three overloads such that:
//
// 3 beats 2
// 2 beats 1
// 3 is neither better than nor worse than 1
//
// It is tempting to say that overload 3 is the winner because it is the one method
// that beats something, and is beaten by nothing. But that would be incorrect;
// method 3 needs to beat all other methods, including method 1.
//
// We work up a full analysis of every member of the set. If it is worse than anything
// then we need to do no more work; we know it cannot win. But it is also possible that
// it is not worse than anything but not better than everything.
const int unknown = 0;
const int worseThanSomething = 1;
const int notBetterThanEverything = 2;
const int betterThanEverything = 3;
var worse = ArrayBuilder<int>.GetInstance(results.Count, unknown);
for (int c1Idx = 0; c1Idx < results.Count; c1Idx++)
{
var c1result = results[c1Idx];
// If we already know this is worse than something else, no need to check again.
if (!c1result.Result.IsValid || worse[c1Idx] == worseThanSomething)
{
continue;
}
bool c1IsBetterThanEverything = true;
for (int c2Idx = 0; c2Idx < results.Count; c2Idx++)
{
var c2result = results[c2Idx];
if (!c2result.Result.IsValid)
{
continue;
}
if (c1result.Member == c2result.Member)
{
continue;
}
var better = BetterFunctionMember(c1result, c2result, arguments.Arguments, ref useSiteDiagnostics);
if (better == BetterResult.Left)
{
worse[c2Idx] = worseThanSomething;
}
else
{
c1IsBetterThanEverything = false;
if (better == BetterResult.Right)
{
worse[c1Idx] = worseThanSomething;
break;
}
}
}
if (worse[c1Idx] == unknown)
{
// c1 was not worse than anything. Was it better than everything?
worse[c1Idx] = c1IsBetterThanEverything ? betterThanEverything : notBetterThanEverything;
}
}
// See we have a winner, otherwise we might need to perform additional analysis
// in order to improve diagnostics
bool haveBestCandidate = false;
int countOfNotBestCandidates = 0;
int notBestIdx = -1;
for (int i = 0; i < worse.Count; ++i)
{
Debug.Assert(!results[i].Result.IsValid || worse[i] != unknown);
if (worse[i] == betterThanEverything)
{
haveBestCandidate = true;
break;
}
else if (worse[i] == notBetterThanEverything)
{
countOfNotBestCandidates++;
notBestIdx = i;
}
}
Debug.Assert(countOfNotBestCandidates == 0 || !haveBestCandidate);
if (haveBestCandidate || countOfNotBestCandidates == 0)
{
for (int i = 0; i < worse.Count; ++i)
{
Debug.Assert(!results[i].Result.IsValid || worse[i] != unknown);
if (worse[i] == worseThanSomething || worse[i] == notBetterThanEverything)
{
results[i] = new MemberResolutionResult<TMember>(results[i].Member, results[i].LeastOverriddenMember, MemberAnalysisResult.Worse());
}
}
}
else if (countOfNotBestCandidates == 1)
{
for (int i = 0; i < worse.Count; ++i)
{
Debug.Assert(!results[i].Result.IsValid || worse[i] != unknown);
if (worse[i] == worseThanSomething)
{
// Mark those candidates, that are worse than the single notBest candidate, as Worst in order to improve error reporting.
var analysisResult = BetterFunctionMember(results[notBestIdx], results[i], arguments.Arguments, ref useSiteDiagnostics) == BetterResult.Left ?
MemberAnalysisResult.Worst() :
MemberAnalysisResult.Worse();
results[i] = new MemberResolutionResult<TMember>(results[i].Member, results[i].LeastOverriddenMember, analysisResult);
}
else
{
Debug.Assert(worse[i] != notBetterThanEverything || i == notBestIdx);
}
}
Debug.Assert(worse[notBestIdx] == notBetterThanEverything);
results[notBestIdx] = new MemberResolutionResult<TMember>(results[notBestIdx].Member, results[notBestIdx].LeastOverriddenMember, MemberAnalysisResult.Worse());
}
else
{
Debug.Assert(countOfNotBestCandidates > 1);
for (int i = 0; i < worse.Count; ++i)
{
Debug.Assert(!results[i].Result.IsValid || worse[i] != unknown);
if (worse[i] == worseThanSomething)
{
// Mark those candidates, that are worse than something, as Worst in order to improve error reporting.
results[i] = new MemberResolutionResult<TMember>(results[i].Member, results[i].LeastOverriddenMember, MemberAnalysisResult.Worst());
}
else if (worse[i] == notBetterThanEverything)
{
results[i] = new MemberResolutionResult<TMember>(results[i].Member, results[i].LeastOverriddenMember, MemberAnalysisResult.Worse());
}
}
}
worse.Free();
}
// Return the parameter type corresponding to the given argument index.
private static TypeSymbol GetParameterType(int argIndex, MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters)
{
RefKind discarded;
return GetParameterType(argIndex, result, parameters, out discarded);
}
// Return the parameter type corresponding to the given argument index.
private static TypeSymbol GetParameterType(int argIndex, MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, out RefKind refKind)
{
int paramIndex = result.ParameterFromArgument(argIndex);
ParameterSymbol parameter = parameters[paramIndex];
refKind = parameter.RefKind;
if (result.Kind == MemberResolutionKind.ApplicableInExpandedForm &&
parameter.IsParams && parameter.Type.TypeKind == TypeKind.Array)
{
return ((ArrayTypeSymbol)parameter.Type).ElementType;
}
else
{
return parameter.Type;
}
}
private BetterResult BetterFunctionMember<TMember>(
MemberResolutionResult<TMember> m1,
MemberResolutionResult<TMember> m2,
ArrayBuilder<BoundExpression> arguments,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
Debug.Assert(m1.Result.IsValid);
Debug.Assert(m2.Result.IsValid);
Debug.Assert(arguments != null);
// Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method/property on an instance of a COM imported type.
// We should have ignored the 'ref' on the parameter while determining the applicability of argument for the given method call.
// As per Devdiv Bug #696573: '[Interop] Com omit ref overload resolution is incorrect', we must prefer non-ref omitted methods over ref omitted methods
// when determining the BetterFunctionMember.
// During argument rewriting, we will replace the argument value with a temporary local and pass that local by reference.
bool hasAnyRefOmittedArgument1 = m1.Result.HasAnyRefOmittedArgument;
bool hasAnyRefOmittedArgument2 = m2.Result.HasAnyRefOmittedArgument;
if (hasAnyRefOmittedArgument1 != hasAnyRefOmittedArgument2)
{
return hasAnyRefOmittedArgument1 ? BetterResult.Right : BetterResult.Left;
}
else
{
return BetterFunctionMember(m1, m2, arguments, considerRefKinds: hasAnyRefOmittedArgument1, useSiteDiagnostics: ref useSiteDiagnostics);
}
}
private BetterResult BetterFunctionMember<TMember>(
MemberResolutionResult<TMember> m1,
MemberResolutionResult<TMember> m2,
ArrayBuilder<BoundExpression> arguments,
bool considerRefKinds,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
Debug.Assert(m1.Result.IsValid);
Debug.Assert(m2.Result.IsValid);
Debug.Assert(arguments != null);
// SPEC:
// Parameter lists for each of the candidate function members are constructed in the following way:
// The expanded form is used if the function member was applicable only in the expanded form.
// Optional parameters with no corresponding arguments are removed from the parameter list
// The parameters are reordered so that they occur at the same position as the corresponding argument in the argument list.
// We don't actually create these lists, for efficiency reason. But we iterate over the arguments
// and get the correspond parameter types.
BetterResult result = BetterResult.Neither;
bool okToDowngradeResultToNeither = false;
bool ignoreDowngradableToNeither = false;
// Given an argument list A with a set of argument expressions { E1, E2, ..., EN } and two
// applicable function members MP and MQ with parameter types { P1, P2, ..., PN } and { Q1, Q2, ..., QN },
// MP is defined to be a better function member than MQ if
// for each argument, the implicit conversion from EX to QX is not better than the
// implicit conversion from EX to PX, and for at least one argument, the conversion from
// EX to PX is better than the conversion from EX to QX.
bool allSame = true; // Are all parameter types equivalent by identify conversions?
int i;
for (i = 0; i < arguments.Count; ++i)
{
var argumentKind = arguments[i].Kind;
// If these are both applicable varargs methods and we're looking at the __arglist argument
// then clearly neither of them is going to be better in this argument.
if (argumentKind == BoundKind.ArgListOperator)
{
Debug.Assert(i == arguments.Count - 1);
Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg());
continue;
}
RefKind refKind1, refKind2;
var type1 = GetParameterType(i, m1.Result, m1.LeastOverriddenMember.GetParameters(), out refKind1);
var type2 = GetParameterType(i, m2.Result, m2.LeastOverriddenMember.GetParameters(), out refKind2);
bool okToDowngradeToNeither;
var r = BetterConversionFromExpression(arguments[i],
type1,
m1.Result.ConversionForArg(i),
refKind1,
type2,
m2.Result.ConversionForArg(i),
refKind2,
considerRefKinds,
ref useSiteDiagnostics,
out okToDowngradeToNeither);
if (r == BetterResult.Neither)
{
if (allSame && Conversions.ClassifyImplicitConversion(type1, type2, ref useSiteDiagnostics).Kind != ConversionKind.Identity)
{
allSame = false;
}
// We learned nothing from this one. Keep going.
continue;
}
if (!considerRefKinds || Conversions.ClassifyImplicitConversion(type1, type2, ref useSiteDiagnostics).Kind != ConversionKind.Identity)
{
// If considerRefKinds is false, conversion between parameter types isn't classified by the if condition.
// This assert is here to verify the assumption that the conversion is never an identity in that case and
// we can skip classification as an optimization.
Debug.Assert(considerRefKinds || Conversions.ClassifyImplicitConversion(type1, type2, ref useSiteDiagnostics).Kind != ConversionKind.Identity);
allSame = false;
}
// One of them was better. Does that contradict a previous result or add a new fact?
if (result == BetterResult.Neither)
{
if (!(ignoreDowngradableToNeither && okToDowngradeToNeither))
{
// Add a new fact; we know that one of them is better when we didn't know that before.
result = r;
okToDowngradeResultToNeither = okToDowngradeToNeither;
}
}
else if (result != r)
{
// We previously got, say, Left is better in one place. Now we have that Right
// is better in one place. We know we can bail out at this point; neither is
// going to be better than the other.
// But first, let's see we we can ignore the ambiguity due to an undocumented legacy behavior of the compiler.
// This is not part of the language spec.
if (okToDowngradeResultToNeither)
{
if (okToDowngradeToNeither)
{
// Ignore the new information and the current result. Going forward,
// continue ignoring any downgradable information.
result = BetterResult.Neither;
okToDowngradeResultToNeither = false;
ignoreDowngradableToNeither = true;
continue;
}
else
{
// Current result can be ignored, but the new information cannot be ignored.
// Let's ignore the current result.
result = r;
okToDowngradeResultToNeither = false;
continue;
}
}
else if (okToDowngradeToNeither)
{
// Current result cannot be ignored, but the new information can be ignored.
// Let's ignore it and continue with the current result.
continue;
}
result = BetterResult.Neither;
break;
}
else
{
Debug.Assert(result == r);
Debug.Assert(result == BetterResult.Left || result == BetterResult.Right);
okToDowngradeResultToNeither = (okToDowngradeResultToNeither && okToDowngradeToNeither);
}
}
// Was one unambiguously better? Return it.
if (result != BetterResult.Neither)
{
return result;
}
// In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are
// equivalent (i.e. each Pi has an identity conversion to the corresponding Qi), the
// following tie-breaking rules are applied, in order, to determine the better function
// member.
int m1ParameterCount;
int m2ParameterCount;
int m1ParametersUsedIncludingExpansionAndOptional;
int m2ParametersUsedIncludingExpansionAndOptional;
GetParameterCounts(m1, arguments, out m1ParameterCount, out m1ParametersUsedIncludingExpansionAndOptional);
GetParameterCounts(m2, arguments, out m2ParameterCount, out m2ParametersUsedIncludingExpansionAndOptional);
// We might have got out of the loop above early and allSame isn't completely calculated.
// We need to ensure that we are not going to skip over the next 'if' because of that.
if (allSame && m1ParametersUsedIncludingExpansionAndOptional == m2ParametersUsedIncludingExpansionAndOptional)
{
// Complete comparison for the remaining parameter types
for (i = i + 1; i < arguments.Count; ++i)
{
var argumentKind = arguments[i].Kind;
// If these are both applicable varargs methods and we're looking at the __arglist argument
// then clearly neither of them is going to be better in this argument.
if (argumentKind == BoundKind.ArgListOperator)
{
Debug.Assert(i == arguments.Count - 1);
Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg());
continue;
}
RefKind refKind1, refKind2;
var type1 = GetParameterType(i, m1.Result, m1.LeastOverriddenMember.GetParameters(), out refKind1);
var type2 = GetParameterType(i, m2.Result, m2.LeastOverriddenMember.GetParameters(), out refKind2);
if (Conversions.ClassifyImplicitConversion(type1, type2, ref useSiteDiagnostics).Kind != ConversionKind.Identity)
{
allSame = false;
break;
}
}
}
// SPEC VIOLATION: When checking for matching parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN},
// native compiler includes types of optional parameters. We partially duplicate this behavior
// here by comparing the number of parameters used taking params expansion and
// optional parameters into account.
if (!allSame || m1ParametersUsedIncludingExpansionAndOptional != m2ParametersUsedIncludingExpansionAndOptional)
{
// SPEC VIOLATION: Even when parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are
// not equivalent, we have tie-breaking rules.
//
// Relevant code in the native compiler is at the end of
// BetterTypeEnum ExpressionBinder::WhichMethodIsBetter(
// const CandidateFunctionMember &node1,
// const CandidateFunctionMember &node2,
// Type* pTypeThrough,
// ArgInfos*args)
//
if (m1ParametersUsedIncludingExpansionAndOptional != m2ParametersUsedIncludingExpansionAndOptional)
{
if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm)
{
if (m2.Result.Kind != MemberResolutionKind.ApplicableInExpandedForm)
{
return BetterResult.Right;
}
}
else if (m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm)
{
Debug.Assert(m1.Result.Kind != MemberResolutionKind.ApplicableInExpandedForm);
return BetterResult.Left;
}
// Here, if both methods needed to use optionals to fill in the signatures,
// then we are ambiguous. Otherwise, take the one that didn't need any
// optionals.
if (m1ParametersUsedIncludingExpansionAndOptional == arguments.Count)
{
return BetterResult.Left;
}
else if (m2ParametersUsedIncludingExpansionAndOptional == arguments.Count)
{
return BetterResult.Right;
}
}
return BetterResult.Neither;
}
// If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.
if (m1.Member.GetMemberArity() == 0)
{
if (m2.Member.GetMemberArity() > 0)
{
return BetterResult.Left;
}
}
else if (m2.Member.GetMemberArity() == 0)
{
return BetterResult.Right;
}
// Otherwise, if MP is applicable in its normal form and MQ has a params array and is
// applicable only in its expanded form, then MP is better than MQ.
if (m1.Result.Kind == MemberResolutionKind.ApplicableInNormalForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm)
{
return BetterResult.Left;
}
if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInNormalForm)
{
return BetterResult.Right;
}
// SPEC ERROR: The spec has a minor error in working here. It says:
//
// Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ.
// This can occur if both methods have params arrays and are applicable only in their
// expanded forms.
//
// The explanatory text actually should be normative. It should say:
//
// Otherwise, if both methods have params arrays and are applicable only in their
// expanded forms, and if MP has more declared parameters than MQ, then MP is better than MQ.
if (m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm && m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm)
{
if (m1ParameterCount > m2ParameterCount)
{
return BetterResult.Left;
}
if (m1ParameterCount < m2ParameterCount)
{
return BetterResult.Right;
}
}
// Otherwise if all parameters of MP have a corresponding argument whereas default
// arguments need to be substituted for at least one optional parameter in MQ then MP is
// better than MQ.
bool hasAll1 = m1.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || m1ParameterCount == arguments.Count;
bool hasAll2 = m2.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm || m2ParameterCount == arguments.Count;
if (hasAll1 && !hasAll2)
{
return BetterResult.Left;
}
if (!hasAll1 && hasAll2)
{
return BetterResult.Right;
}
// Otherwise, if MP has more specific parameter types than MQ, then MP is better than
// MQ. Let {R1, R2, …, RN} and {S1, S2, …, SN} represent the uninstantiated and
// unexpanded parameter types of MP and MQ. MP's parameter types are more specific than
// MQ's if, for each parameter, RX is not less specific than SX, and, for at least one
// parameter, RX is more specific than SX
// NB: OriginalDefinition, not ConstructedFrom. Substitutions into containing symbols
// must also be ignored for this tie-breaker.
var uninst1 = ArrayBuilder<TypeSymbol>.GetInstance();
var uninst2 = ArrayBuilder<TypeSymbol>.GetInstance();
var m1Original = m1.LeastOverriddenMember.OriginalDefinition.GetParameters();
var m2Original = m2.LeastOverriddenMember.OriginalDefinition.GetParameters();
for (i = 0; i < arguments.Count; ++i)
{
uninst1.Add(GetParameterType(i, m1.Result, m1Original));
uninst2.Add(GetParameterType(i, m2.Result, m2Original));
}
result = MoreSpecificType(uninst1, uninst2, ref useSiteDiagnostics);
uninst1.Free();
uninst2.Free();
if (result != BetterResult.Neither)
{
return result;
}
// UNDONE: Otherwise if one member is a non-lifted operator and the other is a lifted
// operator, the non-lifted one is better.
// The penultimate rule: Position in interactive submission chain. The last definition wins.
if (m1.Member.ContainingType.TypeKind == TypeKind.Submission && m2.Member.ContainingType.TypeKind == TypeKind.Submission)
{
// script class is always defined in source:
var compilation1 = m1.Member.DeclaringCompilation;
var compilation2 = m2.Member.DeclaringCompilation;
int submissionId1 = compilation1.GetSubmissionSlotIndex();
int submissionId2 = compilation2.GetSubmissionSlotIndex();
if (submissionId1 > submissionId2)
{
return BetterResult.Left;
}
if (submissionId1 < submissionId2)
{
return BetterResult.Right;
}
}
// Finally, if one has fewer custom modifiers, that is better
int m1ModifierCount = m1.LeastOverriddenMember.CustomModifierCount();
int m2ModifierCount = m2.LeastOverriddenMember.CustomModifierCount();
if (m1ModifierCount != m2ModifierCount)
{
return (m1ModifierCount < m2ModifierCount) ? BetterResult.Left : BetterResult.Right;
}
// Otherwise, neither function member is better.
return BetterResult.Neither;
}
private static void GetParameterCounts<TMember>(MemberResolutionResult<TMember> m, ArrayBuilder<BoundExpression> arguments, out int declaredParameterCount, out int parametersUsedIncludingExpansionAndOptional) where TMember : Symbol
{
declaredParameterCount = m.Member.GetParameterCount();
if (m.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm)
{
if (arguments.Count < declaredParameterCount)
{
// params parameter isn't used (see ExpressionBinder::TryGetExpandedParams in the native compiler)
parametersUsedIncludingExpansionAndOptional = declaredParameterCount - 1;
}
else
{
parametersUsedIncludingExpansionAndOptional = arguments.Count;
}
}
else
{
parametersUsedIncludingExpansionAndOptional = declaredParameterCount;
}
}
private static BetterResult MoreSpecificType(ArrayBuilder<TypeSymbol> t1, ArrayBuilder<TypeSymbol> t2, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
Debug.Assert(t1.Count == t2.Count);
// For t1 to be more specific than t2, it has to be not less specific in every member,
// and more specific in at least one.
var result = BetterResult.Neither;
for (int i = 0; i < t1.Count; ++i)
{
var r = MoreSpecificType(t1[i], t2[i], ref useSiteDiagnostics);
if (r == BetterResult.Neither)
{
// We learned nothing. Do nothing.
}
else if (result == BetterResult.Neither)
{
// We have found the first more specific type. See if
// all the rest on this side are not less specific.
result = r;
}
else if (result != r)
{
// We have more specific types on both left and right, so we
// cannot succeed in picking a better type list. Bail out now.
return BetterResult.Neither;
}
}
return result;
}
private static BetterResult MoreSpecificType(TypeSymbol t1, TypeSymbol t2, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// Spec 7.5.3.2:
// - A type parameter is less specific than a non-type parameter.
var t1IsTypeParameter = t1.IsTypeParameter();
var t2IsTypeParameter = t2.IsTypeParameter();
if (t1IsTypeParameter && !t2IsTypeParameter)
{
return BetterResult.Right;
}
if (!t1IsTypeParameter && t2IsTypeParameter)
{
return BetterResult.Left;
}
if (t1IsTypeParameter && t2IsTypeParameter)
{
return BetterResult.Neither;
}
// Spec:
// - An array type is more specific than another array type (with the same number of dimensions)
// if the element type of the first is more specific than the element type of the second.
if (t1.IsArray())
{
var arr1 = (ArrayTypeSymbol)t1;
var arr2 = (ArrayTypeSymbol)t2;
// We should not have gotten here unless there were identity conversions
// between the two types.
Debug.Assert(arr1.Rank == arr2.Rank);
return MoreSpecificType(arr1.ElementType, arr2.ElementType, ref useSiteDiagnostics);
}
// SPEC EXTENSION: We apply the same rule to pointer types.
if (t1.TypeKind == TypeKind.Pointer)
{
var p1 = (PointerTypeSymbol)t1;
var p2 = (PointerTypeSymbol)t2;
return MoreSpecificType(p1.PointedAtType, p2.PointedAtType, ref useSiteDiagnostics);
}
if (t1.IsDynamic() || t2.IsDynamic())
{
Debug.Assert(t1.IsDynamic() && t2.IsDynamic() ||
t1.IsDynamic() && t2.SpecialType == SpecialType.System_Object ||
t2.IsDynamic() && t1.SpecialType == SpecialType.System_Object);
return BetterResult.Neither;
}
// Spec:
// - A constructed type is more specific than another
// constructed type (with the same number of type arguments) if at least one type
// argument is more specific and no type argument is less specific than the
// corresponding type argument in the other.
var n1 = t1 as NamedTypeSymbol;
var n2 = t2 as NamedTypeSymbol;
Debug.Assert(((object)n1 == null) == ((object)n2 == null));
if ((object)n1 == null)
{
return BetterResult.Neither;
}
// We should not have gotten here unless there were identity conversions between the
// two types.
Debug.Assert(n1.OriginalDefinition == n2.OriginalDefinition);
var allTypeArgs1 = ArrayBuilder<TypeSymbol>.GetInstance();
var allTypeArgs2 = ArrayBuilder<TypeSymbol>.GetInstance();
n1.GetAllTypeArguments(allTypeArgs1, ref useSiteDiagnostics);
n2.GetAllTypeArguments(allTypeArgs2, ref useSiteDiagnostics);
var result = MoreSpecificType(allTypeArgs1, allTypeArgs2, ref useSiteDiagnostics);
allTypeArgs1.Free();
allTypeArgs2.Free();
return result;
}
// Determine whether t1 or t2 is a better conversion target from node.
private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, TypeSymbol t2, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
Debug.Assert(node.Kind != BoundKind.UnboundLambda);
bool ignore;
return BetterConversionFromExpression(
node,
t1,
Conversions.ClassifyImplicitConversionFromExpression(node, t1, ref useSiteDiagnostics),
t2,
Conversions.ClassifyImplicitConversionFromExpression(node, t2, ref useSiteDiagnostics),
ref useSiteDiagnostics,
out ignore);
}
// Determine whether t1 or t2 is a better conversion target from node, possibly considering parameter ref kinds.
private BetterResult BetterConversionFromExpression(
BoundExpression node,
TypeSymbol t1,
Conversion conv1,
RefKind refKind1,
TypeSymbol t2,
Conversion conv2,
RefKind refKind2,
bool considerRefKinds,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
out bool okToDowngradeToNeither)
{
okToDowngradeToNeither = false;
if (considerRefKinds)
{
// We may need to consider the ref kinds of the parameters while determining the better conversion from the given expression to the respective parameter types.
// This is needed for the omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method within a COM imported type.
// We can reach here only if we had at least one ref omitted argument for the given call, which must be a call to a method within a COM imported type.
// Algorithm for determining the better conversion from expression when ref kinds need to be considered is NOT provided in the C# language specification,
// see section 7.5.3.3 'Better Conversion From Expression'.
// We match native compiler's behavior for determining the better conversion as follows:
// 1) If one of the contending parameters is a 'ref' parameter, say p1, and other is a non-ref parameter, say p2,
// then p2 is a better result if the argument has an identity conversion to p2's type. Otherwise, neither result is better.
// 2) Otherwise, if both the contending parameters are 'ref' parameters, neither result is better.
// 3) Otherwise, we use the algorithm in 7.5.3.3 for determining the better conversion without considering ref kinds.
// NOTE: Native compiler does not explicitly implement the above algorithm, but gets it by default. This is due to the fact that the RefKind of a parameter
// NOTE: gets considered while classifying conversions between parameter types when computing better conversion target in the native compiler.
// NOTE: Roslyn correctly follows the specification and ref kinds are not considered while classifying conversions between types, see method BetterConversionTarget.
Debug.Assert(refKind1 == RefKind.None || refKind1 == RefKind.Ref);
Debug.Assert(refKind2 == RefKind.None || refKind2 == RefKind.Ref);
if (refKind1 != refKind2)
{
if (refKind1 == RefKind.None)
{
return conv1.Kind == ConversionKind.Identity ? BetterResult.Left : BetterResult.Neither;
}
else
{
return conv2.Kind == ConversionKind.Identity ? BetterResult.Right : BetterResult.Neither;
}
}
else if (refKind1 == RefKind.Ref)
{
return BetterResult.Neither;
}
}
return BetterConversionFromExpression(node, t1, conv1, t2, conv2, ref useSiteDiagnostics, out okToDowngradeToNeither);
}
// Determine whether t1 or t2 is a better conversion target from node.
private BetterResult BetterConversionFromExpression(BoundExpression node, TypeSymbol t1, Conversion conv1, TypeSymbol t2, Conversion conv2, ref HashSet<DiagnosticInfo> useSiteDiagnostics, out bool okToDowngradeToNeither)
{
okToDowngradeToNeither = false;
if (Conversions.HasIdentityConversion(t1, t2))
{
// Both parameters have the same type.
return BetterResult.Neither;
}
var lambdaOpt = node as UnboundLambda;
// Given an implicit conversion C1 that converts from an expression E to a type T1,
// and an implicit conversion C2 that converts from an expression E to a type T2,
// C1 is a better conversion than C2 if E does not exactly match T2 and one of the following holds:
bool t1MatchesExactly = ExpressionMatchExactly(node, t1, ref useSiteDiagnostics);
bool t2MatchesExactly = ExpressionMatchExactly(node, t2, ref useSiteDiagnostics);
if (t1MatchesExactly)
{
if (t2MatchesExactly)
{
// both exactly match expression
return BetterResult.Neither;
}
// - E exactly matches T1
okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, lambdaOpt, t1, t2, ref useSiteDiagnostics, false);
return BetterResult.Left;
}
else if (t2MatchesExactly)
{
// - E exactly matches T1
okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, lambdaOpt, t1, t2, ref useSiteDiagnostics, false);
return BetterResult.Right;
}
// - T1 is a better conversion target than T2
return BetterConversionTarget(lambdaOpt, t1, t2, ref useSiteDiagnostics, out okToDowngradeToNeither);
}
private bool ExpressionMatchExactly(BoundExpression node, TypeSymbol t, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// Given an expression E and a type T, E exactly matches T if one of the following holds:
// - E has a type S, and an identity conversion exists from S to T
if ((object)node.Type != null && Conversions.HasIdentityConversion(node.Type, t))
{
return true;
}
// - E is an anonymous function, T is either a delegate type D or an expression tree
// type Expression<D>, D has a return type Y, and one of the following holds:
NamedTypeSymbol d;
MethodSymbol invoke;
TypeSymbol y;
if (node.Kind == BoundKind.UnboundLambda &&
(object)(d = t.GetDelegateType()) != null &&
(object)(invoke = d.DelegateInvokeMethod) != null &&
(y = invoke.ReturnType).SpecialType != SpecialType.System_Void)
{
BoundLambda lambda = ((UnboundLambda)node).BindForReturnTypeInference(d);
// - an inferred return type X exists for E in the context of the parameter list of D(§7.5.2.12), and an identity conversion exists from X to Y
TypeSymbol x = lambda.InferredReturnType(ref useSiteDiagnostics);
if ((object)x != null && Conversions.HasIdentityConversion(x, y))
{
return true;
}
if (lambda.Symbol.IsAsync)
{
// Dig through Task<...> for an async lambda.
if (y.OriginalDefinition == Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T))
{
y = ((NamedTypeSymbol)y).TypeArgumentsNoUseSiteDiagnostics[0];
}
else
{
y = null;
}
}
if ((object)y != null)
{
// - The body of E is an expression that exactly matches Y, or
// has a return statement with expression and all return statements have expression that
// exactly matches Y.
// Handle trivial cases first
switch (lambda.Body.Statements.Length)
{
case 0:
break;
case 1:
if (lambda.Body.Statements[0].Kind == BoundKind.ReturnStatement)
{
var returnStmt = (BoundReturnStatement)lambda.Body.Statements[0];
if (returnStmt.ExpressionOpt != null && ExpressionMatchExactly(returnStmt.ExpressionOpt, y, ref useSiteDiagnostics))
{
return true;
}
}
else
{
goto default;
}
break;
default:
var returnStatements = ArrayBuilder<BoundReturnStatement>.GetInstance();
var walker = new ReturnStatements(returnStatements);
walker.Visit(lambda.Body);
bool result = false;
foreach (BoundReturnStatement r in returnStatements)
{
if (r.ExpressionOpt == null || !ExpressionMatchExactly(r.ExpressionOpt, y, ref useSiteDiagnostics))
{
result = false;
break;
}
else
{
result = true;
}
}
returnStatements.Free();
if (result)
{
return true;
}
break;
}
}
}
return false;
}
private class ReturnStatements : BoundTreeWalker
{
private readonly ArrayBuilder<BoundReturnStatement> _returns;
public ReturnStatements(ArrayBuilder<BoundReturnStatement> returns)
{
_returns = returns;
}
public override BoundNode VisitLambda(BoundLambda node)
{
// Do not recurse into nested lambdas; we don't want their returns.
return null;
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
_returns.Add(node);
return null;
}
}
private BetterResult BetterConversionTarget(UnboundLambda lambdaOpt, TypeSymbol type1, TypeSymbol type2, ref HashSet<DiagnosticInfo> useSiteDiagnostics, out bool okToDowngradeToNeither)
{
okToDowngradeToNeither = false;
if (Conversions.HasIdentityConversion(type1, type2))
{
// Both types are the same type.
return BetterResult.Neither;
}
// Given two different types T1 and T2, T1 is a better conversion target than T2 if no implicit conversion from T2 to T1 exists,
// and at least one of the following holds:
bool type1ToType2 = Conversions.ClassifyImplicitConversion(type1, type2, ref useSiteDiagnostics).IsImplicit;
bool type2ToType1 = Conversions.ClassifyImplicitConversion(type2, type1, ref useSiteDiagnostics).IsImplicit;
if (type1ToType2)
{
if (type2ToType1)
{
// An implicit conversion both ways.
return BetterResult.Neither;
}
// - An implicit conversion from T1 to T2 exists
okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Left, lambdaOpt, type1, type2, ref useSiteDiagnostics, true);
return BetterResult.Left;
}
else if (type2ToType1)
{
// - An implicit conversion from T1 to T2 exists
okToDowngradeToNeither = lambdaOpt != null && CanDowngradeConversionFromLambdaToNeither(BetterResult.Right, lambdaOpt, type1, type2, ref useSiteDiagnostics, true);
return BetterResult.Right;
}
bool ignore;
var task_T = Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T);
if ((object)task_T != null)
{
if (type1.OriginalDefinition == task_T)
{
if (type2.OriginalDefinition == task_T)
{
// - T1 is Task<S1>, T2 is Task<S2>, and S1 is a better conversion target than S2
return BetterConversionTarget(null,
((NamedTypeSymbol)type1).TypeArgumentsNoUseSiteDiagnostics[0],
((NamedTypeSymbol)type2).TypeArgumentsNoUseSiteDiagnostics[0],
ref useSiteDiagnostics,
out ignore);
}
// A shortcut, Task<T> type cannot satisfy other rules.
return BetterResult.Neither;
}
else if (type2.OriginalDefinition == task_T)
{
// A shortcut, Task<T> type cannot satisfy other rules.
return BetterResult.Neither;
}
}
NamedTypeSymbol d1;
if ((object)(d1 = type1.GetDelegateType()) != null)
{
NamedTypeSymbol d2;
if ((object)(d2 = type2.GetDelegateType()) != null)
{
// - T1 is either a delegate type D1 or an expression tree type Expression<D1>,
// T2 is either a delegate type D2 or an expression tree type Expression<D2>,
// D1 has a return type S1 and one of the following holds:
MethodSymbol invoke1 = d1.DelegateInvokeMethod;
MethodSymbol invoke2 = d2.DelegateInvokeMethod;
if ((object)invoke1 != null && (object)invoke2 != null)
{
TypeSymbol r1 = invoke1.ReturnType;
TypeSymbol r2 = invoke2.ReturnType;
if (r1.SpecialType != SpecialType.System_Void)
{
if (r2.SpecialType == SpecialType.System_Void)
{
// - D2 is void returning
return BetterResult.Left;
}
}
else if (r2.SpecialType != SpecialType.System_Void)
{
// - D2 is void returning
return BetterResult.Right;
}
// - D2 has a return type S2, and S1 is a better conversion target than S2
return BetterConversionTarget(null, r1, r2, ref useSiteDiagnostics, out ignore);
}
}
// A shortcut, a delegate or an expression tree cannot satisfy other rules.
return BetterResult.Neither;
}
else if (type2.GetDelegateType() != null)
{
// A shortcut, a delegate or an expression tree cannot satisfy other rules.
return BetterResult.Neither;
}
// -T1 is a signed integral type and T2 is an unsigned integral type.Specifically:
// - T1 is sbyte and T2 is byte, ushort, uint, or ulong
// - T1 is short and T2 is ushort, uint, or ulong
// - T1 is int and T2 is uint, or ulong
// - T1 is long and T2 is ulong
if (IsSignedIntegralType(type1))
{
if (IsUnsignedIntegralType(type2))
{
return BetterResult.Left;
}
}
else if (IsUnsignedIntegralType(type1) && IsSignedIntegralType(type2))
{
return BetterResult.Right;
}
return BetterResult.Neither;
}
private bool CanDowngradeConversionFromLambdaToNeither(BetterResult currentResult, UnboundLambda lambda, TypeSymbol type1, TypeSymbol type2, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool fromTypeAnalysis)
{
// DELIBERATE SPEC VIOLATION: See bug 11961.
// The native compiler uses one algorithm for determining betterness of lambdas and another one
// for everything else. This is wrong; the correct behavior is to do the type analysis of
// the parameter types first, and then if necessary, do the lambda analysis. Native compiler
// skips analysis of the parameter types when they are delegate types with identical parameter
// lists and the corresponding argument is a lambda.
// There is a real-world code that breaks if we follow the specification, so we will try to fall
// back to the original behavior to avoid an ambiguity that wasn't an ambiguity before.
NamedTypeSymbol d1;
if ((object)(d1 = type1.GetDelegateType()) != null)
{
NamedTypeSymbol d2;
if ((object)(d2 = type2.GetDelegateType()) != null)
{
MethodSymbol invoke1 = d1.DelegateInvokeMethod;
MethodSymbol invoke2 = d2.DelegateInvokeMethod;
if ((object)invoke1 != null && (object)invoke2 != null)
{
if (!IdenticalParameters(invoke1.Parameters, invoke2.Parameters))
{
return true;
}
TypeSymbol r1 = invoke1.ReturnType;
TypeSymbol r2 = invoke2.ReturnType;
#if DEBUG
if (fromTypeAnalysis)
{
Debug.Assert((r1.SpecialType == SpecialType.System_Void) == (r2.SpecialType == SpecialType.System_Void));
// Since we are dealing with variance delegate conversion and delegates have identical parameter
// lists, return types must be different and neither can be void.
Debug.Assert(r1.SpecialType != SpecialType.System_Void);
Debug.Assert(r2.SpecialType != SpecialType.System_Void);
Debug.Assert(!Conversions.HasIdentityConversion(r1, r2));
}
#endif
if (r1.SpecialType == SpecialType.System_Void)
{
if (r2.SpecialType == SpecialType.System_Void)
{
return true;
}
Debug.Assert(currentResult == BetterResult.Right);
return false;
}
else if (r2.SpecialType == SpecialType.System_Void)
{
Debug.Assert(currentResult == BetterResult.Left);
return false;
}
if (Conversions.HasIdentityConversion(r1, r2))
{
return true;
}
TypeSymbol x = lambda.InferReturnType(d1, ref useSiteDiagnostics);
if (x == null)
{
return true;
}
#if DEBUG
if (fromTypeAnalysis)
{
bool ignore;
// Since we are dealing with variance delegate conversion and delegates have identical parameter
// lists, return types must be implicitly convertible in the same direction.
// Or we might be dealing with error return types and we may have one error delegate matching exactly
// while another not being an error and not convertible.
Debug.Assert(
r1.IsErrorType() ||
r2.IsErrorType() ||
currentResult == BetterConversionTarget(null, r1, r2, ref useSiteDiagnostics, out ignore));
}
#endif
}
}
}
return false;
}
private static bool IdenticalParameters(ImmutableArray<ParameterSymbol> p1, ImmutableArray<ParameterSymbol> p2)
{
if (p1.IsDefault || p2.IsDefault)
{
// This only happens in error scenarios.
return false;
}
if (p1.Length != p2.Length)
{
return false;
}
for (int i = 0; i < p1.Length; ++i)
{
var param1 = p1[i];
var param2 = p2[i];
if (param1.RefKind != param2.RefKind)
{
return false;
}
if (!Conversions.HasIdentityConversion(param1.Type, param2.Type))
{
return false;
}
}
return true;
}
private static bool IsSignedIntegralType(TypeSymbol type)
{
if ((object)type != null && type.IsNullableType())
{
type = type.GetNullableUnderlyingType();
}
switch (type.GetSpecialTypeSafe())
{
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
return true;
default:
return false;
}
}
private static bool IsUnsignedIntegralType(TypeSymbol type)
{
if ((object)type != null && type.IsNullableType())
{
type = type.GetNullableUnderlyingType();
}
switch (type.GetSpecialTypeSafe())
{
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
}
private struct EffectiveParameters
{
internal readonly ImmutableArray<TypeSymbol> ParameterTypes;
internal readonly ImmutableArray<RefKind> ParameterRefKinds;
internal EffectiveParameters(ImmutableArray<TypeSymbol> types, ImmutableArray<RefKind> refKinds)
{
ParameterTypes = types;
ParameterRefKinds = refKinds;
}
}
private EffectiveParameters GetEffectiveParametersInNormalForm<TMember>(
TMember member,
int argumentCount,
ImmutableArray<int> argToParamMap,
ArrayBuilder<RefKind> argumentRefKinds,
bool allowRefOmittedArguments)
where TMember : Symbol
{
bool discarded;
return GetEffectiveParametersInNormalForm(member, argumentCount, argToParamMap, argumentRefKinds, allowRefOmittedArguments, hasAnyRefOmittedArgument: out discarded);
}
private EffectiveParameters GetEffectiveParametersInNormalForm<TMember>(
TMember member,
int argumentCount,
ImmutableArray<int> argToParamMap,
ArrayBuilder<RefKind> argumentRefKinds,
bool allowRefOmittedArguments,
out bool hasAnyRefOmittedArgument) where TMember : Symbol
{
Debug.Assert(argumentRefKinds != null);
hasAnyRefOmittedArgument = false;
ImmutableArray<ParameterSymbol> parameters = member.GetParameters();
// We simulate an extra parameter for vararg methods
int parameterCount = member.GetParameterCount() + (member.GetIsVararg() ? 1 : 0);
if (argumentCount == parameterCount && argToParamMap.IsDefaultOrEmpty)
{
ImmutableArray<RefKind> parameterRefKinds = member.GetParameterRefKinds();
if (parameterRefKinds.IsDefaultOrEmpty || !parameterRefKinds.Any(refKind => refKind == RefKind.Ref))
{
return new EffectiveParameters(member.GetParameterTypes(), parameterRefKinds);
}
}
var types = ArrayBuilder<TypeSymbol>.GetInstance();
ArrayBuilder<RefKind> refs = null;
bool hasAnyRefArg = argumentRefKinds.Any();
for (int arg = 0; arg < argumentCount; ++arg)
{
int parm = argToParamMap.IsDefault ? arg : argToParamMap[arg];
// If this is the __arglist parameter, just skip it.
if (parm == parameters.Length)
{
continue;
}
var parameter = parameters[parm];
types.Add(parameter.Type);
RefKind argRefKind = hasAnyRefArg ? argumentRefKinds[arg] : RefKind.None;
RefKind paramRefKind = GetEffectiveParameterRefKind(parameter, argRefKind, allowRefOmittedArguments, ref hasAnyRefOmittedArgument);
if (refs == null)
{
if (paramRefKind != RefKind.None)
{
refs = ArrayBuilder<RefKind>.GetInstance(arg, RefKind.None);
refs.Add(paramRefKind);
}
}
else
{
refs.Add(paramRefKind);
}
}
var refKinds = refs != null ? refs.ToImmutableAndFree() : default(ImmutableArray<RefKind>);
return new EffectiveParameters(types.ToImmutableAndFree(), refKinds);
}
private RefKind GetEffectiveParameterRefKind(ParameterSymbol parameter, RefKind argRefKind, bool allowRefOmittedArguments, ref bool hasAnyRefOmittedArgument)
{
var paramRefKind = parameter.RefKind;
// Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are calling a method/property on an instance of a COM imported type.
// We must ignore the 'ref' on the parameter while determining the applicability of argument for the given method call.
// During argument rewriting, we will replace the argument value with a temporary local and pass that local by reference.
if (allowRefOmittedArguments && paramRefKind == RefKind.Ref && argRefKind == RefKind.None && !_binder.InAttributeArgument)
{
hasAnyRefOmittedArgument = true;
return RefKind.None;
}
return paramRefKind;
}
private EffectiveParameters GetEffectiveParametersInExpandedForm<TMember>(
TMember member,
int argumentCount,
ImmutableArray<int> argToParamMap,
ArrayBuilder<RefKind> argumentRefKinds,
bool allowRefOmittedArguments) where TMember : Symbol
{
bool discarded;
return GetEffectiveParametersInExpandedForm(member, argumentCount, argToParamMap, argumentRefKinds, allowRefOmittedArguments, hasAnyRefOmittedArgument: out discarded);
}
private EffectiveParameters GetEffectiveParametersInExpandedForm<TMember>(
TMember member,
int argumentCount,
ImmutableArray<int> argToParamMap,
ArrayBuilder<RefKind> argumentRefKinds,
bool allowRefOmittedArguments,
out bool hasAnyRefOmittedArgument) where TMember : Symbol
{
Debug.Assert(argumentRefKinds != null);
var types = ArrayBuilder<TypeSymbol>.GetInstance();
var refs = ArrayBuilder<RefKind>.GetInstance();
bool anyRef = false;
var parameters = member.GetParameters();
var elementType = ((ArrayTypeSymbol)parameters[parameters.Length - 1].Type).ElementType;
bool hasAnyRefArg = argumentRefKinds.Any();
hasAnyRefOmittedArgument = false;
for (int arg = 0; arg < argumentCount; ++arg)
{
var parm = argToParamMap.IsDefault ? arg : argToParamMap[arg];
var parameter = parameters[parm];
types.Add(parm == parameters.Length - 1 ? elementType : parameter.Type);
var argRefKind = hasAnyRefArg ? argumentRefKinds[arg] : RefKind.None;
var paramRefKind = GetEffectiveParameterRefKind(parameter, argRefKind, allowRefOmittedArguments, ref hasAnyRefOmittedArgument);
refs.Add(paramRefKind);
if (paramRefKind != RefKind.None)
{
anyRef = true;
}
}
var refKinds = anyRef ? refs.ToImmutable() : default(ImmutableArray<RefKind>);
refs.Free();
return new EffectiveParameters(types.ToImmutableAndFree(), refKinds);
}
internal MemberResolutionResult<TMember> IsMemberApplicableInNormalForm<TMember>(
TMember member, // method or property
TMember leastOverriddenMember, // method or property
ArrayBuilder<TypeSymbol> typeArguments,
AnalyzedArguments arguments,
bool isMethodGroupConversion,
bool allowRefOmittedArguments,
bool inferWithDynamic,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
// AnalyzeArguments matches arguments to parameter names and positions.
// For that purpose we use the most derived member.
var argumentAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion, expanded: false);
if (!argumentAnalysis.IsValid)
{
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis));
}
// Check after argument analysis, but before more complicated type inference and argument type validation.
// NOTE: The diagnostic may not be reported (e.g. if the member is later removed as less-derived).
if (member.HasUseSiteError)
{
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError());
}
bool hasAnyRefOmittedArgument;
// To determine parameter types we use the originalMember.
EffectiveParameters originalEffectiveParameters = GetEffectiveParametersInNormalForm(
GetConstructedFrom(leastOverriddenMember),
arguments.Arguments.Count,
argumentAnalysis.ArgsToParamsOpt,
arguments.RefKinds,
allowRefOmittedArguments,
out hasAnyRefOmittedArgument);
Debug.Assert(!hasAnyRefOmittedArgument || allowRefOmittedArguments);
// To determine parameter types we use the originalMember.
EffectiveParameters constructedEffectiveParameters = GetEffectiveParametersInNormalForm(
leastOverriddenMember,
arguments.Arguments.Count,
argumentAnalysis.ArgsToParamsOpt,
arguments.RefKinds,
allowRefOmittedArguments);
// The member passed to the following call is returned in the result (possibly a constructed version of it).
// The applicability is checked based on effective parameters passed in.
return IsApplicable(
member, leastOverriddenMember,
typeArguments, arguments, originalEffectiveParameters, constructedEffectiveParameters,
argumentAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument,
ref useSiteDiagnostics,
inferWithDynamic);
}
private MemberResolutionResult<TMember> IsMemberApplicableInExpandedForm<TMember>(
TMember member, // method or property
TMember leastOverriddenMember, // method or property
ArrayBuilder<TypeSymbol> typeArguments,
AnalyzedArguments arguments,
bool allowRefOmittedArguments,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
// AnalyzeArguments matches arguments to parameter names and positions.
// For that purpose we use the most derived member.
var argumentAnalysis = AnalyzeArguments(member, arguments, isMethodGroupConversion: false, expanded: true);
if (!argumentAnalysis.IsValid)
{
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis));
}
// Check after argument analysis, but before more complicated type inference and argument type validation.
// NOTE: The diagnostic may not be reported (e.g. if the member is later removed as less-derived).
if (member.HasUseSiteError)
{
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.UseSiteError());
}
bool hasAnyRefOmittedArgument;
// To determine parameter types we use the least derived member.
EffectiveParameters originalEffectiveParameters = GetEffectiveParametersInExpandedForm(
GetConstructedFrom(leastOverriddenMember),
arguments.Arguments.Count,
argumentAnalysis.ArgsToParamsOpt,
arguments.RefKinds,
allowRefOmittedArguments,
out hasAnyRefOmittedArgument);
Debug.Assert(!hasAnyRefOmittedArgument || allowRefOmittedArguments);
// To determine parameter types we use the least derived member.
EffectiveParameters constructedEffectiveParameters = GetEffectiveParametersInExpandedForm(
leastOverriddenMember,
arguments.Arguments.Count,
argumentAnalysis.ArgsToParamsOpt,
arguments.RefKinds,
allowRefOmittedArguments);
// The member passed to the following call is returned in the result (possibly a constructed version of it).
// The applicability is checked based on effective parameters passed in.
var result = IsApplicable(
member, leastOverriddenMember,
typeArguments, arguments, originalEffectiveParameters, constructedEffectiveParameters,
argumentAnalysis.ArgsToParamsOpt, hasAnyRefOmittedArgument, ref useSiteDiagnostics);
return result.Result.IsValid ?
new MemberResolutionResult<TMember>(
result.Member,
result.LeastOverriddenMember,
MemberAnalysisResult.ExpandedForm(result.Result.ArgsToParamsOpt, result.Result.ConversionsOpt, hasAnyRefOmittedArgument)) :
result;
}
private MemberResolutionResult<TMember> IsApplicable<TMember>(
TMember member, // method or property
TMember leastOverriddenMember, // method or property
ArrayBuilder<TypeSymbol> typeArgumentsBuilder,
AnalyzedArguments arguments,
EffectiveParameters originalEffectiveParameters,
EffectiveParameters constructedEffectiveParameters,
ImmutableArray<int> argsToParamsMap,
bool hasAnyRefOmittedArgument,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool inferWithDynamic = false)
where TMember : Symbol
{
bool ignoreOpenTypes;
MethodSymbol method;
EffectiveParameters effectiveParameters;
if (member.Kind == SymbolKind.Method && (method = (MethodSymbol)(Symbol)member).Arity > 0)
{
if (typeArgumentsBuilder.Count == 0 && arguments.HasDynamicArgument && !inferWithDynamic)
{
// Spec 7.5.4: Compile-time checking of dynamic overload resolution:
// * First, if F is a generic method and type arguments were provided,
// then those are substituted for the type parameters in the parameter list.
// However, if type arguments were not provided, no such substitution happens.
// * Then, any parameter whose type contains a an unsubstituted type parameter of F
// is elided, along with the corresponding arguments(s).
// We don't need to check constraints of types of the non-elided parameters since they
// have no effect on applicability of this candidate.
ignoreOpenTypes = true;
effectiveParameters = constructedEffectiveParameters;
}
else
{
MethodSymbol leastOverriddenMethod = (MethodSymbol)(Symbol)leastOverriddenMember;
ImmutableArray<TypeSymbol> typeArguments;
if (typeArgumentsBuilder.Count > 0)
{
// generic type arguments explicitly specified at call-site:
typeArguments = typeArgumentsBuilder.ToImmutable();
}
else
{
// infer generic type arguments:
MemberAnalysisResult inferenceError;
typeArguments = InferMethodTypeArguments(method, leastOverriddenMethod.ConstructedFrom.TypeParameters, arguments, originalEffectiveParameters, out inferenceError, ref useSiteDiagnostics);
if (typeArguments.IsDefault)
{
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, inferenceError);
}
}
member = (TMember)(Symbol)method.Construct(typeArguments);
leastOverriddenMember = (TMember)(Symbol)leastOverriddenMethod.ConstructedFrom.Construct(typeArguments);
// Spec (§7.6.5.1)
// Once the (inferred) type arguments are substituted for the corresponding method type parameters,
// all constructed types in the parameter list of F satisfy *their* constraints (§4.4.4),
// and the parameter list of F is applicable with respect to A (§7.5.3.1).
//
// This rule is a bit complicated; let's take a look at an example. Suppose we have
// class X<U> where U : struct {}
// ...
// void M<T>(T t, X<T> xt) where T : struct {}
// void M(object o1, object o2) {}
//
// Suppose there is a call M("", null). Type inference infers that T is string.
// M<string> is then not an applicable candidate *NOT* because string violates the
// constraint on T. That is not checked until "final validation". Rather, the
// method is not a candidate because string violates the constraint *on U*.
// The constructed method has formal parameter type X<string>, which is not legal.
// In the case given, the generic method is eliminated and the object version wins.
//
// Note also that the constraints need to be checked on *all* the formal parameter
// types, not just the ones in the *effective parameter list*. If we had:
// void M<T>(T t, X<T> xt = null) where T : struct {}
// void M<T>(object o1, object o2 = null) where T : struct {}
// and a call M("") then type inference still works out that T is string, and
// the generic method still needs to be discarded, even though type inference
// never saw the second formal parameter.
ImmutableArray<TypeSymbol> parameterTypes = leastOverriddenMember.GetParameterTypes();
for (int i = 0; i < parameterTypes.Length; i++)
{
if (!parameterTypes[i].CheckAllConstraints(Conversions))
{
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ConstructedParameterFailedConstraintsCheck(i));
}
}
// Types of constructed effective parameters might originate from a virtual/abstract method
// that the current "method" overrides. If the virtual/abstract method is generic we constructed it
// using the generic parameters of "method", so we can now substitute these type parameters
// in the constructed effective parameters.
var map = new TypeMap(method.TypeParameters, typeArguments, allowAlpha: true);
effectiveParameters = new EffectiveParameters(
map.SubstituteTypes(constructedEffectiveParameters.ParameterTypes),
constructedEffectiveParameters.ParameterRefKinds);
ignoreOpenTypes = false;
}
}
else
{
effectiveParameters = constructedEffectiveParameters;
ignoreOpenTypes = false;
}
return new MemberResolutionResult<TMember>(
member,
leastOverriddenMember,
IsApplicable(member, effectiveParameters, arguments, argsToParamsMap, member.GetIsVararg(), hasAnyRefOmittedArgument, ignoreOpenTypes, ref useSiteDiagnostics));
}
private ImmutableArray<TypeSymbol> InferMethodTypeArguments(
MethodSymbol method,
ImmutableArray<TypeParameterSymbol> originalTypeParameters,
AnalyzedArguments arguments,
EffectiveParameters originalEffectiveParameters,
out MemberAnalysisResult error,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
var argumentTypes = ArrayBuilder<TypeSymbol>.GetInstance();
for (int arg = 0; arg < arguments.Arguments.Count; arg++)
{
argumentTypes.Add(arguments.Argument(arg).Type);
}
var args = arguments.Arguments.ToImmutable();
// The reason why we pass the type parameters and formal parameter types
// from the original definition, not the method as it exists as a member of
// a possibly constructed generic type, is exceedingly subtle. See the comments
// in "Infer" for details.
var inferenceResult = MethodTypeInferrer.Infer(
_binder,
originalTypeParameters,
method.ContainingType,
originalEffectiveParameters.ParameterTypes,
originalEffectiveParameters.ParameterRefKinds,
argumentTypes.ToImmutableAndFree(),
args,
ref useSiteDiagnostics);
if (inferenceResult.Success)
{
error = default(MemberAnalysisResult);
return inferenceResult.InferredTypeArguments;
}
if (arguments.IsExtensionMethodInvocation)
{
var inferredFromFirstArgument = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument(_binder.Conversions, method, originalEffectiveParameters.ParameterTypes, args, ref useSiteDiagnostics);
if (inferredFromFirstArgument.IsDefault)
{
error = MemberAnalysisResult.TypeInferenceExtensionInstanceArgumentFailed();
return default(ImmutableArray<TypeSymbol>);
}
}
error = MemberAnalysisResult.TypeInferenceFailed();
return default(ImmutableArray<TypeSymbol>);
}
private MemberAnalysisResult IsApplicable(
Symbol candidate, // method or property
EffectiveParameters parameters,
AnalyzedArguments arguments,
ImmutableArray<int> argsToParameters,
bool isVararg,
bool hasAnyRefOmittedArgument,
bool ignoreOpenTypes,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// The effective parameters are in the right order with respect to the arguments.
//
// The difference between "parameters" and "original parameters" is as follows. Suppose
// we have class C<V> { static void M<T, U>(T t, U u, V v) { C<T>.M(1, t, t); } }
// In the call, the "original parameters" are (T, U, V). The "constructed parameters",
// not passed in here, are (T, U, T) because T is substituted for V; type inference then
// infers that T is int and U is T. The "parameters" are therefore (int, T, T).
//
// We add a "virtual parameter" for the __arglist.
int paramCount = parameters.ParameterTypes.Length + (isVararg ? 1 : 0);
Debug.Assert(paramCount == arguments.Arguments.Count);
// For each argument in A, the parameter passing mode of the argument (i.e., value, ref, or out) is
// identical to the parameter passing mode of the corresponding parameter, and
// * for a value parameter or a parameter array, an implicit conversion exists from the
// argument to the type of the corresponding parameter, or
// * for a ref or out parameter, the type of the argument is identical to the type of the corresponding
// parameter. After all, a ref or out parameter is an alias for the argument passed.
ArrayBuilder<Conversion> conversions = null;
ArrayBuilder<int> badArguments = null;
for (int argumentPosition = 0; argumentPosition < paramCount; argumentPosition++)
{
BoundExpression argument = arguments.Argument(argumentPosition);
RefKind argumentRefKind = arguments.RefKind(argumentPosition);
Conversion conversion;
if (isVararg && argumentPosition == paramCount - 1)
{
// Only an __arglist() expression is convertible.
if (argument.Kind == BoundKind.ArgListOperator)
{
conversion = Conversion.Identity;
}
else
{
badArguments = badArguments ?? ArrayBuilder<int>.GetInstance();
badArguments.Add(argumentPosition);
conversion = Conversion.NoConversion;
}
}
else
{
RefKind parameterRefKind = parameters.ParameterRefKinds.IsDefault ? RefKind.None : parameters.ParameterRefKinds[argumentPosition];
conversion = CheckArgumentForApplicability(candidate, argument, argumentRefKind, parameters.ParameterTypes[argumentPosition], parameterRefKind, ignoreOpenTypes, ref useSiteDiagnostics);
if (!conversion.Exists ||
(arguments.IsExtensionMethodThisArgument(argumentPosition) && !Conversions.IsValidExtensionMethodThisArgConversion(conversion)))
{
badArguments = badArguments ?? ArrayBuilder<int>.GetInstance();
badArguments.Add(argumentPosition);
}
}
if (conversions != null)
{
conversions.Add(conversion);
}
else if (!conversion.IsIdentity)
{
conversions = ArrayBuilder<Conversion>.GetInstance(paramCount);
conversions.AddMany(Conversion.Identity, argumentPosition);
conversions.Add(conversion);
}
}
MemberAnalysisResult result;
var conversionsArray = conversions != null ? conversions.ToImmutableAndFree() : default(ImmutableArray<Conversion>);
if (badArguments != null)
{
result = MemberAnalysisResult.BadArgumentConversions(argsToParameters, badArguments.ToImmutableAndFree(), conversionsArray);
}
else
{
result = MemberAnalysisResult.NormalForm(argsToParameters, conversionsArray, hasAnyRefOmittedArgument);
}
return result;
}
private Conversion CheckArgumentForApplicability(
Symbol candidate, // method or property
BoundExpression argument,
RefKind argRefKind,
TypeSymbol parameterType,
RefKind parRefKind,
bool ignoreOpenTypes,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
// Spec 7.5.3.1
// For each argument in A, the parameter passing mode of the argument (i.e., value, ref, or out) is identical
// to the parameter passing mode of the corresponding parameter, and
// - for a value parameter or a parameter array, an implicit conversion (§6.1)
// exists from the argument to the type of the corresponding parameter, or
// - for a ref or out parameter, the type of the argument is identical to the type of the corresponding parameter.
// RefKind has to match unless the ref kind is None and argument expression is of the type dynamic. This is a bug in Dev11 which we also implement.
// The spec is correct, this is not an intended behavior. We don't fix the bug to avoid a breaking change.
if (argRefKind != parRefKind && !(argRefKind == RefKind.None && argument.HasDynamicType()))
{
return Conversion.NoConversion;
}
// TODO (tomat): the spec wording isn't final yet
// Spec 7.5.4: Compile-time checking of dynamic overload resolution:
// - Then, any parameter whose type is open (i.e. contains a type parameter; see §4.4.2) is elided, along with its corresponding parameter(s).
// and
// - The modified parameter list for F is applicable to the modified argument list in terms of section §7.5.3.1
if (ignoreOpenTypes && parameterType.ContainsTypeParameter(parameterContainer: (MethodSymbol)candidate))
{
// defer applicability check to runtime:
return Conversion.ImplicitDynamic;
}
if (argRefKind == RefKind.None)
{
var conversion = Conversions.ClassifyImplicitConversionFromExpression(argument, parameterType, ref useSiteDiagnostics);
Debug.Assert((!conversion.Exists) || conversion.IsImplicit, "ClassifyImplicitConversion should only return implicit conversions");
return conversion;
}
var argType = argument.Type;
if ((object)argType != null && Conversions.HasIdentityConversion(argType, parameterType))
{
return Conversion.Identity;
}
else
{
return Conversion.NoConversion;
}
}
private static TMember GetConstructedFrom<TMember>(TMember member) where TMember : Symbol
{
switch (member.Kind)
{
case SymbolKind.Property:
return member;
case SymbolKind.Method:
return (TMember)(Symbol)(member as MethodSymbol).ConstructedFrom;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
}
| 48.309659 | 244 | 0.572435 | [
"Apache-2.0"
] | KashishArora/Roslyn | src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs | 136,065 | C# |
/* Copyright (c) <2014> <LeChosenOne, DingusBungus>
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.*/
//Todo: stats
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using fCraft.Events;
namespace fCraft
{
class CTF
{
//Team Tags
public const string redTeam = "&c-Red-";
public const string blueTeam = "&1*Blue*";
//CTF stats
public static int blueScore = 0;
public static int redScore = 0;
public static int redTeamCount = 0;
public static int blueTeamCount = 0;
//Timing
public static int timeLeft = 0;
private static SchedulerTask task_;
public static SchedulerTask delayTask;
public static CTF instance;
public static DateTime startTime;
public static DateTime lastChecked;
public static int timeLimit = 300;
public static int timeDelay = 20;
public static int totalTime = timeLimit + timeDelay;
public static int scoreCap = 5;
public static Stopwatch stopwatch = new Stopwatch();
public static DateTime announced = DateTime.MaxValue;
public static DateTime RedDisarmed = DateTime.MaxValue;
public static DateTime BlueDisarmed = DateTime.MaxValue;
public static DateTime RedBOFdebuff = DateTime.MaxValue;
public static DateTime BlueBOFdebuff = DateTime.MaxValue;
//Game Bools
public static bool isOn = false;
private static bool started = false;
public static string blueFlagHolder;
public static string redFlagHolder;
private static World world_;
public static CTF GetInstance(World world)
{
if (instance == null)
{
world_ = world;
instance = new CTF();
startTime = DateTime.UtcNow;
task_ = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromMilliseconds(250)); //run loop every quarter second
}
return instance;
}
public static void Start()
{
world_.Hax = false;
//world_.Players.Send(PacketWriter.MakeHackControl(0,0,0,0,0,-1)); Commented out until classicube clients support hax packet
stopwatch.Reset();
stopwatch.Start();
world_.gameMode = GameMode.CaptureTheFlag;
delayTask = Scheduler.NewTask(t => world_.Players.Message("&WCTF &fwill be starting in {0} seconds: &WGet ready!", (timeDelay - stopwatch.Elapsed.Seconds)));
delayTask.RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), (int)Math.Floor((double)(timeDelay / 10)));//Start task immediately, send message every 10s
if (stopwatch.Elapsed.Seconds > 11)
{
stopwatch.Stop();
}
}
public static void Stop(Player p) //for stopping the game early
{
//unhook moving event
Player.Moving -= PlayerMoving;
world_.Hax = true;
foreach (Player pl in world_.Players)
{
pl.JoinWorld(world_, WorldChangeReason.Rejoin);
}
if (p != null && world_ != null)
{
world_.Players.Message("{0}&S stopped the game of CTF early on world {1}", p.ClassyName, world_.ClassyName);
}
RevertGame();
if (!delayTask.IsStopped)//if stop is called when the delayTask is still going, stop the delayTask
{
delayTask.Stop();
}
return;
}
#region MainInterval
public static void Interval(SchedulerTask task)
{
//check to stop Interval
if (world_ == null)
{
task.Stop();
return;
}
if (world_.gameMode != GameMode.CaptureTheFlag)
{
task.Stop();
world_ = null;
return;
}
//remove announcements after 5 seconds
if (announced != DateTime.MaxValue && (DateTime.UtcNow - announced).TotalSeconds >= 5)
{
foreach (Player p in world_.Players)
{
if (p.SupportsMessageTypes)
{
p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&f"));//super hacky way to remove announcements, simply send a color code and call it a day
}
}
announced = DateTime.MaxValue;
}
//remove dodge after 1m
foreach (Player p in world_.Players)
{
if (p.Info.canDodge)
{
if (p.Info.dodgeTime != DateTime.MaxValue && (DateTime.UtcNow - p.Info.dodgeTime).TotalSeconds >= 60)
{
p.Info.canDodge = false;
p.Info.dodgeTime = DateTime.MaxValue;
world_.Players.Message(p.Name + " is no longer able to dodge.");
}
}
}
//remove strengthen after 1m
foreach (Player p in world_.Players)
{
if (p.Info.strengthened)
{
if (p.Info.strengthTime != DateTime.MaxValue && (DateTime.UtcNow - p.Info.strengthTime).TotalSeconds >= 60)
{
p.Info.strengthened = false;
p.Info.strengthTime = DateTime.MaxValue;
world_.Players.Message(p.Name + " is no longer dealing 2x damage.");
}
}
}
//remove Blades of Fury after 1m
if ((BlueBOFdebuff != DateTime.MaxValue && (DateTime.UtcNow - BlueBOFdebuff).TotalSeconds >= 60))
{
foreach (Player p in world_.Players)
{
if (p.Info.CTFBlueTeam)
{
p.Info.stabDisarmed = false;
}
else
{
p.Info.stabAnywhere = false;
}
}
BlueBOFdebuff = DateTime.MaxValue;
world_.Players.Message("Blades of Fury has ended.");
}
if ((RedBOFdebuff != DateTime.MaxValue && (DateTime.UtcNow - RedBOFdebuff).TotalSeconds >= 60))
{
foreach (Player p in world_.Players)
{
if (p.Info.CTFRedTeam)
{
p.Info.stabDisarmed = false;
}
else
{
p.Info.stabAnywhere = false;
}
}
RedBOFdebuff = DateTime.MaxValue;
world_.Players.Message("Blades of Fury has ended.");
}
//remove disarm after 30s
if ((RedDisarmed != DateTime.MaxValue && (DateTime.UtcNow - RedDisarmed).TotalSeconds >= 30))
{
foreach (Player p in world_.Players)
{
if (p.Info.CTFRedTeam)
{
p.GunMode = true;
p.Info.gunDisarmed = false;
}
}
RedDisarmed = DateTime.MaxValue;
world_.Players.Message("The Disarm Spell has ended.");
}
if ((BlueDisarmed != DateTime.MaxValue && (DateTime.UtcNow - BlueDisarmed).TotalSeconds >= 30))
{
foreach (Player p in world_.Players)
{
if (p.Info.CTFBlueTeam)
{
p.GunMode = true;
p.Info.gunDisarmed = false;
}
}
BlueDisarmed = DateTime.MaxValue;
world_.Players.Message("The Disarm Spell has ended.");
}
if (!started)
{
//create a player moving event
Player.Moving += PlayerMoving;
if (world_.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
{
world_.Players.Message("&WCTF&s requires at least 2 people to play.");
return;
}
//once timedelay is up, we start
if (startTime != null && (DateTime.UtcNow - startTime).TotalSeconds > timeDelay)
{
if (!world_.gunPhysics)
{
world_.EnableGunPhysics(Player.Console, true); //enables gun physics if they are not already on
}
foreach (Player p in world_.Players)
{
if (p.SupportsBlockPermissions)
{
//loop through each block ID
for (int i = 1; i < 65; i++)
{
//allow player to break glass block in order to shoot gun, disallow all other blocks except flags
if (i.Equals(20))
{
p.Send(PacketWriter.MakeSetBlockPermissions((byte)20, false, true));
}
else if (i.Equals(21))
{
p.Send(PacketWriter.MakeSetBlockPermissions((byte)21, false, true));
}
else if (i.Equals(29))
{
p.Send(PacketWriter.MakeSetBlockPermissions((byte)29, false, true));
}
else
{
p.Send(PacketWriter.MakeSetBlockPermissions((byte)i, false, false));
}
}
}
assignTeams(p);
if (p.Info.IsHidden) //unhides players automatically if hidden (cannot shoot guns while hidden)
{
p.Info.IsHidden = false;
Player.RaisePlayerHideChangedEvent(p);
}
if (p.Info.CTFRedTeam)
{
p.TeleportTo(world_.redCTFSpawn.ToPlayerCoords());
}
if (p.Info.CTFBlueTeam)
{
p.TeleportTo(world_.blueCTFSpawn.ToPlayerCoords());
}
p.GunMode = true;
GunGlassTimer timer = new GunGlassTimer(p);
timer.Start();
//send an announcement (Will be sent as a normal message to non classicube players)
p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&cLet the Games Begin!"));
if (p.SupportsMessageTypes)
{
//set player health
p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f[&a--------&f]"));
//set game score
p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&cRed&f: 0,&1 Blue&f: 0"));
}
}
//check that the flags haven't been misplaced during startup
if (world_.Map.GetBlock(world_.redFlag) != Block.Red)
{
world_.Map.QueueUpdate(new BlockUpdate(null, world_.redFlag, Block.Red));
}
if (world_.Map.GetBlock(world_.blueFlag) != Block.Blue)
{
world_.Map.QueueUpdate(new BlockUpdate(null, world_.blueFlag, Block.Blue));
}
started = true; //the game has officially started
isOn = true;
lastChecked = DateTime.UtcNow; //used for intervals
announced = DateTime.UtcNow;
return;
}
}
//update blue team and red team counts
redTeamCount =
(
from red in world_.Players
where red.Info.CTFRedTeam
select red
).Count();
blueTeamCount =
(
from blue in world_.Players
where blue.Info.CTFBlueTeam
select blue
).Count();
//Announce flag holder
if (String.IsNullOrEmpty(redFlagHolder))
{
foreach (Player p in world_.Players)
{
if (p.Info.hasRedFlag && redFlagHolder == null)
{
world_.Players.Message(p.Name + " has stolen the Red flag!");
redFlagHolder = p.Name;
}
}
}
//update flagholder
else
{
redFlagHolder = null;
foreach(Player p in world_.Players)
{
if (p.Info.hasRedFlag)
{
redFlagHolder = p.Name;
}
}
}
if (String.IsNullOrEmpty(blueFlagHolder))
{
foreach (Player p in world_.Players)
{
if (p.Info.hasBlueFlag && blueFlagHolder == null)
{
world_.Players.Message(p.Name + " has stolen the Blue flag!");
blueFlagHolder = p.Name;
}
}
}
//update flagholder
else
{
blueFlagHolder = null;
foreach (Player p in world_.Players)
{
if (p.Info.hasBlueFlag)
{
blueFlagHolder = p.Name;
}
}
}
//Check victory conditions
if (blueScore == 5)
{
world_.Players.Message("&fThe blue team has won {0} to {1}!", blueScore, redScore);
Stop(null);
return;
}
if (redScore == 5)
{
world_.Players.Message("&fThe red team has won {1} to {0}!", blueScore, redScore);
Stop(null);
return;
}
//if time is up
if (started && startTime != null && (DateTime.UtcNow - startTime).TotalSeconds >= (totalTime))
{
if (redScore > blueScore)
{
world_.Players.Message("&fThe &cRed&f Team won {0} to {1}!", redScore, blueScore);
Stop(null);
return;
}
if (redScore < blueScore)
{
world_.Players.Message("&fThe &1Blue&f Team won {0} to {1}!", blueScore, redScore);
Stop(null);
return;
}
if (redScore == blueScore)
{
world_.Players.Message("&fThe teams tied {0} to {0}!", blueScore);
Stop(null);
return;
}
if (world_.Players.Count() <= 1)
{
Stop(null);
return;
}
}
//Check for forfeits
if (started && (DateTime.UtcNow - lastChecked).TotalSeconds > 10)
{
if (blueTeamCount < 1 || redTeamCount < 1)
{
if (blueTeamCount == 0)
{
if (world_.Players.Count() >= 1)
{
world_.Players.Message("&1Blue Team &fhas forfeited the game. &cRed Team &fwins!");
}
Stop(null);
return;
}
if (redTeamCount == 0)
{
if (world_.Players.Count() >= 1)
{
world_.Players.Message("&cRed Team &fhas forfeited the game. &1Blue Team &fwins!");
}
Stop(null);
return;
}
//lol, everyone left
else
{
Stop(null);
return;
}
}
}
timeLeft = Convert.ToInt16(((timeDelay + timeLimit) - (DateTime.UtcNow - startTime).TotalSeconds));
//Keep the players updated about the score
if (lastChecked != null && (DateTime.UtcNow - lastChecked).TotalSeconds > 29.8 && timeLeft <= timeLimit)
{
if (redScore > blueScore)
{
world_.Players.Message("&fThe &cRed Team&f is winning {0} to {1}.", redScore, blueScore);
world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
}
if (redScore < blueScore)
{
world_.Players.Message("&fThe &1Blue Team&f is winning {0} to {1}.", blueScore, redScore);
world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
}
if (redScore == blueScore)
{
world_.Players.Message("&fThe teams are tied at {0}!", blueScore);
world_.Players.Message("&fThere are &W{0}&f seconds left in the game.", timeLeft);
}
lastChecked = DateTime.UtcNow;
}
if (timeLeft == 10)
{
world_.Players.Message("&WOnly 10 seconds left!");
}
}
#endregion
#region SeperateVoids
static public void assignTeams(Player p) //Assigns teams to all players in the world
{
//if there are no players assigned to any team yet
if (redTeamCount == 0) { AssignRed(p); return; }
//if the red team has more players and the red team has already been assigned at least one player
if (blueTeamCount < redTeamCount) { AssignBlue(p); return; }
//if the teams have the same number of players, by default the next player will be assigned to the red team
if (blueTeamCount == redTeamCount) { AssignRed(p); return; }
}
public static void RevertGame() //Reset game bools/stats and stop timers
{
task_.Stop();
world_.gameMode = GameMode.NULL;
isOn = false;
instance = null;
started = false;
if (world_.gunPhysics)
{
world_.DisableGunPhysics(Player.Console, true);
}
world_ = null;
redScore = 0;
blueScore = 0;
redTeamCount = 0;
blueTeamCount = 0;
RevertNames();
}
public static void RevertNames() //reverts names and vars for online players. offline players get reverted upon leaving the game
{
List<PlayerInfo> CTFPlayers = new List<PlayerInfo>(PlayerDB.PlayerInfoList.Where(r => (r.CTFBlueTeam || r.CTFRedTeam) && r.IsOnline).ToArray());
for (int i = 0; i < CTFPlayers.Count(); i++)
{
string p1 = CTFPlayers[i].Name.ToString();
PlayerInfo pI = PlayerDB.FindPlayerInfoExact(p1);
Player p = pI.PlayerObject;
if (p != null)
{
p.iName = null;
pI.tempDisplayedName = null;
pI.CTFBlueTeam = false;
pI.CTFRedTeam = false;
pI.isPlayingCTF = false;
pI.placingBlueFlag = false;
pI.placingRedFlag = false;
pI.hasRedFlag = false;
pI.hasBlueFlag = false;
pI.CTFCaptures = 0;
pI.CTFKills = 0;
p.entityChanged = true;
//reset all special messages
if (p.SupportsBlockPermissions) {
p.Send(PacketWriter.MakeSetBlockPermissions((byte)0, true, true));
}
if (p.SupportsMessageTypes) {
p.Send(PacketWriter.MakeSpecialMessage((byte)100, "&f"));
p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f"));
p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&f"));
}
//undo gunmode (taken from GunHandler.cs)
p.GunMode = false;
try
{
foreach (Vector3I block in p.GunCache.Values)
{
p.Send(PacketWriter.MakeSetBlock(block.X, block.Y, block.Z, p.WorldMap.GetBlock(block)));
Vector3I removed;
p.GunCache.TryRemove(block.ToString(), out removed);
}
if (p.bluePortal.Count > 0)
{
int j = 0;
foreach (Vector3I block in p.bluePortal)
{
if (p.WorldMap != null && p.World.IsLoaded)
{
p.WorldMap.QueueUpdate(new BlockUpdate(null, block, p.blueOld[j]));
j++;
}
}
p.blueOld.Clear();
p.bluePortal.Clear();
}
if (p.orangePortal.Count > 0)
{
int j = 0;
foreach (Vector3I block in p.orangePortal)
{
if (p.WorldMap != null && p.World.IsLoaded)
{
p.WorldMap.QueueUpdate(new BlockUpdate(null, block, p.orangeOld[j]));
j++;
}
}
p.orangeOld.Clear();
p.orangePortal.Clear();
}
}
catch (Exception ex)
{
Logger.Log(LogType.SeriousError, "" + ex);
}
if (p.IsOnline)
{
p.Message("&aYour status has been reverted.");
}
}
}
}
public static void AssignRed(Player p)
{
p.Message("You are on the &cRed Team");
p.iName = "TeamRed";
p.Info.tempDisplayedName = "&f(" + redTeam + "&f) " + Color.Red + p.Name;
p.Info.CTFRedTeam = true;
p.Info.CTFBlueTeam = false;
p.Info.isPlayingCTF = true;
p.entityChanged = true;
p.Info.CTFKills = 0;
redTeamCount++;
return;
}
public static void AssignBlue(Player p)
{
p.Message("You are on the &9Blue Team");
p.iName = "TeamBlue";
p.Info.tempDisplayedName = "&f(" + blueTeam + "&f) " + Color.Navy + p.Name;
p.Info.CTFBlueTeam = true;
p.Info.CTFRedTeam = false;
p.Info.isPlayingCTF = true;
p.entityChanged = true;
blueTeamCount++;
return;
}
#endregion
#region PowerUps
public static void PowerUp(Player p)
{
int GetPowerUp = (new Random()).Next(1, 4);
if (GetPowerUp < 3)
{
return;
}
int choosePowerUp = (new Random()).Next(1, 19);
//decide which powerup to use, certain powerups have a higher chance such as first aid kit and dodge as opposed to rarer ones like holy blessing
switch (choosePowerUp)
{
case 1:
case 2:
case 3:
//first aid kit - heal user for 50 hp
world_.Players.Message("&f{0} has discovered a &aFirst Aid Kit&f!", p.Name);
world_.Players.Message("&f{0} has been healed for 50 hp.", p.Name);
//set health to 100, make sure it doesn't overflow
p.Info.Health += 50;
if (p.Info.Health > 100)
{
p.Info.Health = 100;
}
string healthBar = "&f[&a--------&f]";
if (p.Info.Health == 75)
{
healthBar = "&f[&a------&8--&f]";
}
else if (p.Info.Health == 50)
{
healthBar = "&f[&e----&8----&f]";
}
else if (p.Info.Health == 25)
{
healthBar = "&f[&c--&8------&f]";
}
else
{
healthBar = "&f[&8--------&f]";
}
if (p.SupportsMessageTypes)
{
p.Send(PacketWriter.MakeSpecialMessage((byte)1, healthBar));
}
else
{
p.Message("You have " + p.Info.Health.ToString() + " health.");
}
break;
case 4:
case 5:
//penicillin - heal user for 100 hp
world_.Players.Message("&f{0} has discovered a &aPenicillin Case&f!", p.Name);
world_.Players.Message("&f{0} has been healed for 100 hp.", p.Name);
p.Info.Health = 100;
if (p.SupportsMessageTypes)
{
p.Send(PacketWriter.MakeSpecialMessage((byte)1, "&f[&8--------&f]"));
}
else
{
p.Message("You have " + p.Info.Health.ToString() + " health.");
}
break;
case 6:
case 7:
//disarm
world_.Players.Message("&f{0} has discovered a &aDisarm Spell&f!", p.Name);
if (p.Info.CTFBlueTeam)
{
world_.Players.Message("The red team has lost all weaponry for 30 seconds!");
foreach (Player pl in world_.Players)
{
if (pl.Info.CTFRedTeam)
{
pl.Info.gunDisarmed = true;
pl.Info.stabDisarmed = true;
pl.GunMode = false;
}
}
RedDisarmed = DateTime.UtcNow;
}
else
{
world_.Players.Message("The blue team has lost all weaponry for 30 seconds!");
foreach (Player pl in world_.Players)
{
if (pl.Info.CTFBlueTeam)
{
pl.Info.gunDisarmed = true;
pl.Info.stabDisarmed = true;
pl.GunMode = false;
}
}
BlueDisarmed = DateTime.UtcNow;
}
break;
case 8:
case 9:
//blades of fury
world_.Players.Message("&f{0} has discovered the &aBlades of Fury&f!", p.Name);
if (p.Info.CTFBlueTeam)
{
world_.Players.Message("The red team is unable to backstab for 1 minute!");
world_.Players.Message("The blue team can now stab the red team from any angle for 1 minute!");
foreach (Player pl in world_.Players)
{
if (pl.Info.CTFBlueTeam)
{
pl.Info.stabAnywhere = true;
}
else
{
pl.Info.stabDisarmed = true;
}
}
RedBOFdebuff = DateTime.UtcNow;
}
else
{
world_.Players.Message("The blue team is unable to backstab for 1 minute!");
world_.Players.Message("The red team can now stab the blue team from any angle for 1 minute!");
foreach (Player pl in world_.Players)
{
if (pl.Info.CTFRedTeam)
{
pl.Info.stabAnywhere = true;
}
else
{
pl.Info.stabDisarmed = true;
}
}
RedBOFdebuff = DateTime.UtcNow;
}
break;
case 10:
case 11:
//war cry
world_.Players.Message("&f{0} has discovered their &aWar Cry&f!", p.Name);
if (p.Info.CTFBlueTeam)
{
world_.Players.Message("The red team has been frightened back into their spawn!");
foreach (Player pl in world_.Players)
{
if (pl.Info.CTFRedTeam)
{
pl.TeleportTo(world_.redCTFSpawn.ToPlayerCoords());
}
}
}
else
{
world_.Players.Message("The blue team has been frightened back into their spawn!");
foreach (Player pl in world_.Players)
{
if (pl.Info.CTFBlueTeam)
{
pl.TeleportTo(world_.blueCTFSpawn.ToPlayerCoords());
}
}
}
break;
case 12:
case 13:
case 14:
//strengthen
world_.Players.Message("&f{0} has discovered a &aStrength Pack&f!", p.Name);
world_.Players.Message("&f{0}'s gun now deals twice the damage for the next minute!", p.Name);
p.Info.strengthened = true;
p.Info.strengthTime = DateTime.UtcNow;
break;
case 15:
case 16:
case 17:
//dodge
world_.Players.Message("&f{0} has discovered a new &aDodging Technique&f!", p.Name);
world_.Players.Message("&f{0}'s has a 50% chance to dodge incomming gun attacks for the next minute!", p.Name);
p.Info.canDodge = true;
p.Info.dodgeTime = DateTime.UtcNow;
break;
case 18:
//holy blessing (rarest and most treasured power up, yet easiest to code :P )
world_.Players.Message("&f{0} has discovered the rare &aHoly Blessing&f!!!", p.Name);
if (p.Info.CTFBlueTeam)
{
world_.Players.Message("The Blue Team has been granted 1 point.");
redScore++;
}
else
{
world_.Players.Message("The Red Team has been granted 1 point.");
blueScore++;
}
foreach (Player pl in world_.Players)
{
if (pl.SupportsMessageTypes)
{
pl.Send(PacketWriter.MakeSpecialMessage((byte)2, "&cRed&f: " + redScore + ",&1 Blue&f: " + blueScore));
}
else
{
pl.Message("The score is now &cRed&f: {0} and &1Blue&f: {1}.", redScore, blueScore);
}
}
break;
default:
//no power up 4 u
break;
}
}
#endregion
#region MovingEvent
public static void PlayerMoving(object poo, fCraft.Events.PlayerMovingEventArgs e)
{
if (!started)
{
return;
}
//If the player has the red flag (player is no the blue team)
if (e.Player.Info.hasRedFlag)
{
Vector3I oldPos = e.OldPosition.ToBlockCoords(); //get positions as block coords
Vector3I newPos = e.NewPosition.ToBlockCoords();
if (oldPos.X != newPos.X || oldPos.Y != newPos.Y || oldPos.Z != newPos.Z) //check if player has moved at least one block
{
//If the player is near enough to the blue spawn
if (e.NewPosition.DistanceSquaredTo(world_.blueCTFSpawn.ToPlayerCoords()) <= 42 * 42)
{
blueScore++;
world_.Players.Message("&f{0} has capped the &cred &fflag. The score is now &cRed&f: {1} and &1Blue&f: {2}.", e.Player.Name, redScore, blueScore);
e.Player.Info.hasRedFlag = false;
redFlagHolder = null;
e.Player.Info.CTFCaptures++;
//Replace red block as flag
BlockUpdate blockUpdate = new BlockUpdate(null, world_.redFlag, Block.Red);
foreach (Player p in world_.Players)
{
p.World.Map.QueueUpdate(blockUpdate);
//set game score
if (p.SupportsMessageTypes)
{
p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&cRed&f: " + redScore + ",&1 Blue&f: " + blueScore));
p.Send(PacketWriter.MakeSpecialMessage((byte)100, e.Player.Name + " has successfully capped the &cred &fflag"));
}
}
world_.redFlagTaken = false;
announced = DateTime.UtcNow;
return;
}
}
}
//If the player has the blue flag (player must be on red team)
else if (e.Player.Info.hasBlueFlag)
{
Vector3I oldPos = e.OldPosition.ToBlockCoords(); //get positions as block coords
Vector3I newPos = e.NewPosition.ToBlockCoords();
if (oldPos.X != newPos.X || oldPos.Y != newPos.Y || oldPos.Z != newPos.Z) //check if player has moved at least one block
{
//If the player is near enough to the red spawn
if (e.NewPosition.DistanceSquaredTo(world_.redCTFSpawn.ToPlayerCoords()) <= 42 * 42)
{
redScore++;
world_.Players.Message("&f{0} has capped the &1blue &fflag. The score is now &cRed&f: {1} and &1Blue&f: {2}.", e.Player.Name, redScore, blueScore);
e.Player.Info.hasBlueFlag = false;
blueFlagHolder = null;
e.Player.Info.CTFCaptures++;
//Replace blue block as flag
BlockUpdate blockUpdate = new BlockUpdate(null, world_.blueFlag, Block.Blue);
foreach (Player p in world_.Players)
{
p.World.Map.QueueUpdate(blockUpdate);
//set game scorecboard
if (p.SupportsMessageTypes)
{
p.Send(PacketWriter.MakeSpecialMessage((byte)2, "&cRed&f: " + redScore + ",&1 Blue&f: " + blueScore));
p.Send(PacketWriter.MakeSpecialMessage((byte)100, e.Player.Name + " has successfully capped the &cred &fflag"));
}
}
world_.blueFlagTaken = false;
announced = DateTime.UtcNow;
return;
}
}
}
//backstabbing, player with a flag cannot backstab an enemy player
else
{
if (e.Player.Info.stabDisarmed)
{
return;
}
Vector3I oldPos = e.OldPosition.ToBlockCoords(); //get positions as block coords
Vector3I newPos = e.NewPosition.ToBlockCoords();
if (oldPos.X != newPos.X || oldPos.Y != newPos.Y || oldPos.Z != newPos.Z) //check if player has moved at least one block
{
//loop through each player, detect if current player is "touching" another player
foreach (Player p in world_.Players)
{
Vector3I pos = p.Position.ToBlockCoords(); //convert to block coords
//determine if player is "touching" another player
if (e.NewPosition.DistanceSquaredTo(pos.ToPlayerCoords()) <= 42 * 42 && p != e.Player)
{
if ((p.Info.CTFBlueTeam && e.Player.Info.CTFBlueTeam) || (p.Info.CTFRedTeam && e.Player.Info.CTFRedTeam))
{
//friendly fire, do not stab
return;
}
//create just under a 180 degree semicircle in the direction the target player is facing (90 degrees = 64 pos.R bytes)
short lowerLimit = (short)(p.Position.R - 63);
short upperLimit = (short)(p.Position.R + 63);
//if lower limit is -45 degrees for example, convert to 256 + (-32) = 201 bytes (-45 degrees translates to -32 bytes)
if (lowerLimit < 0)
{
lowerLimit = (short)(256 + lowerLimit);
}
//if upper limit is 450 degrees for example, convert to 320 - 256 = 54 bytes (450 degrees translates to 320 bytes, 360 degrees translates to 256 bytes)
if (upperLimit > 256)
{
upperLimit = (short)(upperLimit - 256);
}
//Logger.LogToConsole(upperLimit.ToString() + " " + lowerLimit.ToString() + " " + e.Player.Position.R.ToString() + " " + p.Position.R);
bool kill = false;
//if target's line of sight contains 0
if (p.Position.R > 192 && p.Position.R < 64)
{
if (Enumerable.Range(lowerLimit, 255).Contains(e.Player.Position.R) || Enumerable.Range(0, upperLimit).Contains(e.Player.Position.R))
{
kill = true;
}
}
else
{
if (Enumerable.Range(lowerLimit, upperLimit).Contains(e.Player.Position.R))
{
kill = true;
}
}
if (e.Player.Info.stabAnywhere)
{
kill = true;
}
if (kill)
{
p.KillCTF(world_, String.Format("&f{0}&S was backstabbed by &f{1}", p.Name, e.Player.Name));
e.Player.Info.CTFKills++;
PowerUp(e.Player);
if (p.Info.hasRedFlag)
{
world_.Players.Message("The red flag has been returned.");
p.Info.hasRedFlag = false;
redFlagHolder = null;
//Put flag back
BlockUpdate blockUpdate = new BlockUpdate(null, world_.redFlag, Block.Red);
foreach (Player pl in world_.Players)
{
pl.World.Map.QueueUpdate(blockUpdate);
}
world_.redFlagTaken = false;
}
if (p.Info.hasBlueFlag)
{
world_.Players.Message("The blue flag has been returned.");
p.Info.hasBlueFlag = false;
blueFlagHolder = null;
//Put flag back
BlockUpdate blockUpdate = new BlockUpdate(null, world_.blueFlag, Block.Blue);
foreach (Player pl in world_.Players)
{
pl.World.Map.QueueUpdate(blockUpdate);
}
world_.blueFlagTaken = false;
}
}
//target player can see player, do not stab
}
}
}
}
}
#endregion
}
}
| 41.638554 | 179 | 0.421741 | [
"MIT"
] | CybertronicToon/LegendCraft | fCraft/Games/CTF.cs | 44,930 | C# |
using System;
using SLua;
using System.Collections.Generic;
[UnityEngine.Scripting.Preserve]
public class Lua_UnityEngine_UI_MaskUtilities : LuaObject {
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int constructor(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.UI.MaskUtilities o;
o=new UnityEngine.UI.MaskUtilities();
pushValue(l,true);
pushValue(l,o);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int Notify2DMaskStateChanged_s(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Component a1;
checkType(l,1,out a1);
UnityEngine.UI.MaskUtilities.Notify2DMaskStateChanged(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int NotifyStencilStateChanged_s(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Component a1;
checkType(l,1,out a1);
UnityEngine.UI.MaskUtilities.NotifyStencilStateChanged(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int FindRootSortOverrideCanvas_s(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Transform a1;
checkType(l,1,out a1);
var ret=UnityEngine.UI.MaskUtilities.FindRootSortOverrideCanvas(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GetStencilDepth_s(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Transform a1;
checkType(l,1,out a1);
UnityEngine.Transform a2;
checkType(l,2,out a2);
var ret=UnityEngine.UI.MaskUtilities.GetStencilDepth(a1,a2);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int IsDescendantOrSelf_s(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.Transform a1;
checkType(l,1,out a1);
UnityEngine.Transform a2;
checkType(l,2,out a2);
var ret=UnityEngine.UI.MaskUtilities.IsDescendantOrSelf(a1,a2);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GetRectMaskForClippable_s(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.UI.IClippable a1;
checkType(l,1,out a1);
var ret=UnityEngine.UI.MaskUtilities.GetRectMaskForClippable(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GetRectMasksForClip_s(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
UnityEngine.UI.RectMask2D a1;
checkType(l,1,out a1);
System.Collections.Generic.List<UnityEngine.UI.RectMask2D> a2;
checkType(l,2,out a2);
UnityEngine.UI.MaskUtilities.GetRectMasksForClip(a1,a2);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[UnityEngine.Scripting.Preserve]
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.UI.MaskUtilities");
addMember(l,Notify2DMaskStateChanged_s);
addMember(l,NotifyStencilStateChanged_s);
addMember(l,FindRootSortOverrideCanvas_s);
addMember(l,GetStencilDepth_s);
addMember(l,IsDescendantOrSelf_s);
addMember(l,GetRectMaskForClippable_s);
addMember(l,GetRectMasksForClip_s);
createTypeMetatable(l,constructor, typeof(UnityEngine.UI.MaskUtilities));
}
}
| 25.529825 | 75 | 0.726636 | [
"BSD-3-Clause"
] | HugoFang/LuaProfiler | SLua/Assets/Slua/LuaObject/Unity/Lua_UnityEngine_UI_MaskUtilities.cs | 7,278 | C# |
namespace Tweetinvi.Core.Public.Models.Enum
{
/// <summary>
/// List of known media categories. This list might not be complete.
/// Use the string mediaCategory parameter if you need to use another one.
/// </summary>
public enum MediaCategory
{
// Tweet media categories
Image,
Gif,
Video,
// DM media categories
DmImage,
DmGif,
DmVideo,
}
}
| 21.9 | 78 | 0.579909 | [
"MIT"
] | 247GradLabs/tweetinvi | Tweetinvi.Core/Public/Models/Enum/MediaCategory.cs | 440 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Core22.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Core22.Areas.Identity.Pages.Account.Manage
{
public class DownloadPersonalDataModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<DownloadPersonalDataModel> _logger;
public DownloadPersonalDataModel(
UserManager<ApplicationUser> userManager,
ILogger<DownloadPersonalDataModel> logger)
{
_userManager = userManager;
_logger = logger;
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
_logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));
// Only include personal data for download
var personalData = new Dictionary<string, string>();
var personalDataProps = typeof(ApplicationUser).GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
foreach (var p in personalDataProps)
{
personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
}
Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");
return new FileContentResult(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(personalData)), "text/json");
}
}
}
| 38 | 124 | 0.642206 | [
"MIT"
] | lhendinha/ASP.Net-Core-2.2 | Core22/Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml.cs | 1,978 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.FSx")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.6.4")] | 46.15625 | 221 | 0.750846 | [
"Apache-2.0"
] | jamieromanowski/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/FSx/Properties/AssemblyInfo.cs | 1,477 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Localisation;
using osu.Game.Localisation;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.Changelog
{
public class ChangelogHeader : BreadcrumbControlOverlayHeader
{
public readonly Bindable<APIChangelogBuild> Build = new Bindable<APIChangelogBuild>();
public Action ListingSelected;
public ChangelogUpdateStreamControl Streams;
public static LocalisableString ListingString => LayoutStrings.HeaderChangelogIndex;
private readonly Bindable<APIUpdateStream> currentStream = new Bindable<APIUpdateStream>();
private Box streamsBackground;
public ChangelogHeader()
{
TabControl.AddItem(ListingString);
Current.ValueChanged += e =>
{
if (e.NewValue == ListingString)
ListingSelected?.Invoke();
};
Build.ValueChanged += showBuild;
currentStream.ValueChanged += e =>
{
if (e.NewValue?.LatestBuild != null && !e.NewValue.Equals(Build.Value?.UpdateStream))
Build.Value = e.NewValue.LatestBuild;
};
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
streamsBackground.Colour = colourProvider.Background5;
}
private void showBuild(ValueChangedEvent<APIChangelogBuild> e)
{
if (e.OldValue != null)
TabControl.RemoveItem(e.OldValue.ToString());
if (e.NewValue != null)
{
TabControl.AddItem(e.NewValue.ToString());
Current.Value = e.NewValue.ToString();
updateCurrentStream();
}
else
{
Current.Value = ListingString;
currentStream.Value = null;
}
}
protected override Drawable CreateBackground() => new OverlayHeaderBackground(@"Headers/changelog");
protected override Drawable CreateContent() => new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
streamsBackground = new Box
{
RelativeSizeAxes = Axes.Both
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding
{
Horizontal = 65,
Vertical = 20
},
Child = Streams = new ChangelogUpdateStreamControl { Current = currentStream },
}
}
};
protected override OverlayTitle CreateTitle() => new ChangelogHeaderTitle();
public void Populate(List<APIUpdateStream> streams)
{
Streams.Populate(streams);
updateCurrentStream();
}
private void updateCurrentStream()
{
if (Build.Value == null)
return;
currentStream.Value = Streams.Items.FirstOrDefault(s => s.Name == Build.Value.UpdateStream.Name);
}
private class ChangelogHeaderTitle : OverlayTitle
{
public ChangelogHeaderTitle()
{
Title = PageTitleStrings.MainChangelogControllerDefault;
Description = NamedOverlayComponentStrings.ChangelogDescription;
IconTexture = "Icons/Hexacons/devtools";
}
}
}
}
| 32.821705 | 110 | 0.559282 | [
"MIT"
] | 20PercentRendered/osu | osu.Game/Overlays/Changelog/ChangelogHeader.cs | 4,108 | C# |
using Mirror;
using Mirror.Tests.Runtime;
using NUnit.Framework;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TestTools;
namespace JamesFrowen.PositionSync.Tests.Runtime
{
[Category("NetworkPositionSync")]
public class NetworkTransformSnapshotInterpolationTest : HostSetup
{
readonly List<GameObject> spawned = new List<GameObject>();
private SyncPositionBehaviour serverNT;
private SyncPositionBehaviour clientNT;
protected override bool AutoAddPlayer => false;
protected override void afterStartHost()
{
var serverGO = new GameObject("server object");
var clientGO = new GameObject("client object");
this.spawned.Add(serverGO);
this.spawned.Add(clientGO);
var serverNI = serverGO.AddComponent<NetworkIdentity>();
var clientNI = clientGO.AddComponent<NetworkIdentity>();
this.serverNT = serverGO.AddComponent<SyncPositionBehaviour>();
this.clientNT = clientGO.AddComponent<SyncPositionBehaviour>();
// set up Identitys so that server object can send message to client object in host mode
FakeSpawnServerClientIdentity(serverNI, clientNI);
// reset both transforms
serverGO.transform.position = Vector3.zero;
clientGO.transform.position = Vector3.zero;
}
protected override void beforeStopHost()
{
foreach (var obj in this.spawned)
{
Object.Destroy(obj);
}
}
[UnityTest]
public IEnumerator SyncPositionFromServerToClient()
{
var positions = new Vector3[] {
new Vector3(1, 2, 3),
new Vector3(2, 2, 3),
new Vector3(2, 3, 5),
new Vector3(2, 3, 5),
};
foreach (var position in positions)
{
this.serverNT.transform.position = position;
// wait more than needed to check end position is reached
yield return new WaitForSeconds(0.5f);
Assert.That(this.clientNT.transform.position, Is.EqualTo(position));
}
}
}
}
| 32.295775 | 100 | 0.607937 | [
"MIT"
] | James-Frowen/MirrorPositionSync | tests/runtime/NetworkTransformSnapshotInterpolationTest.cs | 2,293 | C# |
using Domain.Common;
namespace Domain.Entities
{
public class EmailToken : Entity
{
public string UserId { get; set; }
public string Token { get; set; }
public User User { get; set; }
}
}
| 14.375 | 42 | 0.582609 | [
"MIT"
] | BinaryStudioAcademy/bsa-2021-scout | backend/src/Domain/Entities/EmailToken.cs | 232 | C# |
using Amazon.Lambda.Core;
using System;
namespace <%=ProjectName%>
{
public class <%=Prefix%>Response
{
public string Message {get; set;}
public <%=Prefix%>Request Request {get; set;}
public <%=Prefix%>Response(string message, <%=Prefix%>Request request){
Message = message;
Request = request;
}
}
}
| 18.736842 | 77 | 0.603933 | [
"MIT"
] | msolimans/generator-sls | generators/rdotnet/templates/Response.cs | 356 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BrawlCrate.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.3.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UpdateSettings {
get {
return ((bool)(this["UpdateSettings"]));
}
set {
this["UpdateSettings"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool ShowFullPath {
get {
return ((bool)(this["ShowFullPath"]));
}
set {
this["ShowFullPath"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.Specialized.StringCollection RecentFiles {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["RecentFiles"]));
}
set {
this["RecentFiles"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("10")]
public int RecentFilesMax {
get {
return ((int)(this["RecentFilesMax"]));
}
set {
this["RecentFilesMax"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool DisplayPropertyDescriptionWhenAvailable {
get {
return ((bool)(this["DisplayPropertyDescriptionWhenAvailable"]));
}
set {
this["DisplayPropertyDescriptionWhenAvailable"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool ShowHex {
get {
return ((bool)(this["ShowHex"]));
}
set {
this["ShowHex"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::BrawlLib.Internal.ModelEditorSettings ViewerSettings {
get {
return ((global::BrawlLib.Internal.ModelEditorSettings)(this["ViewerSettings"]));
}
set {
this["ViewerSettings"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool ViewerSettingsSet {
get {
return ((bool)(this["ViewerSettingsSet"]));
}
set {
this["ViewerSettingsSet"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool PixelLighting {
get {
return ((bool)(this["PixelLighting"]));
}
set {
this["PixelLighting"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool APIEnabled {
get {
return ((bool)(this["APIEnabled"]));
}
set {
this["APIEnabled"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string PythonInstallationPath {
get {
return ((string)(this["PythonInstallationPath"]));
}
set {
this["PythonInstallationPath"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string FSharpInstallationPath {
get {
return ((string)(this["FSharpInstallationPath"]));
}
set {
this["FSharpInstallationPath"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool CheckUpdatesAtStartup {
get {
return ((bool)(this["CheckUpdatesAtStartup"]));
}
set {
this["CheckUpdatesAtStartup"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool GetDocumentationUpdates {
get {
return ((bool)(this["GetDocumentationUpdates"]));
}
set {
this["GetDocumentationUpdates"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UpdateAutomatically {
get {
return ((bool)(this["UpdateAutomatically"]));
}
set {
this["UpdateAutomatically"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool DiscordRPCEnabled {
get {
return ((bool)(this["DiscordRPCEnabled"]));
}
set {
this["DiscordRPCEnabled"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Nullable<BrawlCrate.Discord.DiscordSettings.ModNameType> DiscordRPCNameType {
get {
return ((global::System.Nullable<BrawlCrate.Discord.DiscordSettings.ModNameType>)(this["DiscordRPCNameType"]));
}
set {
this["DiscordRPCNameType"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("My Mod")]
public string DiscordRPCNameCustom {
get {
return ((string)(this["DiscordRPCNameCustom"]));
}
set {
this["DiscordRPCNameCustom"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool PreviewBRRESModels {
get {
return ((bool)(this["PreviewBRRESModels"]));
}
set {
this["PreviewBRRESModels"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool PreviewARCModels {
get {
return ((bool)(this["PreviewARCModels"]));
}
set {
this["PreviewARCModels"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string BuildPath {
get {
return ((string)(this["BuildPath"]));
}
set {
this["BuildPath"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.Specialized.StringCollection APILoadersBlacklist {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["APILoadersBlacklist"]));
}
set {
this["APILoadersBlacklist"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.Collections.Specialized.StringCollection APILoadersWhitelist {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["APILoadersWhitelist"]));
}
set {
this["APILoadersWhitelist"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool APIOnlyAllowLoadersFromWhitelist {
get {
return ((bool)(this["APIOnlyAllowLoadersFromWhitelist"]));
}
set {
this["APIOnlyAllowLoadersFromWhitelist"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool APIAutoUpdate {
get {
return ((bool)(this["APIAutoUpdate"]));
}
set {
this["APIAutoUpdate"] = value;
}
}
}
}
| 38.531056 | 151 | 0.570323 | [
"MIT"
] | GamendeMier/BrawlCrate | BrawlCrate/Properties/Settings.Designer.cs | 12,409 | 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 kafkaconnect-2021-09-14.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.KafkaConnect.Model
{
/// <summary>
/// This is the response object from the DescribeCustomPlugin operation.
/// </summary>
public partial class DescribeCustomPluginResponse : AmazonWebServiceResponse
{
private DateTime? _creationTime;
private string _customPluginArn;
private CustomPluginState _customPluginState;
private string _description;
private CustomPluginRevisionSummary _latestRevision;
private string _name;
/// <summary>
/// Gets and sets the property CreationTime.
/// <para>
/// The time that the custom plugin was created.
/// </para>
/// </summary>
public DateTime CreationTime
{
get { return this._creationTime.GetValueOrDefault(); }
set { this._creationTime = value; }
}
// Check to see if CreationTime property is set
internal bool IsSetCreationTime()
{
return this._creationTime.HasValue;
}
/// <summary>
/// Gets and sets the property CustomPluginArn.
/// <para>
/// The Amazon Resource Name (ARN) of the custom plugin.
/// </para>
/// </summary>
public string CustomPluginArn
{
get { return this._customPluginArn; }
set { this._customPluginArn = value; }
}
// Check to see if CustomPluginArn property is set
internal bool IsSetCustomPluginArn()
{
return this._customPluginArn != null;
}
/// <summary>
/// Gets and sets the property CustomPluginState.
/// <para>
/// The state of the custom plugin.
/// </para>
/// </summary>
public CustomPluginState CustomPluginState
{
get { return this._customPluginState; }
set { this._customPluginState = value; }
}
// Check to see if CustomPluginState property is set
internal bool IsSetCustomPluginState()
{
return this._customPluginState != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the custom plugin.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property LatestRevision.
/// <para>
/// The latest successfully created revision of the custom plugin. If there are no successfully
/// created revisions, this field will be absent.
/// </para>
/// </summary>
public CustomPluginRevisionSummary LatestRevision
{
get { return this._latestRevision; }
set { this._latestRevision = value; }
}
// Check to see if LatestRevision property is set
internal bool IsSetLatestRevision()
{
return this._latestRevision != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the custom plugin.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
}
} | 30.137255 | 110 | 0.586424 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/KafkaConnect/Generated/Model/DescribeCustomPluginResponse.cs | 4,611 | C# |
using System;
using System.Linq;
namespace Mandater.Utilities
{
/// <summary>
/// Enum representing the available methods of seat calculation for political systems given a voting district/circuit.
/// </summary>
public enum Algorithm
{
/// <summary>
/// Algorithm not defined
/// </summary>
Undefined = 0,
/// <summary>
/// The Modified Sainte-Lagüe method in accordance with the Norwegian system. TODO: More accurate description of Modified Sainte-Lagüe
/// </summary>
ModifiedSainteLagues,
/// <summary>
/// Normal Sainte-Lagüe method TODO: More accurate description of Sainte-Lagüe
/// </summary>
SainteLagues,
/// <summary>
/// D'Hondt method TODO: More accurate description of D'Hondt
/// </summary>
DHondt
}
/// <summary>
/// Utility class to make operations surrounding the Algorithm enum more practical
/// </summary>
public static class AlgorithmUtilities
{
// Our internal textual representations of the algorithm names
private const string modifiedSainteLagues = "Sainte Laguës (modified)";
private const string sainteLagues = "Sainte Laguës";
private const string dHondt = "d'Hondt";
// Our accepted names for the different algorithms
private static readonly string[] ModifiedSainteLaguesSet = {modifiedSainteLagues.ToLower()};
private static readonly string[] SainteLaguesSet = {sainteLagues.ToLower()};
private static readonly string[] DHondtSet = {dHondt.ToLower()};
/// <summary>
/// Accepts a string and returns the matching algorithm enum.
/// If no matching enum can be found it throws an ArgumentException.
/// </summary>
/// <param name="name">The name of the algorithm to be converted.</param>
/// <returns>An algorithm enum</returns>
private static Algorithm StringToAlgorithm(string name)
{
string curName = name.ToLower();
if (ModifiedSainteLaguesSet.Contains(curName))
{
return Algorithm.ModifiedSainteLagues;
}
if (SainteLaguesSet.Contains(curName))
{
return Algorithm.SainteLagues;
}
if (DHondtSet.Contains(curName))
{
return Algorithm.DHondt;
}
throw new ArgumentException($"{name} is not a valid algorithm name.");
}
/// <summary>
/// Accepts an algorithm enum and returns our internal textual representation of that algorithm.
/// If there is not any known textual representation of it an ArgumentException is thrown.
/// </summary>
/// <param name="algorithm">The Algorithm enum to be converted.</param>
/// <returns>The name of the algorithm enum</returns>
public static string AlgorithmToString(Algorithm algorithm)
{
switch (algorithm)
{
case Algorithm.ModifiedSainteLagues:
return modifiedSainteLagues;
case Algorithm.SainteLagues:
return sainteLagues;
case Algorithm.DHondt:
return dHondt;
default:
throw new ArgumentException($"{algorithm} does not have a string name.");
}
}
/// <summary>
/// Checks whether the name matches any algorithm we know.
/// </summary>
/// <param name="name">The name of the algorithm.</param>
/// <returns>True if we have an enum for the algorithm, false otherwise.</returns>
private static bool IsAlgorithm(string name)
{
string curName = name.ToLower();
return ModifiedSainteLaguesSet.Contains(curName)
|| SainteLaguesSet.Contains(curName)
|| DHondtSet.Contains(curName);
}
/// <summary>
/// Attempts to convert the name to an algorithm.
/// If it is successful it returns true and pushes the Algorithm to the algorithm variable.
/// Otherwise it returns false and pushes Algorithm.Undefined to the algorithm variable.
/// </summary>
/// <param name="name">The name of the algorithm.</param>
/// <param name="algorithm">Where the algorithm should be returned.</param>
/// <returns>True if successful, false otherwise.</returns>
public static bool TryParse(string name, out Algorithm algorithm)
{
if (IsAlgorithm(name))
{
algorithm = StringToAlgorithm(name);
return true;
}
algorithm = Algorithm.Undefined;
return false;
}
}
}
| 38.547619 | 142 | 0.592753 | [
"Apache-2.0"
] | Log234/Mandater | Mandater/Utilities/AlgorithmUtilities.cs | 4,865 | C# |
using HttpReports.Core;
using HttpReports.Core.Config;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
namespace HttpReports
{
internal abstract class BaseRequestInfoBuilder : IRequestInfoBuilder
{
protected HttpReportsOptions Options { get; }
protected IModelCreator ModelCreator { get; }
public BaseRequestInfoBuilder(IModelCreator modelCreator, IOptions<HttpReportsOptions> options)
{
Options = options.Value;
ModelCreator = modelCreator;
}
protected abstract (IRequestInfo, IRequestDetail) Build(HttpContext context, IRequestInfo request, string path);
public (IRequestInfo, IRequestDetail) Build(HttpContext context, Stopwatch stopwatch)
{
var path = (context.Request.Path.Value ?? string.Empty).ToLowerInvariant();
if (IsFilterRequest(context)) return (null, null);
// Build RequestInfo
Uri uri = new Uri(Options.Urls);
var request = ModelCreator.CreateRequestInfo();
var remoteIP = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
request.IP = remoteIP.IsEmpty() ? context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString() : remoteIP;
request.Port = context.Connection.RemotePort;
request.LocalIP = uri.Host;
request.LocalPort = uri.Port;
request.StatusCode = context.Response.StatusCode;
request.Method = context.Request.Method;
request.Url = context.Request.Path;
request.RequestType = (context.Request.ContentType ?? string.Empty).Contains("grpc") ? "grpc" : "http";
request.Milliseconds = ToInt32(stopwatch.ElapsedMilliseconds);
request.CreateTime = context.Items[BasicConfig.ActiveTraceCreateTime].ToDateTime();
path = path.Replace(@"///", @"/").Replace(@"//", @"/");
var (requestInfo, requestDetail ) = Build(context, request, path);
return (ParseRequestInfo(requestInfo), ParseRequestDetail(requestDetail));
}
private IRequestInfo ParseRequestInfo(IRequestInfo request)
{
if (request.Node == null) request.Node = string.Empty;
if (request.Route == null) request.Route = string.Empty;
if (request.Url == null) request.Url = string.Empty;
if (request.Method == null) request.Method = string.Empty;
if (request.IP == null) request.IP = string.Empty;
return request;
}
private IRequestDetail ParseRequestDetail(IRequestDetail request)
{
if (request.Scheme == null) request.Scheme = string.Empty;
if (request.QueryString == null) request.QueryString = string.Empty;
if (request.Header == null) request.Header = string.Empty;
if (request.Cookie == null) request.Cookie = string.Empty;
if (request.RequestBody == null) request.RequestBody = string.Empty;
if (request.ResponseBody == null) request.ResponseBody = string.Empty;
if (request.ErrorMessage == null) request.ErrorMessage = string.Empty;
if (request.ErrorStack == null) request.ErrorStack = string.Empty;
int max = BasicConfig.HttpReportsFieldMaxLength;
if (request.QueryString.Length > max)
{
request.QueryString = request.QueryString.Substring(0, max);
}
if (request.Header.Length > max)
{
request.Header = request.Header.Substring(0, max);
}
if (request.Cookie.Length > max)
{
request.Cookie = request.Cookie.Substring(0, max);
}
if (request.RequestBody.Length > max)
{
request.RequestBody = request.RequestBody.Substring(0, max);
}
if (request.ResponseBody.Length > max)
{
request.ResponseBody = request.ResponseBody.Substring(0, max);
}
if (request.ErrorMessage.Length > max)
{
request.ErrorMessage = request.ErrorMessage.Substring(0, max);
}
if (request.ErrorStack.Length > max)
{
request.ErrorStack = request.ErrorStack.Substring(0, max);
}
return request;
}
private bool IsFilterRequest(HttpContext context)
{
bool result = false;
if (!context.Request.ContentType.IsEmpty() && context.Request.ContentType.Contains("application/grpc"))
return false;
if (context.Request.Method.ToLowerInvariant() == "options")
return true;
if (!Options.FilterStaticFile)
return false;
var path = (context.Request.Path.Value ?? string.Empty).ToLowerInvariant();
if (path.Contains("."))
{
var fileType = path.Split('.').Last();
if (fileType != "html" && fileType != "aspx")
return true;
}
return result;
}
protected static int ToInt32(long value)
{
if (value < int.MinValue || value > int.MaxValue)
{
return -1;
}
return (int)value == 0 ? 1 : (int)value;
}
protected static bool IsNumber(string str)
{
return int.TryParse(str, out _);
}
}
} | 35.575 | 120 | 0.583099 | [
"MIT"
] | XXXXX34/HttpReports | src/HttpReports/RequestInfoBuilder/BaseRequestInfoBuilder.cs | 5,694 | 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.Network
{
using AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using MNM = Microsoft.Azure.Management.Network.Models;
using System;
using System.Collections;
using System.Management.Automation;
using System.Net;
using System.Collections.Generic;
public class VpnGatewayBaseCmdlet : NetworkBaseCmdlet
{
public IVpnGatewaysOperations VpnGatewayClient
{
get
{
return NetworkClient.NetworkManagementClient.VpnGateways;
}
}
public PSVpnGateway ToPsVpnGateway(Management.Network.Models.VpnGateway vpnGateway)
{
var pSVpnGateway = NetworkResourceManagerProfile.Mapper.Map<PSVpnGateway>(vpnGateway);
pSVpnGateway.Tag = TagsConversionHelper.CreateTagHashtable(vpnGateway.Tags);
return pSVpnGateway;
}
public PSVpnGateway GetVpnGateway(string resourceGroupName, string name)
{
var vpnGateway = this.VpnGatewayClient.Get(resourceGroupName, name);
var psVpnGateway = this.ToPsVpnGateway(vpnGateway);
psVpnGateway.ResourceGroupName = resourceGroupName;
return psVpnGateway;
}
public List<PSVpnGateway> ListVpnGateways(string resourceGroupName)
{
var vpnGateways = ShouldListBySubscription(resourceGroupName, null) ?
this.VpnGatewayClient.List() : //// List by sub id
this.VpnGatewayClient.ListByResourceGroup(resourceGroupName); //// List by RG name
List<PSVpnGateway> gatewaysToReturn = new List<PSVpnGateway>();
if (vpnGateways != null)
{
foreach (MNM.VpnGateway gateway in vpnGateways)
{
PSVpnGateway gatewayToReturn = ToPsVpnGateway(gateway);
gatewayToReturn.ResourceGroupName = resourceGroupName;
gatewaysToReturn.Add(gatewayToReturn);
}
}
return gatewaysToReturn;
}
public PSVpnGateway CreateOrUpdateVpnGateway(string resourceGroupName, string vpnGatewayName, PSVpnGateway vpnGateway, Hashtable tags)
{
var vpnGatewayModel = NetworkResourceManagerProfile.Mapper.Map<MNM.VpnGateway>(vpnGateway);
vpnGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(tags, validate: true);
var vpnGatewayCreatedOrUpdated = this.VpnGatewayClient.CreateOrUpdate(resourceGroupName, vpnGatewayName, vpnGatewayModel);
PSVpnGateway gatewayToReturn = this.ToPsVpnGateway(vpnGatewayCreatedOrUpdated);
gatewayToReturn.ResourceGroupName = resourceGroupName;
return gatewayToReturn;
}
public bool IsVpnGatewayPresent(string resourceGroupName, string name)
{
try
{
GetVpnGateway(resourceGroupName, name);
}
catch (Microsoft.Azure.Management.Network.Models.ErrorException exception)
{
if (exception.Response.StatusCode == HttpStatusCode.NotFound)
{
// Resource is not present
return false;
}
}
return true;
}
}
}
| 41.245283 | 143 | 0.606359 | [
"MIT"
] | AzPsTest/azure-powershell | src/Network/Network/Cortex/VpnGateway/VpnGatewayBaseCmdlet.cs | 4,269 | C# |
using GerberLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GerberClipper
{
class GerberClipper: IProgressLog
{
static void Main(string[] args)
{
if (args.Count() < 3)
{
Console.WriteLine("Usage: GerberClipper.exe <outlinegerber> <subject> <outputfile>");
return;
}
string outline = args[0];
string infile = args[1];
string outputfile = args[2];
GerberImageCreator GIC = new GerberImageCreator();
GIC.AddBoardsToSet(new List<string>() { outline, infile }, true, new GerberClipper());
GIC.ClipBoard(infile, outputfile, new GerberClipper());
}
public void AddString(string text, float progress = -1F)
{
Console.WriteLine("{0}", text);
}
}
}
| 26.222222 | 101 | 0.576271 | [
"MIT"
] | ghent360/GerberTools | GerberClipper/GerberClipper.cs | 946 | C# |
using System;
using System.Linq;
namespace Hotel_Reservation
{
class StartUp
{
static void Main(string[] args)
{
var items = Console.ReadLine()
.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
var pricePerDay = decimal.Parse(items[0]);
var numberOfDays = int.Parse(items[1]);
var season = (Season)Enum.Parse(typeof(Season), items[2]);
var discountType = DiscountType.None;
if (items.Length == 4)
{
discountType = (DiscountType)Enum.Parse(typeof(DiscountType), items[3]);
}
PriceCalculator calculator = new PriceCalculator(pricePerDay, numberOfDays, season, discountType);
Console.WriteLine($"{calculator.CalculatePrice():F2}");
}
}
} | 30.928571 | 110 | 0.569284 | [
"MIT"
] | markodjunev/Softuni | C#/C# OOP/Working with Abstraction - Lab/Hotel Reservation/StartUp.cs | 868 | C# |
using System.Collections;
using UnityEngine;
public class WelcomeHandler : MonoBehaviour {
public GameObject bootScreen;
public GameObject lockScreen;
public GameObject userScreen;
public GameObject welcomeScreen;
public GameObject blankImage;
void Start ()
{
bootScreen.SetActive (true);
lockScreen.SetActive (true);
userScreen.SetActive (true);
blankImage.SetActive (false);
welcomeScreen.SetActive (false);
}
}
| 20.809524 | 45 | 0.773455 | [
"MIT"
] | RobsonMaciel/glassos | Scripts/UI/WelcomeHandler.cs | 439 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
namespace AltiFinReact.Web
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling=PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
}
| 33.7 | 152 | 0.751731 | [
"MIT"
] | brunoAltinet/ReactAspNetCrudExample | AltiFinReact.Web/Global.asax.cs | 1,013 | C# |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 NUnit.Framework;
using Sensus.Shared.Android.Concurrent;
using Sensus.Shared.Tests.Concurrent;
namespace Sensus.Android.Tests.Concurrent
{
[TestFixture]
public class MainConcurrentTests : IConcurrentTests
{
public MainConcurrentTests() : base(new MainConcurrent(1000))
{
}
}
} | 33.448276 | 75 | 0.721649 | [
"Apache-2.0"
] | w-bonelli/sensus | Sensus.Android.Tests/Tests/Concurrent/MainConcurrentTests.cs | 972 | C# |
using Lucene.Net.QueryParsers.Flexible.Core.Messages;
using Lucene.Net.QueryParsers.Flexible.Core.Parser;
using Lucene.Net.QueryParsers.Flexible.Messages;
namespace Lucene.Net.QueryParsers.Flexible.Core.Nodes
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Query node for <see cref="Search.PhraseQuery"/>'s slop factor.
/// </summary>
public class PhraseSlopQueryNode : QueryNode, IFieldableNode
{
private int value = 0;
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="value"></param>
/// <exception cref="QueryNodeError">throw in overridden method to disallow</exception>
public PhraseSlopQueryNode(IQueryNode query, int value)
{
if (query == null)
{
throw new QueryNodeError(new Message(
QueryParserMessages.NODE_ACTION_NOT_SUPPORTED, "query", "null"));
}
this.value = value;
IsLeaf = false;
Allocate();
Add(query);
}
public virtual IQueryNode GetChild()
{
return GetChildren()[0];
}
public virtual int Value
{
get { return this.value; }
}
private string GetValueString()
{
float f = this.value;
if (f == (long)f)
return "" + (long)f;
else
return "" + f;
}
public override string ToString()
{
return "<phraseslop value='" + GetValueString() + "'>" + "\n"
+ GetChild().ToString() + "\n</phraseslop>";
}
public override string ToQueryString(IEscapeQuerySyntax escapeSyntaxParser)
{
if (GetChild() == null)
return "";
return GetChild().ToQueryString(escapeSyntaxParser) + "~"
+ GetValueString();
}
public override IQueryNode CloneTree()
{
PhraseSlopQueryNode clone = (PhraseSlopQueryNode)base.CloneTree();
clone.value = this.value;
return clone;
}
public virtual string Field
{
get
{
IQueryNode child = GetChild();
if (child is IFieldableNode)
{
return ((IFieldableNode)child).Field;
}
return null;
}
set
{
IQueryNode child = GetChild();
if (child is IFieldableNode)
{
((IFieldableNode)child).Field = value;
}
}
}
}
}
| 31.228814 | 96 | 0.524016 | [
"Apache-2.0"
] | NikolayXHD/Lucene.Net.Contrib | Lucene.Net.QueryParser/Flexible/Core/Nodes/PhraseSlopQueryNode.cs | 3,687 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Common
{
public class GeoLocation
{
public Coordinate Latitude { get; set; }
public Coordinate Longtitude { get; set; }
}
}
| 16.571429 | 50 | 0.663793 | [
"MIT"
] | sagulati/dotnet-lambda-refarch-imagerecognition | lambda-functions/Common/GeoLocation.cs | 234 | C# |
using Edibles;
using System;
using System.Collections.Generic;
using System.Linq;
using UniRx.Toolkit;
using UnityEngine;
using UniRx;
namespace Edibles
{
public class HumanPool : ObjectPool<Human>
{
public bool isInitialized { get; private set; }
private Human prefab;
private Transform parent;
private Action<Human> callback;
private Dictionary<Human, Action<Edible>> wrappers = new Dictionary<Human, Action<Edible>>();
public HumanPool(Human prefab, Transform parent)
{
this.prefab = prefab;
this.parent = parent;
}
protected override Human CreateInstance()
{
var instance = UnityEngine.Object.Instantiate(prefab, parent);
instance.transform.SetAsLastSibling();
return instance;
}
}
}
| 22.90625 | 95 | 0.739427 | [
"MIT"
] | Deadcreep/Snake | Assets/Scripts/Edibles/HumanPool.cs | 735 | 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 worklink-2018-09-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.WorkLink.Model
{
/// <summary>
/// Container for the parameters to the AssociateDomain operation.
/// Specifies a domain to be associated to Amazon WorkLink.
/// </summary>
public partial class AssociateDomainRequest : AmazonWorkLinkRequest
{
private string _acmCertificateArn;
private string _displayName;
private string _domainName;
private string _fleetArn;
/// <summary>
/// Gets and sets the property AcmCertificateArn.
/// <para>
/// The ARN of an issued ACM certificate that is valid for the domain being associated.
///
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string AcmCertificateArn
{
get { return this._acmCertificateArn; }
set { this._acmCertificateArn = value; }
}
// Check to see if AcmCertificateArn property is set
internal bool IsSetAcmCertificateArn()
{
return this._acmCertificateArn != null;
}
/// <summary>
/// Gets and sets the property DisplayName.
/// <para>
/// The name to display.
/// </para>
/// </summary>
[AWSProperty(Max=100)]
public string DisplayName
{
get { return this._displayName; }
set { this._displayName = value; }
}
// Check to see if DisplayName property is set
internal bool IsSetDisplayName()
{
return this._displayName != null;
}
/// <summary>
/// Gets and sets the property DomainName.
/// <para>
/// The fully qualified domain name (FQDN).
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=64)]
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
/// <summary>
/// Gets and sets the property FleetArn.
/// <para>
/// The Amazon Resource Name (ARN) of the fleet.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=20, Max=2048)]
public string FleetArn
{
get { return this._fleetArn; }
set { this._fleetArn = value; }
}
// Check to see if FleetArn property is set
internal bool IsSetFleetArn()
{
return this._fleetArn != null;
}
}
} | 29.815126 | 106 | 0.590192 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/WorkLink/Generated/Model/AssociateDomainRequest.cs | 3,548 | C# |
using UnityEngine;
using System.Collections;
namespace SpaceImpact {
public class SICPowerup : SICGamePowerup {
// Public Variables
// Private Variables
// Static Variables
# region Game Powerup
public override PowerupType GetPowerupType() {
return PowerupType.BALL;
}
# endregion
}
} | 16.368421 | 48 | 0.723473 | [
"MIT"
] | pixelsquare/SpaceImpactClone | Assets/Scripts/Elements/Powerup/SICPowerup.cs | 313 | C# |
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;
using System.Text;
// Copyright 2019 J Forristal LLC
// Copyright 2016 Addition Security Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
public class MobileAwareness {
//
// Return values of the various SDK APIs
//
public const int AS_INIT_ERR_MORE_THAN_ONCE = 1;
public const int AS_INIT_SUCCESS = 0;
public const int AS_INIT_ERR_GENERAL = -1;
public const int AS_INIT_ERR_LICENSE = -2;
public const int AS_INIT_ERR_INTEGRITY = -3;
public const int AS_INIT_ERR_ARMONX86 = -4;
public const int AS_SUCCESS = 0;
public const int AS_ERR_GENERAL = -1;
//
// Initialization result callback; check for any of the AS_INIT_* return codes and respond accordingly
//
private static void inititializeResult(int result)
{
if( result != AS_INIT_SUCCESS)
{
// SOMETHING BAD HAPPENED! The library couldn't initialize properly
//
// Include failure handling here
// ... Your logic ...
Debug.Log("ERROR INITIALIZING MOBILEAWARENESS SDK");
}
}
//
// Event callback -- customize this to respond to the various security events generated by the SDK
//
[AOT.MonoPInvokeCallback(typeof(EventCallbackFunc))]
private static void eventCallback(int id, int subid, IntPtr data1Ptr, UInt32 data1_len, IntPtr data2Ptr, UInt32 data2_len)
{
// The callback must not propogate any exceptions back to the SDK, so wrap everything with a try/catch block
try
{
//
// Enable this code if you wish to access/review the data parameters in your response logic:
#if false
byte[] data1 = null;
if (data1Ptr != IntPtr.Zero)
{
// NOTE: data1_len could be zero
data1 = new byte[data1_len];
if (data1_len > 0)
Marshal.Copy(data1Ptr, data1, 0, (int)(data1_len & 0xfffff));
}
byte[] data2 = null;
if (data2Ptr != IntPtr.Zero)
{
// NOTE: data2_len could be zero
data2 = new byte[data2_len];
if (data2_len > 0)
Marshal.Copy(data2Ptr, data2, 0, (int)(data2_len & 0xfffff));
}
#endif
// FOR DEBUGGING ONLY:
Debug.Log("Event Callback: " + id.ToString() + "/" + subid.ToString());
//
// Malware on the device
//
if( id == 150 // 150: Known Malware Artifact Detected
|| id == 152 // 152: Known Malware Signer Present
)
{
// ... Your response ...
Debug.Log("SECURITY: MALWARE");
}
//
// Application vulnerabilities
//
if( id == 252 // 252: Open Application Local Attack Vector
|| id == 253 // 253: Open Application Remote Attack Vector
)
{
// ... Your response ...
Debug.Log("SECURITY: APP VULNERABILITY");
}
if( id == 300 // 300: Synthetic System (Emulator/Simulator)
)
{
// ... Your response ...
Debug.Log("SECURITY: EMULATOR");
}
if( id == 302 // 302: Non-Production System
|| id == 317 // 317: System Unsigned (Android)
)
{
// WARNING: unfortunately there are Android vendors that ship devices that don't
// meet Google's requirements for production, e.g. debug builds, signed with test
// keys, etc. These are effectively development builds that got sent to market,
// and are indistinguishable from development builds that a hacker may make to
// try to compromise an app. Most users don't know they purchased an at-risk
// development grade device/firmware build, and are in no position to really
// remedy it except for buy a new device. Therefore, you should consider using
// thes category of indicators passively if you do not want to snag a few
// innocent users who unfortunately bought sketchy devices.
// ... Your response ...
Debug.Log("SECURITY: NONPRODUCTION DEVICE");
}
if( id == 305 // 305: Privilege Providing Application (SU, etc.)
|| id == 314 // 314: System Rooted/Jailbroken
)
{
// ... Your response ...
Debug.Log("SECURITY: ROOTED/JAILBROKEN");
}
if( id == 307 // 307: Hacking Tool Installed
|| id == 308 // 308: Security Subversion Tool Installed (rooting/jailbreak exploit)
|| id == 315 // 315: Security Hiding Tool Installed (trying to hide root/jailbreak)
)
{
// ... Your response ...
Debug.Log("SECURITY: SECURITY TOOL/EXPLOIT");
}
if( id == 309 // 309: Application Tampering Tool Installed
|| id == 310 // 310: Game Cheat Tool Installed
|| id == 311 // 311: In-App Purchasing Fraud Tool Installed
)
{
// ... Your response ...
Debug.Log("SECURITY: CHEAT/FRAUD TOOL");
}
if( id == 312 // 312: Test/Automation Tool Installed
|| id == 318 // 318: ADBD Running (Android Developer Bridge)
)
{
// ... Your response ...
Debug.Log("SECURITY: DEVELOPMENT/TEST ITEMS");
}
if( id == 313 // 313: Security Expectation Failure (sandbox security is broken)
|| id == 411 // 411: Security Operation Failure (system security call failed)
)
{
// ... Your response ...
Debug.Log("SECURITY: RUNTIME OPERATION VIOLATION");
}
if( id == 400 // 400: Debugger/Instrumentation Detected
)
{
// ... Your response ...
Debug.Log("SECURITY: DEBUGGER DETECTED");
}
if( id == 401 // 401: Application Tampering Detected
|| id == 403 // 403: Application Encryption Disabled (IOS: app-store app got cracked)
|| id == 406 // 406: Stealth Callback Failure (Advanced MobileAwareness feature)
|| id == 410 // 410: Provisiong Corrupted (unable to read embedded provisioning profile)
|| id == 416 // 416: Heartbeat failure (re: heartbeat() API call)
)
{
// ... Your response ...
Debug.Log("SECURITY: RUNTIME APP VIOLATION");
}
if( id == 402 // 402: Application Unencrypted (IOS non-app-store install)
|| id == 409 // 409: Provisioning Missing (sideloaded or not from known app store)
|| id == 413 // 412: Application is Developer Signed
|| id == 414 // 414: Debug Build (app is a debug/developer build)
)
{
// ... Your response ...
// NOTE: these are typically seen in development/pre-production installs, but shouldn't
// occur on production installs going through app stores
Debug.Log("SECURITY: VIOLATION IF NOT DEVELOPMENT BUILD");
}
if( id == 500 // 500: SSL Pin Violation (network MitM attacker detected)
)
{
// ... Your response ...
Debug.Log("SECURITY: NETWORK ATTACKER");
}
if( id == 415 ) // 415: Provisioning Provider
{
// This message indicates provisioning info.
// IOS: the information comes from the embedded provisioning profile
// Android: it contains the package name of the installer, e.g. com.android.vending for Google Play
//
// You can test the values against expectations to see if your application is coming from unauthorized
// stores or getting distributed via ad-hoc means
// Android:
// data1: string of package name of installer; may be NULL if sideloaded
// ... Your logic ...
}
if( id == 408 ) // 408: Provisioning Signer
{
// This message includes the SHA1 hash of the provisioning profile signer.
//
// You can test the values against expectations to see if your application is redistributed.
// IOS:
// data1: SHA1 hash byte array (binary, 20 bytes) of certificate in provisioning profile
// data2: (optional) text string of the certificate X509 subject
// ... Your logic ...
}
if( id == 404 ) // 404: Application Signer
{
// This message includes the SHA1 hash of the application signer.
//
// You can test the values against expectations to see if your application is resigned.
//
// Android:
// data1: SHA1 hash byte array (binary, 20 bytes) of certificate used to sign APK
// data2: (optional) text string of the certificate X509 subject
//
// IOS:
// data1: SHA1 hash byte array (binary, 20 bytes) of certificate used to sign the executable
// NOTE: this may reflect an Apple signature, if re-signed for App Store distribution
// data2: (optional) text string of the certificate X509 subject
// ... Your logic ...
}
if( id == 407 ) // 407: Application Measurement
{
// This message includes the SHA1 hash of the application bundle.
//
// You can test the values against expectations to see if your application has been modified.
if (subid == 10)
{
// Android: This is SHA1 hash of the APK file
// data1: SHA1 hash byte array (binary, 20 bytes) of certificate used to sign APK
// data2: string of the file name/path on device
// ... Your logic ...
}
if( subid == 1 )
{
// IOS: THis is the SHA1 hash of the executable file
// data1: SHA1 hash byte array (binary, 20 bytes) of certificate used to sign APK
// data2: string of the file name/path on device
// ... Your logic ...
}
}
}
catch
{
// Your choice on how to handle errors, as long as they don't propogate back into the SDK
// ...
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// No need to edit anything below here (for basic operation)
//
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void EventCallbackFunc(int id, int subid, IntPtr data1Ptr, UInt32 data1_len, IntPtr data2Ptr, UInt32 data2_len);
//
// Main SDK initialization. Must be called once, and as early as possible (e.g. startup object)
// Callback must be ready to receive calls.
//
private static bool _initialized = false;
public static void initialize()
{
if (_initialized)
{
inititializeResult(AS_INIT_ERR_MORE_THAN_ONCE);
return;
}
#if UNITY_IOS || UNITY_ANDROID
// Load the as.conf configuration & license file from resources
TextAsset ta = Resources.Load("asconf", typeof(TextAsset)) as TextAsset;
byte[] asconf = ta.bytes;
// Load the as.def definitions file from resources
#if UNITY_IOS
ta = Resources.Load("asdef_i", typeof(TextAsset)) as TextAsset;
#else
ta = Resources.Load("asdef_a", typeof(TextAsset)) as TextAsset;
#endif
byte[] asdef = ta.bytes;
// result will be sent to the callback
EventCallbackFunc cb = eventCallback;
initialize_platform(asconf, asdef, cb);
#else
// In order to keep existing logic (namely, the callback) preserved, we are going to
// "fake" the InitializationComplete message here before we return success
_initialized = true;
eventCallback(50,0,IntPtr.Zero,0,IntPtr.Zero,0);
inititializeResult(AS_INIT_SUCCESS);
#endif
}
//
// Associate an authenticated identity with the message stream, for remote correllation
//
public static int registerIdentity(string identity)
{
if (!_initialized) return AS_ERR_GENERAL;
#if UNITY_IOS || UNITY_ANDROID
int len = Encoding.UTF8.GetByteCount(identity);
byte[] buffer = new byte[len + 1]; // +1 for NULL
Encoding.UTF8.GetBytes(identity, 0, identity.Length, buffer, 0);
GCHandle pinned = GCHandle.Alloc(buffer, GCHandleType.Pinned);
int res = AS_Register_Identity(pinned.AddrOfPinnedObject());
pinned.Free();
return res;
#else
return AS_SUCCESS;
#endif
}
//
// Send an arbitrary message to the remote message receiver
//
public static int sendMessage(UInt32 id, string data)
{
if (!_initialized) return AS_ERR_GENERAL;
#if UNITY_IOS || UNITY_ANDROID
int len = Encoding.UTF8.GetByteCount(data);
byte[] buffer = new byte[len + 1]; // +1 for NULL
Encoding.UTF8.GetBytes(data, 0, data.Length, buffer, 0);
GCHandle pinned = GCHandle.Alloc(buffer, GCHandleType.Pinned);
int res = AS_Send_Message(id, pinned.AddrOfPinnedObject());
pinned.Free();
return res;
#else
return AS_SUCCESS;
#endif
}
//
// Let the SDK & remote receiver know of a successful login
//
public static void loginSuccess()
{
if (!_initialized) return;
#if UNITY_IOS || UNITY_ANDROID
AS_Login_Status(1);
#endif
}
//
// Let the SDK & remote receiver know of a failed login
//
public static void loginFailed()
{
if (!_initialized) return;
#if UNITY_IOS || UNITY_ANDROID
AS_Login_Status(0);
#endif
}
//
// Call upon a change of network conditions, to check the network and
// flush any pending messages to the remote receiver
//
public static void networkReachability()
{
if (!_initialized) return;
#if UNITY_IOS || UNITY_ANDROID
AS_Network_Reachability();
#endif
}
//
// Report the MobileAwareness library version
//
public static UInt32 version()
{
#if UNITY_IOS || UNITY_ANDROID
return AS_Version();
#else
return 0;
#endif
}
public static long heartbeat(long input)
{
if (!_initialized) return -1;
#if UNITY_IOS || UNITY_ANDROID
return AS_Heartbeat(input);
#else
// THIS NEEDS TO MATCH YOUR HEARTBEAT VALUE PER YOUR AS.CONF
return 1234;
#endif
}
#if UNITY_IOS
[DllImport("__Internal")]
private static extern int AS_MobileAwareness_Unity_Init_Bridge( IntPtr config, UInt32 config_len,
IntPtr defs, UInt32 defs_len, EventCallbackFunc cb );
[DllImport("__Internal")]
private static extern int AS_Register_Identity(IntPtr identity);
[DllImport("__Internal")]
private static extern int AS_Send_Message(UInt32 id, IntPtr data);
[DllImport("__Internal")]
private static extern long AS_Heartbeat(long input);
[DllImport("__Internal")]
private static extern void AS_Login_Status(int status);
[DllImport("__Internal")]
private static extern void AS_Network_Reachability();
[DllImport("__Internal")]
private static extern UInt32 AS_Version();
private static void initialize_platform(byte[] asconf, byte[] asdef, EventCallbackFunc cb)
{
GCHandle pinned_asconf = GCHandle.Alloc(asconf, GCHandleType.Pinned);
GCHandle pinned_asdef = GCHandle.Alloc(asdef, GCHandleType.Pinned);
int res_init = AS_MobileAwareness_Unity_Init_Bridge(pinned_asconf.AddrOfPinnedObject(), (UInt32)asconf.Length,
pinned_asdef.AddrOfPinnedObject(), (UInt32)asdef.Length, cb );
pinned_asconf.Free();
pinned_asdef.Free();
if( res_init == AS_INIT_SUCCESS ) _initialized = true;
inititializeResult(res_init);
}
#elif UNITY_ANDROID
[DllImport("asma")]
private static extern int AS_Initialize_Unity(IntPtr config, UInt32 config_len,
IntPtr defs, UInt32 defs_len, EventCallbackFunc cb);
[DllImport("asma")]
private static extern int AS_Register_Identity(IntPtr identity);
[DllImport("asma")]
private static extern int AS_Send_Message(UInt32 id, IntPtr data);
[DllImport("asma")]
private static extern long AS_Heartbeat(long input);
[DllImport("asma")]
private static extern void AS_Login_Status(int status);
[DllImport("asma")]
private static extern void AS_Network_Reachability();
[DllImport("asma")]
private static extern UInt32 AS_Version();
private static void initialize_platform(byte[] asconf, byte[] asdef, EventCallbackFunc cb)
{
//
// The initialize must happen on the main UI thread to get the proper JNIEnv
// reference under the hood.
//
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
activity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
{
// We need to load the MobileAwareness SDK class, because it has some
// static initializing logic that is used for various Java-side detections
AndroidJavaClass cl = new AndroidJavaClass("com.additionsecurity.MobileAwareness");
// Pin the asconf byte array and pass it in as a pointer to the Initialize function
GCHandle pinned_asconf = GCHandle.Alloc(asconf, GCHandleType.Pinned);
GCHandle pinned_asdef = GCHandle.Alloc(asdef, GCHandleType.Pinned);
int res_init = AS_Initialize_Unity(pinned_asconf.AddrOfPinnedObject(), (UInt32)asconf.Length,
pinned_asdef.AddrOfPinnedObject(), (UInt32)asdef.Length, cb);
pinned_asconf.Free();
pinned_asdef.Free();
if( res_init == AS_INIT_SUCCESS ) _initialized = true;
inititializeResult(res_init);
}));
}
#endif
}
| 37.577491 | 133 | 0.555506 | [
"Apache-2.0"
] | additionsec/as_mobileawareness | targets/unity/MobileAwareness.cs | 20,369 | 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.Diagnostics.CodeAnalysis;
using Microsoft.Azure.Devices.Client.Extensions;
namespace Microsoft.Azure.Devices.Client
{
/// <summary>
/// Authentication method that uses the symmetric key associated with the device in the device registry.
/// </summary>
public sealed class DeviceAuthenticationWithRegistrySymmetricKey : IAuthenticationMethod
{
private string _deviceId;
private byte[] _key;
/// <summary>
/// Initializes a new instance of the <see cref="DeviceAuthenticationWithRegistrySymmetricKey"/> class.
/// </summary>
/// <param name="deviceId">Device identifier.</param>
/// <param name="key">Symmetric key associated with the device.</param>
public DeviceAuthenticationWithRegistrySymmetricKey(string deviceId, string key)
{
SetDeviceId(deviceId);
SetKeyFromBase64String(key);
}
/// <summary>
/// Gets or sets the device identifier.
/// </summary>
public string DeviceId
{
get => _deviceId;
set => SetDeviceId(value);
}
/// <summary>
/// Gets or sets the key associated with the device.
/// </summary>
[SuppressMessage(
"Performance",
"CA1819:Properties should not return arrays",
Justification = "Cannot change property types on public classes.")]
public byte[] Key
{
get => _key;
set => SetKey(value);
}
/// <summary>
/// Gets or sets the Base64 formatted key associated with the device.
/// </summary>
public string KeyAsBase64String
{
get => Convert.ToBase64String(Key);
set => SetKeyFromBase64String(value);
}
/// <summary>
/// Populates an <see cref="IotHubConnectionStringBuilder"/> instance based on the properties of the current instance.
/// </summary>
/// <param name="iotHubConnectionStringBuilder">Instance to populate.</param>
/// <returns>The populated <see cref="IotHubConnectionStringBuilder"/> instance.</returns>
public IotHubConnectionStringBuilder Populate(IotHubConnectionStringBuilder iotHubConnectionStringBuilder)
{
if (iotHubConnectionStringBuilder == null)
{
throw new ArgumentNullException(nameof(iotHubConnectionStringBuilder));
}
iotHubConnectionStringBuilder.DeviceId = DeviceId;
iotHubConnectionStringBuilder.SharedAccessKey = KeyAsBase64String;
iotHubConnectionStringBuilder.SharedAccessKeyName = null;
iotHubConnectionStringBuilder.SharedAccessSignature = null;
return iotHubConnectionStringBuilder;
}
private void SetKey(byte[] key)
{
_key = key ?? throw new ArgumentNullException(nameof(key));
}
private void SetKeyFromBase64String(string key)
{
if (key.IsNullOrWhiteSpace())
{
throw new ArgumentNullException(nameof(key));
}
if (!StringValidationHelper.IsBase64String(key))
{
throw new ArgumentException("Key must be base64 encoded");
}
_key = Convert.FromBase64String(key);
}
private void SetDeviceId(string deviceId)
{
if (deviceId.IsNullOrWhiteSpace())
{
throw new ArgumentNullException(nameof(deviceId));
}
_deviceId = deviceId;
}
}
}
| 34.279279 | 126 | 0.60841 | [
"MIT"
] | Azure/azure-iot-sdk-csharp | iothub/device/src/DeviceAuthenticationWithRegistrySymmetricKey.cs | 3,807 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. 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 System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class NamedTypeGenerator
{
public static TypeDeclarationSyntax AddNamedTypeTo(
ICodeGenerationService service,
TypeDeclarationSyntax destination,
INamedTypeSymbol namedType,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), options);
var members = Insert(destination.Members, declaration, options, availableIndices);
return AddMembersTo(destination, members);
}
public static NamespaceDeclarationSyntax AddNamedTypeTo(
ICodeGenerationService service,
NamespaceDeclarationSyntax destination,
INamedTypeSymbol namedType,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.Namespace, options);
var members = Insert(destination.Members, declaration, options, availableIndices);
return ConditionallyAddFormattingAnnotationTo(
destination.WithMembers(members),
members);
}
public static CompilationUnitSyntax AddNamedTypeTo(
ICodeGenerationService service,
CompilationUnitSyntax destination,
INamedTypeSymbol namedType,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, options);
var members = Insert(destination.Members, declaration, options, availableIndices);
return destination.WithMembers(members);
}
public static MemberDeclarationSyntax GenerateNamedTypeDeclaration(
ICodeGenerationService service,
INamedTypeSymbol namedType,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
options = options ?? CodeGenerationOptions.Default;
var declaration = GetDeclarationSyntaxWithoutMembers(namedType, destination, options);
// If we are generating members then make sure to exclude properties that cannot be generated.
// Reason: Calling AddProperty on a propertysymbol that can't be generated (like one with params) causes
// the getter and setter to get generated instead. Since the list of members is going to include
// the method symbols for the getter and setter, we don't want to generate them twice.
declaration = options.GenerateMembers && namedType.TypeKind != TypeKind.Delegate
? service.AddMembers(declaration,
GetMembers(namedType).Where(s => s.Kind != SymbolKind.Property || PropertyGenerator.CanBeGenerated((IPropertySymbol)s)),
options)
: declaration;
return AddCleanupAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options));
}
public static MemberDeclarationSyntax UpdateNamedTypeDeclaration(
ICodeGenerationService service,
MemberDeclarationSyntax declaration,
IList<ISymbol> newMembers,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
declaration = RemoveAllMembers(declaration);
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken);
return AddCleanupAnnotationsTo(declaration);
}
private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembers(
INamedTypeSymbol namedType,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(namedType, options);
if (reusableDeclarationSyntax == null)
{
return GenerateNamedTypeDeclarationWorker(namedType, destination, options);
}
return RemoveAllMembers(reusableDeclarationSyntax);
}
private static MemberDeclarationSyntax RemoveAllMembers(MemberDeclarationSyntax declaration)
{
switch (declaration.CSharpKind())
{
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)declaration).WithMembers(default(SeparatedSyntaxList<EnumMemberDeclarationSyntax>));
case SyntaxKind.StructDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.ClassDeclaration:
return ((TypeDeclarationSyntax)declaration).WithMembers(default(SyntaxList<MemberDeclarationSyntax>));
default:
return declaration;
}
}
private static MemberDeclarationSyntax GenerateNamedTypeDeclarationWorker(
INamedTypeSymbol namedType,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
if (namedType.TypeKind == TypeKind.Enum)
{
return GenerateEnumDeclaration(namedType, destination, options);
}
else if (namedType.TypeKind == TypeKind.Delegate)
{
return GenerateDelegateDeclaration(namedType, destination, options);
}
var kind = namedType.TypeKind == TypeKind.Struct
? SyntaxKind.StructDeclaration
: namedType.TypeKind == TypeKind.Interface
? SyntaxKind.InterfaceDeclaration
: SyntaxKind.ClassDeclaration;
var typeDeclaration =
SyntaxFactory.TypeDeclaration(kind, namedType.Name.ToIdentifierToken())
.WithAttributeLists(GenerateAttributeDeclarations(namedType, options))
.WithModifiers(GenerateModifiers(namedType, destination, options))
.WithTypeParameterList(GenerateTypeParameterList(namedType, options))
.WithBaseList(GenerateBaseList(namedType))
.WithConstraintClauses(GenerateConstraintClauses(namedType));
return typeDeclaration;
}
private static DelegateDeclarationSyntax GenerateDelegateDeclaration(
INamedTypeSymbol namedType,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var invokeMethod = namedType.DelegateInvokeMethod;
return SyntaxFactory.DelegateDeclaration(
GenerateAttributeDeclarations(namedType, options),
GenerateModifiers(namedType, destination, options),
invokeMethod.ReturnType.GenerateTypeSyntax(),
namedType.Name.ToIdentifierToken(),
TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options),
ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, isExplicit: false, options: options),
namedType.TypeParameters.GenerateConstraintClauses());
}
private static EnumDeclarationSyntax GenerateEnumDeclaration(
INamedTypeSymbol namedType,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var baseList = namedType.EnumUnderlyingType != null && namedType.EnumUnderlyingType.SpecialType != SpecialType.System_Int32
? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList(namedType.EnumUnderlyingType.GenerateTypeSyntax()))
: null;
return SyntaxFactory.EnumDeclaration(
GenerateAttributeDeclarations(namedType, options),
GenerateModifiers(namedType, destination, options),
namedType.Name.ToIdentifierToken(),
baseList: baseList,
members: default(SeparatedSyntaxList<EnumMemberDeclarationSyntax>));
}
private static SyntaxList<AttributeListSyntax> GenerateAttributeDeclarations(
INamedTypeSymbol namedType, CodeGenerationOptions options)
{
return AttributeGenerator.GenerateAttributeLists(namedType.GetAttributes(), options);
}
private static SyntaxTokenList GenerateModifiers(
INamedTypeSymbol namedType,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var tokens = new List<SyntaxToken>();
var defaultAccessibility = destination == CodeGenerationDestination.CompilationUnit || destination == CodeGenerationDestination.Namespace
? Accessibility.Internal
: Accessibility.Private;
AddAccessibilityModifiers(namedType.DeclaredAccessibility, tokens, options, defaultAccessibility);
if (namedType.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
else
{
if (namedType.TypeKind == TypeKind.Class)
{
if (namedType.IsAbstract)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
}
if (namedType.IsSealed)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword));
}
}
}
return tokens.ToSyntaxTokenList();
}
private static TypeParameterListSyntax GenerateTypeParameterList(
INamedTypeSymbol namedType, CodeGenerationOptions options)
{
return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options);
}
private static BaseListSyntax GenerateBaseList(INamedTypeSymbol namedType)
{
var types = new List<TypeSyntax>();
if (namedType.TypeKind == TypeKind.Class && namedType.BaseType != null && namedType.BaseType.SpecialType != Microsoft.CodeAnalysis.SpecialType.System_Object)
{
types.Add(namedType.BaseType.GenerateTypeSyntax());
}
foreach (var type in namedType.Interfaces)
{
types.Add(type.GenerateTypeSyntax());
}
if (types.Count == 0)
{
return null;
}
return SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(types));
}
private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses(INamedTypeSymbol namedType)
{
return namedType.TypeParameters.GenerateConstraintClauses();
}
}
} | 44.815385 | 184 | 0.651991 | [
"Apache-2.0"
] | sperling/cskarp | Src/Workspaces/CSharp/CodeGeneration/NamedTypeGenerator.cs | 11,654 | C# |
using LibGit2Sharp.Core;
using LibGit2Sharp.Handlers;
namespace LibGit2Sharp
{
/// <summary>
/// Options controlling Revert behavior.
/// </summary>
public sealed class RevertOptions : IConvertableToGitCheckoutOpts
{
/// <summary>
/// Initializes a new instance of the <see cref="RevertOptions"/> class.
/// By default the revert will be committed if there are no conflicts.
/// </summary>
public RevertOptions()
{
CommitOnSuccess = true;
FindRenames = true;
// TODO: libgit2 should provide reasonable defaults for these
// values, but it currently does not.
RenameThreshold = 50;
TargetLimit = 200;
}
/// <summary>
/// The Flags specifying what conditions are
/// reported through the OnCheckoutNotify delegate.
/// </summary>
public CheckoutNotifyFlags CheckoutNotifyFlags { get; set; }
/// <summary>
/// Delegate that checkout progress will be reported through.
/// </summary>
public CheckoutProgressHandler OnCheckoutProgress { get; set; }
/// <summary>
/// Delegate that checkout will notify callers of
/// certain conditions. The conditions that are reported is
/// controlled with the CheckoutNotifyFlags property.
/// </summary>
public CheckoutNotifyHandler OnCheckoutNotify { get; set; }
/// <summary>
/// Commit the revert if the revert is successful.
/// </summary>
public bool CommitOnSuccess { get; set; }
/// <summary>
/// When reverting a merge commit, the parent number to consider as
/// mainline, starting from offset 1.
/// <para>
/// As a merge commit has multiple parents, reverting a merge commit
/// will reverse all the changes brought in by the merge except for
/// one parent's line of commits. The parent to preserve is called the
/// mainline, and must be specified by its number (i.e. offset).
/// </para>
/// </summary>
public int Mainline { get; set; }
/// <summary>
/// How to handle conflicts encountered during a merge.
/// </summary>
public MergeFileFavor MergeFileFavor { get; set; }
/// <summary>
/// How Checkout should handle writing out conflicting index entries.
/// </summary>
public CheckoutFileConflictStrategy FileConflictStrategy { get; set; }
/// <summary>
/// Find renames. Default is true.
/// </summary>
public bool FindRenames { get; set; }
/// <summary>
/// Similarity to consider a file renamed (default 50). If
/// `FindRenames` is enabled, added files will be compared
/// with deleted files to determine their similarity. Files that are
/// more similar than the rename threshold (percentage-wise) will be
/// treated as a rename.
/// </summary>
public int RenameThreshold;
/// <summary>
/// Maximum similarity sources to examine for renames (default 200).
/// If the number of rename candidates (add / delete pairs) is greater
/// than this value, inexact rename detection is aborted.
///
/// This setting overrides the `merge.renameLimit` configuration value.
/// </summary>
public int TargetLimit;
#region IConvertableToGitCheckoutOpts
CheckoutCallbacks IConvertableToGitCheckoutOpts.GenerateCallbacks()
{
return CheckoutCallbacks.From(OnCheckoutProgress, OnCheckoutNotify);
}
CheckoutStrategy IConvertableToGitCheckoutOpts.CheckoutStrategy
{
get
{
return CheckoutStrategy.GIT_CHECKOUT_SAFE |
CheckoutStrategy.GIT_CHECKOUT_ALLOW_CONFLICTS |
GitCheckoutOptsWrapper.CheckoutStrategyFromFileConflictStrategy(FileConflictStrategy);
}
}
#endregion IConvertableToGitCheckoutOpts
}
}
| 35.827586 | 109 | 0.606352 | [
"MIT"
] | Acidburn0zzz/libgit2sharp | LibGit2Sharp/RevertOptions.cs | 4,158 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Areas operations.
/// </summary>
public partial class Areas : IServiceOperations<DynamicsClient>, IAreas
{
/// <summary>
/// Initializes a new instance of the Areas class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Areas(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get entities from adoxio_areas
/// </summary>
/// <param name='top'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioAreaCollection>> GetWithHttpMessagesAsync(int? top = default(int?), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("top", top);
tracingParameters.Add("filter", filter);
tracingParameters.Add("count", count);
tracingParameters.Add("orderby", orderby);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_areas").ToString();
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (count != null)
{
_queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (orderby != null)
{
_queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby))));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioAreaCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioAreaCollection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Add new entity to adoxio_areas
/// </summary>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation of the
/// object.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioArea>> CreateWithHttpMessagesAsync(MicrosoftDynamicsCRMadoxioArea body, string prefer = "return=representation", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("prefer", prefer);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_areas").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (prefer != null)
{
if (_httpRequest.Headers.Contains("Prefer"))
{
_httpRequest.Headers.Remove("Prefer");
}
_httpRequest.Headers.TryAddWithoutValidation("Prefer", prefer);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioArea>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioArea>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get entity from adoxio_areas by key
/// </summary>
/// <param name='adoxioAreaid'>
/// key: adoxio_areaid of adoxio_area
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioArea>> GetByKeyWithHttpMessagesAsync(string adoxioAreaid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (adoxioAreaid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "adoxioAreaid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("adoxioAreaid", adoxioAreaid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetByKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_areas({adoxio_areaid})").ToString();
_url = _url.Replace("{adoxio_areaid}", System.Uri.EscapeDataString(adoxioAreaid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioArea>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioArea>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update entity in adoxio_areas
/// </summary>
/// <param name='adoxioAreaid'>
/// key: adoxio_areaid of adoxio_area
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string adoxioAreaid, MicrosoftDynamicsCRMadoxioArea body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (adoxioAreaid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "adoxioAreaid");
}
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("adoxioAreaid", adoxioAreaid);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_areas({adoxio_areaid})").ToString();
_url = _url.Replace("{adoxio_areaid}", System.Uri.EscapeDataString(adoxioAreaid));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete entity from adoxio_areas
/// </summary>
/// <param name='adoxioAreaid'>
/// key: adoxio_areaid of adoxio_area
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string adoxioAreaid, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (adoxioAreaid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "adoxioAreaid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("adoxioAreaid", adoxioAreaid);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_areas({adoxio_areaid})").ToString();
_url = _url.Replace("{adoxio_areaid}", System.Uri.EscapeDataString(adoxioAreaid));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 44.27027 | 467 | 0.560273 | [
"Apache-2.0"
] | ElizabethWolfe/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/Areas.cs | 36,036 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Insights;
using Microsoft.Azure.Management.Insights.Models;
using Microsoft.WindowsAzure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Insights
{
/// <summary>
/// Operations for managing resources sku.
/// </summary>
internal partial class SkuOperations : IServiceOperations<InsightsManagementClient>, ISkuOperations
{
// Uri templates for currently supported types
private static readonly Uri BaseUri = new Uri("http://localhost.com");
private static readonly List<UriTemplate> SupportedUriTemplates = new List<UriTemplate>()
{
// currently only server farm is supported
new UriTemplate("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.web/serverFarms/{serverFarmName}", true)
};
/// <param name='resourceId'>
/// Required. The resource id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<SkuListResponse> ListAvailableSkusAsync(string resourceId, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
// Confirm resourceId is supported
if (!IsSupportedResourceType(resourceId))
{
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Manual scaling not currently supported for resourceId {0}", resourceId));
}
// Antares does not currently support the new contract and has no API to get all valid SKUs so these are hardcoded for now.
SkuListResponse response = new SkuListResponse
{
StatusCode = HttpStatusCode.OK,
Skus = new SkuCollection
{
Value = new List<Sku>
{
new Sku
{
Name = "S1",
Tier = "Standard",
Capacity = new Capacity()
{
Minimum = 1,
Maximum = 10,
Default = 1,
ScaleType = SupportedScaleType.Automatic
}
},
new Sku
{
Name = "S2",
Tier = "Standard",
Capacity = new Capacity()
{
Minimum = 1,
Maximum = 10,
Default = 1,
ScaleType = SupportedScaleType.Automatic
}
},
new Sku
{
Name = "S3",
Tier = "Standard",
Capacity = new Capacity()
{
Minimum = 1,
Maximum = 10,
Default = 1,
ScaleType = SupportedScaleType.Automatic
}
},
new Sku
{
Name = "B1",
Tier = "Basic",
Capacity = new Capacity()
{
Minimum = 1,
Maximum = 3,
Default = 1,
ScaleType = SupportedScaleType.Manual
}
},
new Sku
{
Name = "B2",
Tier = "Basic",
Capacity = new Capacity()
{
Minimum = 1,
Maximum = 3,
Default = 1,
ScaleType = SupportedScaleType.Manual
}
},
new Sku
{
Name = "B3",
Tier = "Basic",
Capacity = new Capacity()
{
Minimum = 1,
Maximum = 3,
Default = 1,
ScaleType = SupportedScaleType.Manual
}
},
new Sku
{
Name = "D1",
Tier = "Shared",
Capacity = new Capacity()
{
ScaleType = SupportedScaleType.None
}
},
new Sku
{
Name = "F1",
Tier = "Free",
Capacity = new Capacity()
{
ScaleType = SupportedScaleType.None
}
},
}
}
};
return response;
}
/// <param name='resourceId'>
/// Required. The resource id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<SkuGetResponse> GetCurrentSkuAsync(string resourceId, CancellationToken cancellationToken)
{
// Confirm resourceId is supported
if (!IsSupportedResourceType(resourceId))
{
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Manual scaling not currently supported for resourceId {0}", resourceId));
}
AntaresSkuGetResponse response = await this.GetAntaresCurrentSkuInternalAsync(resourceId, cancellationToken);
return new SkuGetResponse
{
Name = SkuOperations.GetSkuName(response.Properties.CurrentWorkerSize, response.Properties.Sku),
Tier = response.Properties.Sku,
Capacity = response.Properties.CurrentNumberOfWorkers
};
}
/// <param name='resourceId'>
/// The resource id.
/// </param>
/// <param name='skuName'>
/// The sku name.
/// </param>
/// <param name='skuTier'>
/// The sku tier.
/// </param>
/// <param name='skuCapacity'>
/// The sku capacity.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public Task<SkuUpdateResponse> UpdateCurrentSkuAsync(string resourceId, string skuName, string skuTier, int skuCapacity, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
if (skuName == null)
{
throw new ArgumentNullException("skuName");
}
if (skuTier == null)
{
throw new ArgumentNullException("skuTier");
}
// Confirm resourceId is supported
if (!IsSupportedResourceType(resourceId))
{
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Manual scaling not currently supported for resourceId {0}", resourceId));
}
AntaresSkuUpdateRequest parameters = new AntaresSkuUpdateRequest
{
WorkerSize = SkuOperations.GetWorkerSize(skuName),
Sku = skuTier,
NumberOfWorkers = skuCapacity
};
return this.UpdateAntaresCurrentSkuInternalAsync(resourceId, parameters, cancellationToken);
}
// Verify resourceId is of a supported type
private static bool IsSupportedResourceType(string resourceId)
{
// resource is supported if it matches any of the currently supported templates
return SupportedUriTemplates.Any(template => template.Match(BaseUri, new Uri(BaseUri, resourceId)) != null);
}
private static int GetWorkerSize(string skuName)
{
switch (skuName)
{
case "S1":
case "B1":
case "D1":
case "F1":
return 0;
case "S2":
case "B2":
return 1;
case "S3":
case "B3":
return 2;
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid SKU Name: {0}", skuName));
}
}
private static string GetSkuName(int workerSize, string tier)
{
switch (workerSize)
{
case 0:
switch (tier)
{
case "Standard":
return "S1";
case "Basic":
return "B1";
case "Shared":
return "D1";
case "Free":
return "F1";
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize));
}
case 1:
switch (tier)
{
case "Standard":
return "S2";
case "Basic":
return "B2";
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize));
}
case 2:
switch (tier)
{
case "Standard":
return "S3";
case "Basic":
return "B3";
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize));
}
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize));
}
}
}
}
| 38.504505 | 166 | 0.450788 | [
"Apache-2.0"
] | chuanboz/HDInsight | src/Insights/Customizations/Sku/SkuOperations.Customizations.cs | 12,822 | 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>
//------------------------------------------------------------------------------
// Copyright (c) 2007-2008
// Available under the terms of the
// Eclipse Public License with GPL exception
// See enclosed license file for more information
namespace PhysX.NET
{
using System;
using System.Runtime.InteropServices;
public class NxSceneQueryDesc : DoxyBindObject
{
internal NxSceneQueryDesc(IntPtr ptr) :
base(ptr)
{
}
/// <summary>The callback class used to return results from the batched queries. </summary>
public NxSceneQueryReport report
{
get
{
return NxSceneQueryReport.GetClass(get_NxSceneQueryDesc_report_INVOKE(ClassPointer));
}
set
{
set_NxSceneQueryDesc_report_INVOKE(ClassPointer, value.ClassPointer);
}
}
/// <summary>The method used to execute the queries. ie synchronous or asynchronous. </summary>
public NxSceneQueryExecuteMode executeMode
{
get
{
NxSceneQueryExecuteMode value = get_NxSceneQueryDesc_executeMode_INVOKE(ClassPointer);
return value;
}
set
{
set_NxSceneQueryDesc_executeMode_INVOKE(ClassPointer, value);
}
}
/// <summary></summary>
public NxSceneQueryDesc() :
base(new_NxSceneQueryDesc_INVOKE(false))
{
GC.ReRegisterForFinalize(this);
}
/// <summary></summary>
public void setToDefault()
{
NxSceneQueryDesc_setToDefault_INVOKE(ClassPointer, doSetFunctionPointers);
}
/// <summary></summary>
public bool isValid()
{
return NxSceneQueryDesc_isValid_INVOKE(ClassPointer, doSetFunctionPointers);
}
#region Imports
[System.Security.SuppressUnmanagedCodeSecurity()]
[DllImport(NATIVE_LIBRARY, EntryPoint="set_NxSceneQueryDesc_report")]
private extern static void set_NxSceneQueryDesc_report_INVOKE (HandleRef classPointer, HandleRef newvalue);
[System.Security.SuppressUnmanagedCodeSecurity()]
[DllImport(NATIVE_LIBRARY, EntryPoint="get_NxSceneQueryDesc_report")]
private extern static IntPtr get_NxSceneQueryDesc_report_INVOKE (HandleRef classPointer);
[System.Security.SuppressUnmanagedCodeSecurity()]
[DllImport(NATIVE_LIBRARY, EntryPoint="set_NxSceneQueryDesc_executeMode")]
private extern static void set_NxSceneQueryDesc_executeMode_INVOKE (HandleRef classPointer, NxSceneQueryExecuteMode newvalue);
[System.Security.SuppressUnmanagedCodeSecurity()]
[DllImport(NATIVE_LIBRARY, EntryPoint="get_NxSceneQueryDesc_executeMode")]
private extern static NxSceneQueryExecuteMode get_NxSceneQueryDesc_executeMode_INVOKE (HandleRef classPointer);
[System.Security.SuppressUnmanagedCodeSecurity()]
[DllImport(NATIVE_LIBRARY, EntryPoint="new_NxSceneQueryDesc")]
private extern static IntPtr new_NxSceneQueryDesc_INVOKE (System.Boolean do_override);
[System.Security.SuppressUnmanagedCodeSecurity()]
[DllImport(NATIVE_LIBRARY, EntryPoint="NxSceneQueryDesc_setToDefault")]
private extern static void NxSceneQueryDesc_setToDefault_INVOKE (HandleRef classPointer, System.Boolean call_explicit);
[System.Security.SuppressUnmanagedCodeSecurity()]
[DllImport(NATIVE_LIBRARY, EntryPoint="NxSceneQueryDesc_isValid")]
private extern static System.Boolean NxSceneQueryDesc_isValid_INVOKE (HandleRef classPointer, System.Boolean call_explicit);
#endregion
private static System.Collections.Generic.Dictionary<System.IntPtr, System.WeakReference> database = new System.Collections.Generic.Dictionary<System.IntPtr, System.WeakReference>();
protected override void SetPointer(IntPtr ptr)
{
base.SetPointer(ptr);
database[ptr] = new WeakReference(this);
}
public override void Dispose()
{
database.Remove(ClassPointer.Handle);
base.Dispose();
}
public static NxSceneQueryDesc GetClass(IntPtr ptr)
{
if ((ptr == IntPtr.Zero))
{
return null;
}
System.WeakReference obj;
if (database.TryGetValue(ptr, out obj))
{
if (obj.IsAlive)
{
return ((NxSceneQueryDesc)(obj.Target));
}
}
return new NxSceneQueryDesc(ptr);
}
protected override System.Collections.Generic.List<System.IntPtr> CreateFunctionPointers()
{
System.Collections.Generic.List<System.IntPtr> list = base.CreateFunctionPointers();
return list;
}
}
}
| 32.18 | 185 | 0.688834 | [
"MIT"
] | d3x0r/xperdex | games/PhysX.NET/NxSceneQueryDesc.cs | 4,827 | 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("Microsoft.WindowsAzure.Commands.ServiceManagement.Preview")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
// 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("0a3d16e8-9b84-4c77-a6e3-bc627587472b")]
// 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.3")]
[assembly: AssemblyFileVersion("1.0.3")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.ServiceManagement.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.ServiceManagement.Test")]
#endif
| 52.461538 | 421 | 0.803519 | [
"MIT"
] | azuresdkci/azure-powershell | src/ServiceManagement/Compute/Commands.ServiceManagement.Preview/Properties/AssemblyInfo.cs | 2,010 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
internal partial class ApplicationGatewaysRestOperations
{
private readonly string _userAgent;
private readonly HttpPipeline _pipeline;
private readonly Uri _endpoint;
private readonly string _apiVersion;
/// <summary> The ClientDiagnostics is used to provide tracing support for the client library. </summary>
internal ClientDiagnostics ClientDiagnostics { get; }
/// <summary> Initializes a new instance of ApplicationGatewaysRestOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception>
public ApplicationGatewaysRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
_endpoint = endpoint ?? new Uri("https://management.azure.com");
_apiVersion = apiVersion ?? "2021-02-01";
ClientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
_userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId);
}
internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Delete;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Deletes the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, applicationGatewayName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Deletes the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public Response Delete(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, applicationGatewayName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public async Task<Response<ApplicationGatewayData>> GetAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateGetRequest(subscriptionId, resourceGroupName, applicationGatewayName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayData.DeserializeApplicationGatewayData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ApplicationGatewayData)null, message.Response);
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public Response<ApplicationGatewayData> Get(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateGetRequest(subscriptionId, resourceGroupName, applicationGatewayName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayData.DeserializeApplicationGatewayData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ApplicationGatewayData)null, message.Response);
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName, ApplicationGatewayData parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Creates or updates the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="parameters"> Parameters supplied to the create or update application gateway operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="applicationGatewayName"/> or <paramref name="parameters"/> is null. </exception>
public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, ApplicationGatewayData parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, applicationGatewayName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 201:
return message.Response;
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Creates or updates the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="parameters"> Parameters supplied to the create or update application gateway operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="applicationGatewayName"/> or <paramref name="parameters"/> is null. </exception>
public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string applicationGatewayName, ApplicationGatewayData parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, applicationGatewayName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 201:
return message.Response;
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateUpdateTagsRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName, TagsObject parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Patch;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Updates the specified application gateway tags. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="parameters"> Parameters supplied to update application gateway tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="applicationGatewayName"/> or <paramref name="parameters"/> is null. </exception>
public async Task<Response<ApplicationGatewayData>> UpdateTagsAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, TagsObject parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateUpdateTagsRequest(subscriptionId, resourceGroupName, applicationGatewayName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayData.DeserializeApplicationGatewayData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Updates the specified application gateway tags. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="parameters"> Parameters supplied to update application gateway tags. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="applicationGatewayName"/> or <paramref name="parameters"/> is null. </exception>
public Response<ApplicationGatewayData> UpdateTags(string subscriptionId, string resourceGroupName, string applicationGatewayName, TagsObject parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateUpdateTagsRequest(subscriptionId, resourceGroupName, applicationGatewayName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayData.DeserializeApplicationGatewayData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all application gateways in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
public async Task<Response<ApplicationGatewayListResult>> ListAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListRequest(subscriptionId, resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all application gateways in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
public Response<ApplicationGatewayListResult> List(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListRequest(subscriptionId, resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAllRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets all the application gateways in a subscription. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<ApplicationGatewayListResult>> ListAllAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAllRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets all the application gateways in a subscription. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public Response<ApplicationGatewayListResult> ListAll(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAllRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateStartRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendPath("/start", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Starts the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public async Task<Response> StartAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateStartRequest(subscriptionId, resourceGroupName, applicationGatewayName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Starts the specified application gateway. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public Response Start(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateStartRequest(subscriptionId, resourceGroupName, applicationGatewayName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateStopRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendPath("/stop", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Stops the specified application gateway in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public async Task<Response> StopAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateStopRequest(subscriptionId, resourceGroupName, applicationGatewayName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Stops the specified application gateway in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public Response Stop(string subscriptionId, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateStopRequest(subscriptionId, resourceGroupName, applicationGatewayName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateBackendHealthRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName, string expand)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendPath("/backendhealth", false);
uri.AppendQuery("api-version", _apiVersion, true);
if (expand != null)
{
uri.AppendQuery("$expand", expand, true);
}
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the backend health of the specified application gateway in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="expand"> Expands BackendAddressPool and BackendHttpSettings referenced in backend health. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public async Task<Response> BackendHealthAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, string expand = null, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateBackendHealthRequest(subscriptionId, resourceGroupName, applicationGatewayName, expand);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets the backend health of the specified application gateway in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="expand"> Expands BackendAddressPool and BackendHttpSettings referenced in backend health. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="applicationGatewayName"/> is null. </exception>
public Response BackendHealth(string subscriptionId, string resourceGroupName, string applicationGatewayName, string expand = null, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
using var message = CreateBackendHealthRequest(subscriptionId, resourceGroupName, applicationGatewayName, expand);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateBackendHealthOnDemandRequest(string subscriptionId, string resourceGroupName, string applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, string expand)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGateways/", false);
uri.AppendPath(applicationGatewayName, true);
uri.AppendPath("/getBackendHealthOnDemand", false);
uri.AppendQuery("api-version", _apiVersion, true);
if (expand != null)
{
uri.AppendQuery("$expand", expand, true);
}
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(probeRequest);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets the backend health for given combination of backend pool and http setting of the specified application gateway in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="probeRequest"> Request body for on-demand test probe operation. </param>
/// <param name="expand"> Expands BackendAddressPool and BackendHttpSettings referenced in backend health. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="applicationGatewayName"/> or <paramref name="probeRequest"/> is null. </exception>
public async Task<Response> BackendHealthOnDemandAsync(string subscriptionId, string resourceGroupName, string applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, string expand = null, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
if (probeRequest == null)
{
throw new ArgumentNullException(nameof(probeRequest));
}
using var message = CreateBackendHealthOnDemandRequest(subscriptionId, resourceGroupName, applicationGatewayName, probeRequest, expand);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets the backend health for given combination of backend pool and http setting of the specified application gateway in a resource group. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="applicationGatewayName"> The name of the application gateway. </param>
/// <param name="probeRequest"> Request body for on-demand test probe operation. </param>
/// <param name="expand"> Expands BackendAddressPool and BackendHttpSettings referenced in backend health. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="applicationGatewayName"/> or <paramref name="probeRequest"/> is null. </exception>
public Response BackendHealthOnDemand(string subscriptionId, string resourceGroupName, string applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, string expand = null, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (applicationGatewayName == null)
{
throw new ArgumentNullException(nameof(applicationGatewayName));
}
if (probeRequest == null)
{
throw new ArgumentNullException(nameof(probeRequest));
}
using var message = CreateBackendHealthOnDemandRequest(subscriptionId, resourceGroupName, applicationGatewayName, probeRequest, expand);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAvailableServerVariablesRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGatewayAvailableServerVariables", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all available server variables. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<IReadOnlyList<string>>> ListAvailableServerVariablesAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableServerVariablesRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
IReadOnlyList<string> value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
List<string> array = new List<string>();
foreach (var item in document.RootElement.EnumerateArray())
{
array.Add(item.GetString());
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all available server variables. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public Response<IReadOnlyList<string>> ListAvailableServerVariables(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableServerVariablesRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
IReadOnlyList<string> value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
List<string> array = new List<string>();
foreach (var item in document.RootElement.EnumerateArray())
{
array.Add(item.GetString());
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAvailableRequestHeadersRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGatewayAvailableRequestHeaders", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all available request headers. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<IReadOnlyList<string>>> ListAvailableRequestHeadersAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableRequestHeadersRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
IReadOnlyList<string> value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
List<string> array = new List<string>();
foreach (var item in document.RootElement.EnumerateArray())
{
array.Add(item.GetString());
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all available request headers. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public Response<IReadOnlyList<string>> ListAvailableRequestHeaders(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableRequestHeadersRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
IReadOnlyList<string> value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
List<string> array = new List<string>();
foreach (var item in document.RootElement.EnumerateArray())
{
array.Add(item.GetString());
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAvailableResponseHeadersRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGatewayAvailableResponseHeaders", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all available response headers. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<IReadOnlyList<string>>> ListAvailableResponseHeadersAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableResponseHeadersRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
IReadOnlyList<string> value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
List<string> array = new List<string>();
foreach (var item in document.RootElement.EnumerateArray())
{
array.Add(item.GetString());
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all available response headers. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public Response<IReadOnlyList<string>> ListAvailableResponseHeaders(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableResponseHeadersRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
IReadOnlyList<string> value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
List<string> array = new List<string>();
foreach (var item in document.RootElement.EnumerateArray())
{
array.Add(item.GetString());
}
value = array;
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAvailableWafRuleSetsRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGatewayAvailableWafRuleSets", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all available web application firewall rule sets. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<ApplicationGatewayAvailableWafRuleSetsResult>> ListAvailableWafRuleSetsAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableWafRuleSetsRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableWafRuleSetsResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayAvailableWafRuleSetsResult.DeserializeApplicationGatewayAvailableWafRuleSetsResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all available web application firewall rule sets. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public Response<ApplicationGatewayAvailableWafRuleSetsResult> ListAvailableWafRuleSets(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableWafRuleSetsRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableWafRuleSetsResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayAvailableWafRuleSetsResult.DeserializeApplicationGatewayAvailableWafRuleSetsResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAvailableSslOptionsRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists available Ssl options for configuring Ssl policy. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<ApplicationGatewayAvailableSslOptionsData>> ListAvailableSslOptionsAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableSslOptionsRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableSslOptionsData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayAvailableSslOptionsData.DeserializeApplicationGatewayAvailableSslOptionsData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ApplicationGatewayAvailableSslOptionsData)null, message.Response);
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists available Ssl options for configuring Ssl policy. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public Response<ApplicationGatewayAvailableSslOptionsData> ListAvailableSslOptions(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableSslOptionsRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableSslOptionsData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayAvailableSslOptionsData.DeserializeApplicationGatewayAvailableSslOptionsData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ApplicationGatewayAvailableSslOptionsData)null, message.Response);
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAvailableSslPredefinedPoliciesRequest(string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all SSL predefined policies for configuring Ssl policy. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<ApplicationGatewayAvailableSslPredefinedPolicies>> ListAvailableSslPredefinedPoliciesAsync(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableSslPredefinedPoliciesRequest(subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableSslPredefinedPolicies value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayAvailableSslPredefinedPolicies.DeserializeApplicationGatewayAvailableSslPredefinedPolicies(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all SSL predefined policies for configuring Ssl policy. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception>
public Response<ApplicationGatewayAvailableSslPredefinedPolicies> ListAvailableSslPredefinedPolicies(string subscriptionId, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableSslPredefinedPoliciesRequest(subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableSslPredefinedPolicies value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayAvailableSslPredefinedPolicies.DeserializeApplicationGatewayAvailableSslPredefinedPolicies(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetSslPredefinedPolicyRequest(string subscriptionId, string predefinedPolicyName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Network/applicationGatewayAvailableSslOptions/default/predefinedPolicies/", false);
uri.AppendPath(predefinedPolicyName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets Ssl predefined policy with the specified policy name. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="predefinedPolicyName"> Name of Ssl predefined policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="predefinedPolicyName"/> is null. </exception>
public async Task<Response<ApplicationGatewaySslPredefinedPolicyData>> GetSslPredefinedPolicyAsync(string subscriptionId, string predefinedPolicyName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (predefinedPolicyName == null)
{
throw new ArgumentNullException(nameof(predefinedPolicyName));
}
using var message = CreateGetSslPredefinedPolicyRequest(subscriptionId, predefinedPolicyName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewaySslPredefinedPolicyData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewaySslPredefinedPolicyData.DeserializeApplicationGatewaySslPredefinedPolicyData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ApplicationGatewaySslPredefinedPolicyData)null, message.Response);
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets Ssl predefined policy with the specified policy name. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="predefinedPolicyName"> Name of Ssl predefined policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="predefinedPolicyName"/> is null. </exception>
public Response<ApplicationGatewaySslPredefinedPolicyData> GetSslPredefinedPolicy(string subscriptionId, string predefinedPolicyName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (predefinedPolicyName == null)
{
throw new ArgumentNullException(nameof(predefinedPolicyName));
}
using var message = CreateGetSslPredefinedPolicyRequest(subscriptionId, predefinedPolicyName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewaySslPredefinedPolicyData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewaySslPredefinedPolicyData.DeserializeApplicationGatewaySslPredefinedPolicyData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ApplicationGatewaySslPredefinedPolicyData)null, message.Response);
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all application gateways in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
public async Task<Response<ApplicationGatewayListResult>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all application gateways in a resource group. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception>
public Response<ApplicationGatewayListResult> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAllNextPageRequest(string nextLink, string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Gets all the application gateways in a subscription. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<ApplicationGatewayListResult>> ListAllNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAllNextPageRequest(nextLink, subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets all the application gateways in a subscription. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
public Response<ApplicationGatewayListResult> ListAllNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAllNextPageRequest(nextLink, subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayListResult.DeserializeApplicationGatewayListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListAvailableSslPredefinedPoliciesNextPageRequest(string nextLink, string subscriptionId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Lists all SSL predefined policies for configuring Ssl policy. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
public async Task<Response<ApplicationGatewayAvailableSslPredefinedPolicies>> ListAvailableSslPredefinedPoliciesNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableSslPredefinedPoliciesNextPageRequest(nextLink, subscriptionId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableSslPredefinedPolicies value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ApplicationGatewayAvailableSslPredefinedPolicies.DeserializeApplicationGatewayAvailableSslPredefinedPolicies(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists all SSL predefined policies for configuring Ssl policy. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception>
public Response<ApplicationGatewayAvailableSslPredefinedPolicies> ListAvailableSslPredefinedPoliciesNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
using var message = CreateListAvailableSslPredefinedPoliciesNextPageRequest(nextLink, subscriptionId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ApplicationGatewayAvailableSslPredefinedPolicies value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ApplicationGatewayAvailableSslPredefinedPolicies.DeserializeApplicationGatewayAvailableSslPredefinedPolicies(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 56.710795 | 257 | 0.631864 | [
"MIT"
] | AntonioVT/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/RestOperations/ApplicationGatewaysRestOperations.cs | 99,811 | C# |
#if ENABLE_PLAYFABSERVER_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.ServerModels
{
[Serializable]
public class AdCampaignAttribution
{
/// <summary>
/// UTC time stamp of attribution
/// </summary>
public DateTime AttributedAt;
/// <summary>
/// Attribution campaign identifier
/// </summary>
public string CampaignId;
/// <summary>
/// Attribution network name
/// </summary>
public string Platform;
}
[Serializable]
public class AdCampaignAttributionModel
{
/// <summary>
/// UTC time stamp of attribution
/// </summary>
public DateTime AttributedAt;
/// <summary>
/// Attribution campaign identifier
/// </summary>
public string CampaignId;
/// <summary>
/// Attribution network name
/// </summary>
public string Platform;
}
[Serializable]
public class AddCharacterVirtualCurrencyRequest : PlayFabRequestCommon
{
/// <summary>
/// Amount to be added to the character balance of the specified virtual currency. Maximum VC balance is Int32
/// (2,147,483,647). Any increase over this value will be discarded.
/// </summary>
public int Amount;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// PlayFab unique identifier of the user whose virtual currency balance is to be incremented.
/// </summary>
public string PlayFabId;
/// <summary>
/// Name of the virtual currency which is to be incremented.
/// </summary>
public string VirtualCurrency;
}
[Serializable]
public class AddFriendRequest : PlayFabRequestCommon
{
/// <summary>
/// Email address of the user being added.
/// </summary>
public string FriendEmail;
/// <summary>
/// The PlayFab identifier of the user being added.
/// </summary>
public string FriendPlayFabId;
/// <summary>
/// Title-specific display name of the user to being added.
/// </summary>
public string FriendTitleDisplayName;
/// <summary>
/// The PlayFab username of the user being added
/// </summary>
public string FriendUsername;
/// <summary>
/// PlayFab identifier of the player to add a new friend.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// This API will trigger a player_tag_added event and add a tag with the given TagName and PlayFabID to the corresponding
/// player profile. TagName can be used for segmentation and it is limited to 256 characters. Also there is a limit on the
/// number of tags a title can have.
/// </summary>
[Serializable]
public class AddPlayerTagRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique tag for player profile.
/// </summary>
public string TagName;
}
[Serializable]
public class AddPlayerTagResult : PlayFabResultCommon
{
}
[Serializable]
public class AddSharedGroupMembersRequest : PlayFabRequestCommon
{
/// <summary>
/// An array of unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public List<string> PlayFabIds;
/// <summary>
/// Unique identifier for the shared group.
/// </summary>
public string SharedGroupId;
}
[Serializable]
public class AddSharedGroupMembersResult : PlayFabResultCommon
{
}
[Serializable]
public class AddUserVirtualCurrencyRequest : PlayFabRequestCommon
{
/// <summary>
/// Amount to be added to the user balance of the specified virtual currency. Maximum VC balance is Int32 (2,147,483,647).
/// Any increase over this value will be discarded.
/// </summary>
public int Amount;
/// <summary>
/// PlayFab unique identifier of the user whose virtual currency balance is to be increased.
/// </summary>
public string PlayFabId;
/// <summary>
/// Name of the virtual currency which is to be incremented.
/// </summary>
public string VirtualCurrency;
}
[Serializable]
public class AdvancedPushPlatformMsg
{
/// <summary>
/// The Json the platform should receive.
/// </summary>
public string Json;
/// <summary>
/// The platform that should receive the Json.
/// </summary>
public PushNotificationPlatform Platform;
}
/// <summary>
/// Note that data returned may be Personally Identifying Information (PII), such as email address, and so care should be
/// taken in how this data is stored and managed. Since this call will always return the relevant information for users who
/// have accessed
/// the title, the recommendation is to not store this data locally.
/// </summary>
[Serializable]
public class AuthenticateSessionTicketRequest : PlayFabRequestCommon
{
/// <summary>
/// Session ticket as issued by a PlayFab client login API.
/// </summary>
public string SessionTicket;
}
[Serializable]
public class AuthenticateSessionTicketResult : PlayFabResultCommon
{
/// <summary>
/// Account info for the user whose session ticket was supplied.
/// </summary>
public UserAccountInfo UserInfo;
}
[Serializable]
public class AwardSteamAchievementItem
{
/// <summary>
/// Unique Steam achievement name.
/// </summary>
public string AchievementName;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Result of the award attempt (only valid on response, not on request).
/// </summary>
public bool Result;
}
[Serializable]
public class AwardSteamAchievementRequest : PlayFabRequestCommon
{
/// <summary>
/// Array of achievements to grant and the users to whom they are to be granted.
/// </summary>
public List<AwardSteamAchievementItem> Achievements;
}
[Serializable]
public class AwardSteamAchievementResult : PlayFabResultCommon
{
/// <summary>
/// Array of achievements granted.
/// </summary>
public List<AwardSteamAchievementItem> AchievementResults;
}
/// <summary>
/// Contains information for a ban.
/// </summary>
[Serializable]
public class BanInfo
{
/// <summary>
/// The active state of this ban. Expired bans may still have this value set to true but they will have no effect.
/// </summary>
public bool Active;
/// <summary>
/// The unique Ban Id associated with this ban.
/// </summary>
public string BanId;
/// <summary>
/// The time when this ban was applied.
/// </summary>
public DateTime? Created;
/// <summary>
/// The time when this ban expires. Permanent bans do not have expiration date.
/// </summary>
public DateTime? Expires;
/// <summary>
/// The IP address on which the ban was applied. May affect multiple players.
/// </summary>
public string IPAddress;
/// <summary>
/// The MAC address on which the ban was applied. May affect multiple players.
/// </summary>
public string MACAddress;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// The reason why this ban was applied.
/// </summary>
public string Reason;
}
/// <summary>
/// Represents a single ban request.
/// </summary>
[Serializable]
public class BanRequest : PlayFabRequestCommon
{
/// <summary>
/// The duration in hours for the ban. Leave this blank for a permanent ban.
/// </summary>
public uint? DurationInHours;
/// <summary>
/// IP address to be banned. May affect multiple players.
/// </summary>
public string IPAddress;
/// <summary>
/// MAC address to be banned. May affect multiple players.
/// </summary>
public string MACAddress;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// The reason for this ban. Maximum 140 characters.
/// </summary>
public string Reason;
}
/// <summary>
/// The existence of each user will not be verified. When banning by IP or MAC address, multiple players may be affected, so
/// use this feature with caution. Returns information about the new bans.
/// </summary>
[Serializable]
public class BanUsersRequest : PlayFabRequestCommon
{
/// <summary>
/// List of ban requests to be applied. Maximum 100.
/// </summary>
public List<BanRequest> Bans;
}
[Serializable]
public class BanUsersResult : PlayFabResultCommon
{
/// <summary>
/// Information on the bans that were applied
/// </summary>
public List<BanInfo> BanData;
}
/// <summary>
/// A purchasable item from the item catalog
/// </summary>
[Serializable]
public class CatalogItem
{
/// <summary>
/// defines the bundle properties for the item - bundles are items which contain other items, including random drop tables
/// and virtual currencies
/// </summary>
public CatalogItemBundleInfo Bundle;
/// <summary>
/// if true, then an item instance of this type can be used to grant a character to a user.
/// </summary>
public bool CanBecomeCharacter;
/// <summary>
/// catalog version for this item
/// </summary>
public string CatalogVersion;
/// <summary>
/// defines the consumable properties (number of uses, timeout) for the item
/// </summary>
public CatalogItemConsumableInfo Consumable;
/// <summary>
/// defines the container properties for the item - what items it contains, including random drop tables and virtual
/// currencies, and what item (if any) is required to open it via the UnlockContainerItem API
/// </summary>
public CatalogItemContainerInfo Container;
/// <summary>
/// game specific custom data
/// </summary>
public string CustomData;
/// <summary>
/// text description of item, to show in-game
/// </summary>
public string Description;
/// <summary>
/// text name for the item, to show in-game
/// </summary>
public string DisplayName;
/// <summary>
/// If the item has IsLImitedEdition set to true, and this is the first time this ItemId has been defined as a limited
/// edition item, this value determines the total number of instances to allocate for the title. Once this limit has been
/// reached, no more instances of this ItemId can be created, and attempts to purchase or grant it will return a Result of
/// false for that ItemId. If the item has already been defined to have a limited edition count, or if this value is less
/// than zero, it will be ignored.
/// </summary>
public int InitialLimitedEditionCount;
/// <summary>
/// BETA: If true, then only a fixed number can ever be granted.
/// </summary>
public bool IsLimitedEdition;
/// <summary>
/// if true, then only one item instance of this type will exist and its remaininguses will be incremented instead.
/// RemainingUses will cap out at Int32.Max (2,147,483,647). All subsequent increases will be discarded
/// </summary>
public bool IsStackable;
/// <summary>
/// if true, then an item instance of this type can be traded between players using the trading APIs
/// </summary>
public bool IsTradable;
/// <summary>
/// class to which the item belongs
/// </summary>
public string ItemClass;
/// <summary>
/// unique identifier for this item
/// </summary>
public string ItemId;
/// <summary>
/// URL to the item image. For Facebook purchase to display the image on the item purchase page, this must be set to an HTTP
/// URL.
/// </summary>
public string ItemImageUrl;
/// <summary>
/// override prices for this item for specific currencies
/// </summary>
public Dictionary<string,uint> RealCurrencyPrices;
/// <summary>
/// list of item tags
/// </summary>
public List<string> Tags;
/// <summary>
/// price of this item in virtual currencies and "RM" (the base Real Money purchase price, in USD pennies)
/// </summary>
public Dictionary<string,uint> VirtualCurrencyPrices;
}
[Serializable]
public class CatalogItemBundleInfo
{
/// <summary>
/// unique ItemId values for all items which will be added to the player inventory when the bundle is added
/// </summary>
public List<string> BundledItems;
/// <summary>
/// unique TableId values for all RandomResultTable objects which are part of the bundle (random tables will be resolved and
/// add the relevant items to the player inventory when the bundle is added)
/// </summary>
public List<string> BundledResultTables;
/// <summary>
/// virtual currency types and balances which will be added to the player inventory when the bundle is added
/// </summary>
public Dictionary<string,uint> BundledVirtualCurrencies;
}
[Serializable]
public class CatalogItemConsumableInfo
{
/// <summary>
/// number of times this object can be used, after which it will be removed from the player inventory
/// </summary>
public uint? UsageCount;
/// <summary>
/// duration in seconds for how long the item will remain in the player inventory - once elapsed, the item will be removed
/// (recommended minimum value is 5 seconds, as lower values can cause the item to expire before operations depending on
/// this item's details have completed)
/// </summary>
public uint? UsagePeriod;
/// <summary>
/// all inventory item instances in the player inventory sharing a non-null UsagePeriodGroup have their UsagePeriod values
/// added together, and share the result - when that period has elapsed, all the items in the group will be removed
/// </summary>
public string UsagePeriodGroup;
}
/// <summary>
/// Containers are inventory items that can hold other items defined in the catalog, as well as virtual currency, which is
/// added to the player inventory when the container is unlocked, using the UnlockContainerItem API. The items can be
/// anything defined in the catalog, as well as RandomResultTable objects which will be resolved when the container is
/// unlocked. Containers and their keys should be defined as Consumable (having a limited number of uses) in their catalog
/// defintiions, unless the intent is for the player to be able to re-use them infinitely.
/// </summary>
[Serializable]
public class CatalogItemContainerInfo
{
/// <summary>
/// unique ItemId values for all items which will be added to the player inventory, once the container has been unlocked
/// </summary>
public List<string> ItemContents;
/// <summary>
/// ItemId for the catalog item used to unlock the container, if any (if not specified, a call to UnlockContainerItem will
/// open the container, adding the contents to the player inventory and currency balances)
/// </summary>
public string KeyItemId;
/// <summary>
/// unique TableId values for all RandomResultTable objects which are part of the container (once unlocked, random tables
/// will be resolved and add the relevant items to the player inventory)
/// </summary>
public List<string> ResultTableContents;
/// <summary>
/// virtual currency types and balances which will be added to the player inventory when the container is unlocked
/// </summary>
public Dictionary<string,uint> VirtualCurrencyContents;
}
[Serializable]
public class CharacterInventory
{
/// <summary>
/// The id of this character.
/// </summary>
public string CharacterId;
/// <summary>
/// The inventory of this character.
/// </summary>
public List<ItemInstance> Inventory;
}
[Serializable]
public class CharacterLeaderboardEntry
{
/// <summary>
/// PlayFab unique identifier of the character that belongs to the user for this leaderboard entry.
/// </summary>
public string CharacterId;
/// <summary>
/// Title-specific display name of the character for this leaderboard entry.
/// </summary>
public string CharacterName;
/// <summary>
/// Name of the character class for this entry.
/// </summary>
public string CharacterType;
/// <summary>
/// Title-specific display name of the user for this leaderboard entry.
/// </summary>
public string DisplayName;
/// <summary>
/// PlayFab unique identifier of the user for this leaderboard entry.
/// </summary>
public string PlayFabId;
/// <summary>
/// User's overall position in the leaderboard.
/// </summary>
public int Position;
/// <summary>
/// Specific value of the user's statistic.
/// </summary>
public int StatValue;
}
[Serializable]
public class CharacterResult : PlayFabResultCommon
{
/// <summary>
/// The id for this character on this player.
/// </summary>
public string CharacterId;
/// <summary>
/// The name of this character.
/// </summary>
public string CharacterName;
/// <summary>
/// The type-string that was given to this character on creation.
/// </summary>
public string CharacterType;
}
public enum CloudScriptRevisionOption
{
Live,
Latest,
Specific
}
[Serializable]
public class ConsumeItemRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Number of uses to consume from the item.
/// </summary>
public int ConsumeCount;
/// <summary>
/// Unique instance identifier of the item to be consumed.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class ConsumeItemResult : PlayFabResultCommon
{
/// <summary>
/// Unique instance identifier of the item with uses consumed.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Number of uses remaining on the item.
/// </summary>
public int RemainingUses;
}
[Serializable]
public class ContactEmailInfo
{
/// <summary>
/// The email address
/// </summary>
public string EmailAddress;
/// <summary>
/// The name of the email info data
/// </summary>
public string Name;
/// <summary>
/// The verification status of the email
/// </summary>
public EmailVerificationStatus? VerificationStatus;
}
[Serializable]
public class ContactEmailInfoModel
{
/// <summary>
/// The email address
/// </summary>
public string EmailAddress;
/// <summary>
/// The name of the email info data
/// </summary>
public string Name;
/// <summary>
/// The verification status of the email
/// </summary>
public EmailVerificationStatus? VerificationStatus;
}
public enum ContinentCode
{
AF,
AN,
AS,
EU,
NA,
OC,
SA
}
public enum CountryCode
{
AF,
AX,
AL,
DZ,
AS,
AD,
AO,
AI,
AQ,
AG,
AR,
AM,
AW,
AU,
AT,
AZ,
BS,
BH,
BD,
BB,
BY,
BE,
BZ,
BJ,
BM,
BT,
BO,
BQ,
BA,
BW,
BV,
BR,
IO,
BN,
BG,
BF,
BI,
KH,
CM,
CA,
CV,
KY,
CF,
TD,
CL,
CN,
CX,
CC,
CO,
KM,
CG,
CD,
CK,
CR,
CI,
HR,
CU,
CW,
CY,
CZ,
DK,
DJ,
DM,
DO,
EC,
EG,
SV,
GQ,
ER,
EE,
ET,
FK,
FO,
FJ,
FI,
FR,
GF,
PF,
TF,
GA,
GM,
GE,
DE,
GH,
GI,
GR,
GL,
GD,
GP,
GU,
GT,
GG,
GN,
GW,
GY,
HT,
HM,
VA,
HN,
HK,
HU,
IS,
IN,
ID,
IR,
IQ,
IE,
IM,
IL,
IT,
JM,
JP,
JE,
JO,
KZ,
KE,
KI,
KP,
KR,
KW,
KG,
LA,
LV,
LB,
LS,
LR,
LY,
LI,
LT,
LU,
MO,
MK,
MG,
MW,
MY,
MV,
ML,
MT,
MH,
MQ,
MR,
MU,
YT,
MX,
FM,
MD,
MC,
MN,
ME,
MS,
MA,
MZ,
MM,
NA,
NR,
NP,
NL,
NC,
NZ,
NI,
NE,
NG,
NU,
NF,
MP,
NO,
OM,
PK,
PW,
PS,
PA,
PG,
PY,
PE,
PH,
PN,
PL,
PT,
PR,
QA,
RE,
RO,
RU,
RW,
BL,
SH,
KN,
LC,
MF,
PM,
VC,
WS,
SM,
ST,
SA,
SN,
RS,
SC,
SL,
SG,
SX,
SK,
SI,
SB,
SO,
ZA,
GS,
SS,
ES,
LK,
SD,
SR,
SJ,
SZ,
SE,
CH,
SY,
TW,
TJ,
TZ,
TH,
TL,
TG,
TK,
TO,
TT,
TN,
TR,
TM,
TC,
TV,
UG,
UA,
AE,
GB,
US,
UM,
UY,
UZ,
VU,
VE,
VN,
VG,
VI,
WF,
EH,
YE,
ZM,
ZW
}
/// <summary>
/// If SharedGroupId is specified, the service will attempt to create a group with that
/// identifier, and will return an error if it is already in use. If no SharedGroupId is specified, a random identifier will
/// be assigned.
/// </summary>
[Serializable]
public class CreateSharedGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier for the shared group (a random identifier will be assigned, if one is not specified).
/// </summary>
public string SharedGroupId;
}
[Serializable]
public class CreateSharedGroupResult : PlayFabResultCommon
{
/// <summary>
/// Unique identifier for the shared group.
/// </summary>
public string SharedGroupId;
}
public enum Currency
{
AED,
AFN,
ALL,
AMD,
ANG,
AOA,
ARS,
AUD,
AWG,
AZN,
BAM,
BBD,
BDT,
BGN,
BHD,
BIF,
BMD,
BND,
BOB,
BRL,
BSD,
BTN,
BWP,
BYR,
BZD,
CAD,
CDF,
CHF,
CLP,
CNY,
COP,
CRC,
CUC,
CUP,
CVE,
CZK,
DJF,
DKK,
DOP,
DZD,
EGP,
ERN,
ETB,
EUR,
FJD,
FKP,
GBP,
GEL,
GGP,
GHS,
GIP,
GMD,
GNF,
GTQ,
GYD,
HKD,
HNL,
HRK,
HTG,
HUF,
IDR,
ILS,
IMP,
INR,
IQD,
IRR,
ISK,
JEP,
JMD,
JOD,
JPY,
KES,
KGS,
KHR,
KMF,
KPW,
KRW,
KWD,
KYD,
KZT,
LAK,
LBP,
LKR,
LRD,
LSL,
LYD,
MAD,
MDL,
MGA,
MKD,
MMK,
MNT,
MOP,
MRO,
MUR,
MVR,
MWK,
MXN,
MYR,
MZN,
NAD,
NGN,
NIO,
NOK,
NPR,
NZD,
OMR,
PAB,
PEN,
PGK,
PHP,
PKR,
PLN,
PYG,
QAR,
RON,
RSD,
RUB,
RWF,
SAR,
SBD,
SCR,
SDG,
SEK,
SGD,
SHP,
SLL,
SOS,
SPL,
SRD,
STD,
SVC,
SYP,
SZL,
THB,
TJS,
TMT,
TND,
TOP,
TRY,
TTD,
TVD,
TWD,
TZS,
UAH,
UGX,
USD,
UYU,
UZS,
VEF,
VND,
VUV,
WST,
XAF,
XCD,
XDR,
XOF,
XPF,
YER,
ZAR,
ZMW,
ZWD
}
/// <summary>
/// This function will delete the specified character from the list allowed by the user, and
/// will also delete any inventory or VC currently held by that character. It will NOT delete any statistics
/// associated for this character, in order to preserve leaderboard integrity.
/// </summary>
[Serializable]
public class DeleteCharacterFromUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// If true, the character's inventory will be transferred up to the owning user; otherwise, this request will purge those
/// items.
/// </summary>
public bool SaveCharacterInventory;
}
[Serializable]
public class DeleteCharacterFromUserResult : PlayFabResultCommon
{
}
/// <summary>
/// Deletes all data associated with the player, including statistics, custom data, inventory, purchases, virtual currency
/// balances,
/// characters and shared group memberships. Removes the player from all leaderboards and player search
/// indexes. Does not delete PlayStream event history associated with the player.
/// Does not delete the publisher user account that created the player in the title nor associated data
/// such as username, password, email address, account linkages, or friends list.
/// Note, this API queues the player for deletion and returns immediately. It may take several minutes
/// or more before all player data is fully deleted.
/// Until the player data is fully deleted, attempts to recreate the player with the same user account
/// in the same title will fail with the 'AccountDeleted' error.
/// This API must be enabled for use as an option in the game manager website. It is disabled by
/// default.
/// </summary>
[Serializable]
public class DeletePlayerRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class DeletePlayerResult : PlayFabResultCommon
{
}
[Serializable]
public class DeleteSharedGroupRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier for the shared group.
/// </summary>
public string SharedGroupId;
}
[Serializable]
public class DeregisterGameRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier for the Game Server Instance that is being deregistered.
/// </summary>
public string LobbyId;
}
[Serializable]
public class DeregisterGameResponse : PlayFabResultCommon
{
}
public enum EmailVerificationStatus
{
Unverified,
Pending,
Confirmed
}
[Serializable]
public class EmptyResponse : PlayFabResultCommon
{
}
/// <summary>
/// Combined entity type and ID structure which uniquely identifies a single entity.
/// </summary>
[Serializable]
public class EntityKey
{
/// <summary>
/// Unique ID of the entity.
/// </summary>
public string Id;
/// <summary>
/// Entity type. See https://api.playfab.com/docs/tutorials/entities/entitytypes
/// </summary>
public string Type;
}
[Serializable]
public class EntityTokenResponse : PlayFabResultCommon
{
/// <summary>
/// The entity id and type.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The token used to set X-EntityToken for all entity based API calls.
/// </summary>
public string EntityToken;
/// <summary>
/// The time the token will expire, if it is an expiring token, in UTC.
/// </summary>
public DateTime? TokenExpiration;
}
[Serializable]
public class EvaluateRandomResultTableRequest : PlayFabRequestCommon
{
/// <summary>
/// Specifies the catalog version that should be used to evaluate the Random Result Table. If unspecified, uses
/// default/primary catalog.
/// </summary>
public string CatalogVersion;
/// <summary>
/// The unique identifier of the Random Result Table to use.
/// </summary>
public string TableId;
}
/// <summary>
/// Note that if the Random Result Table contains no entries, or does not exist for the catalog specified (the Primary
/// catalog if one is not specified), an InvalidDropTable error will be returned.
/// </summary>
[Serializable]
public class EvaluateRandomResultTableResult : PlayFabResultCommon
{
/// <summary>
/// Unique identifier for the item returned from the Random Result Table evaluation, for the given catalog.
/// </summary>
public string ResultItemId;
}
[Serializable]
public class ExecuteCloudScriptResult : PlayFabResultCommon
{
/// <summary>
/// Number of PlayFab API requests issued by the CloudScript function
/// </summary>
public int APIRequestsIssued;
/// <summary>
/// Information about the error, if any, that occurred during execution
/// </summary>
public ScriptExecutionError Error;
public double ExecutionTimeSeconds;
/// <summary>
/// The name of the function that executed
/// </summary>
public string FunctionName;
/// <summary>
/// The object returned from the CloudScript function, if any
/// </summary>
public object FunctionResult;
/// <summary>
/// Flag indicating if the FunctionResult was too large and was subsequently dropped from this event. This only occurs if
/// the total event size is larger than 350KB.
/// </summary>
public bool? FunctionResultTooLarge;
/// <summary>
/// Number of external HTTP requests issued by the CloudScript function
/// </summary>
public int HttpRequestsIssued;
/// <summary>
/// Entries logged during the function execution. These include both entries logged in the function code using log.info()
/// and log.error() and error entries for API and HTTP request failures.
/// </summary>
public List<LogStatement> Logs;
/// <summary>
/// Flag indicating if the logs were too large and were subsequently dropped from this event. This only occurs if the total
/// event size is larger than 350KB after the FunctionResult was removed.
/// </summary>
public bool? LogsTooLarge;
public uint MemoryConsumedBytes;
/// <summary>
/// Processor time consumed while executing the function. This does not include time spent waiting on API calls or HTTP
/// requests.
/// </summary>
public double ProcessorTimeSeconds;
/// <summary>
/// The revision of the CloudScript that executed
/// </summary>
public int Revision;
}
[Serializable]
public class ExecuteCloudScriptServerRequest : PlayFabRequestCommon
{
/// <summary>
/// The name of the CloudScript function to execute
/// </summary>
public string FunctionName;
/// <summary>
/// Object that is passed in to the function as the first argument
/// </summary>
public object FunctionParameter;
/// <summary>
/// Generate a 'player_executed_cloudscript' PlayStream event containing the results of the function execution and other
/// contextual information. This event will show up in the PlayStream debugger console for the player in Game Manager.
/// </summary>
public bool? GeneratePlayStreamEvent;
/// <summary>
/// The unique user identifier for the player on whose behalf the script is being run
/// </summary>
public string PlayFabId;
/// <summary>
/// Option for which revision of the CloudScript to execute. 'Latest' executes the most recently created revision, 'Live'
/// executes the current live, published revision, and 'Specific' executes the specified revision. The default value is
/// 'Specific', if the SpeificRevision parameter is specified, otherwise it is 'Live'.
/// </summary>
public CloudScriptRevisionOption? RevisionSelection;
/// <summary>
/// The specivic revision to execute, when RevisionSelection is set to 'Specific'
/// </summary>
public int? SpecificRevision;
}
[Serializable]
public class FacebookInstantGamesPlayFabIdPair
{
/// <summary>
/// Unique Facebook Instant Games identifier for a user.
/// </summary>
public string FacebookInstantGamesId;
/// <summary>
/// Unique PlayFab identifier for a user, or null if no PlayFab account is linked to the Facebook Instant Games identifier.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class FacebookPlayFabIdPair
{
/// <summary>
/// Unique Facebook identifier for a user.
/// </summary>
public string FacebookId;
/// <summary>
/// Unique PlayFab identifier for a user, or null if no PlayFab account is linked to the Facebook identifier.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class FriendInfo
{
/// <summary>
/// Unique lobby identifier of the Game Server Instance to which this player is currently connected.
/// </summary>
public string CurrentMatchmakerLobbyId;
/// <summary>
/// Available Facebook information (if the user and PlayFab friend are also connected in Facebook).
/// </summary>
public UserFacebookInfo FacebookInfo;
/// <summary>
/// PlayFab unique identifier for this friend.
/// </summary>
public string FriendPlayFabId;
/// <summary>
/// Available Game Center information (if the user and PlayFab friend are also connected in Game Center).
/// </summary>
public UserGameCenterInfo GameCenterInfo;
/// <summary>
/// The profile of the user, if requested.
/// </summary>
public PlayerProfileModel Profile;
/// <summary>
/// Available PSN information, if the user and PlayFab friend are both connected to PSN.
/// </summary>
public UserPsnInfo PSNInfo;
/// <summary>
/// Available Steam information (if the user and PlayFab friend are also connected in Steam).
/// </summary>
public UserSteamInfo SteamInfo;
/// <summary>
/// Tags which have been associated with this friend.
/// </summary>
public List<string> Tags;
/// <summary>
/// Title-specific display name for this friend.
/// </summary>
public string TitleDisplayName;
/// <summary>
/// PlayFab unique username for this friend.
/// </summary>
public string Username;
/// <summary>
/// Available Xbox information, if the user and PlayFab friend are both connected to Xbox Live.
/// </summary>
public UserXboxInfo XboxInfo;
}
public enum GameInstanceState
{
Open,
Closed
}
public enum GenericErrorCodes
{
Success,
UnkownError,
InvalidParams,
AccountNotFound,
AccountBanned,
InvalidUsernameOrPassword,
InvalidTitleId,
InvalidEmailAddress,
EmailAddressNotAvailable,
InvalidUsername,
InvalidPassword,
UsernameNotAvailable,
InvalidSteamTicket,
AccountAlreadyLinked,
LinkedAccountAlreadyClaimed,
InvalidFacebookToken,
AccountNotLinked,
FailedByPaymentProvider,
CouponCodeNotFound,
InvalidContainerItem,
ContainerNotOwned,
KeyNotOwned,
InvalidItemIdInTable,
InvalidReceipt,
ReceiptAlreadyUsed,
ReceiptCancelled,
GameNotFound,
GameModeNotFound,
InvalidGoogleToken,
UserIsNotPartOfDeveloper,
InvalidTitleForDeveloper,
TitleNameConflicts,
UserisNotValid,
ValueAlreadyExists,
BuildNotFound,
PlayerNotInGame,
InvalidTicket,
InvalidDeveloper,
InvalidOrderInfo,
RegistrationIncomplete,
InvalidPlatform,
UnknownError,
SteamApplicationNotOwned,
WrongSteamAccount,
TitleNotActivated,
RegistrationSessionNotFound,
NoSuchMod,
FileNotFound,
DuplicateEmail,
ItemNotFound,
ItemNotOwned,
ItemNotRecycleable,
ItemNotAffordable,
InvalidVirtualCurrency,
WrongVirtualCurrency,
WrongPrice,
NonPositiveValue,
InvalidRegion,
RegionAtCapacity,
ServerFailedToStart,
NameNotAvailable,
InsufficientFunds,
InvalidDeviceID,
InvalidPushNotificationToken,
NoRemainingUses,
InvalidPaymentProvider,
PurchaseInitializationFailure,
DuplicateUsername,
InvalidBuyerInfo,
NoGameModeParamsSet,
BodyTooLarge,
ReservedWordInBody,
InvalidTypeInBody,
InvalidRequest,
ReservedEventName,
InvalidUserStatistics,
NotAuthenticated,
StreamAlreadyExists,
ErrorCreatingStream,
StreamNotFound,
InvalidAccount,
PurchaseDoesNotExist,
InvalidPurchaseTransactionStatus,
APINotEnabledForGameClientAccess,
NoPushNotificationARNForTitle,
BuildAlreadyExists,
BuildPackageDoesNotExist,
CustomAnalyticsEventsNotEnabledForTitle,
InvalidSharedGroupId,
NotAuthorized,
MissingTitleGoogleProperties,
InvalidItemProperties,
InvalidPSNAuthCode,
InvalidItemId,
PushNotEnabledForAccount,
PushServiceError,
ReceiptDoesNotContainInAppItems,
ReceiptContainsMultipleInAppItems,
InvalidBundleID,
JavascriptException,
InvalidSessionTicket,
UnableToConnectToDatabase,
InternalServerError,
InvalidReportDate,
ReportNotAvailable,
DatabaseThroughputExceeded,
InvalidGameTicket,
ExpiredGameTicket,
GameTicketDoesNotMatchLobby,
LinkedDeviceAlreadyClaimed,
DeviceAlreadyLinked,
DeviceNotLinked,
PartialFailure,
PublisherNotSet,
ServiceUnavailable,
VersionNotFound,
RevisionNotFound,
InvalidPublisherId,
DownstreamServiceUnavailable,
APINotIncludedInTitleUsageTier,
DAULimitExceeded,
APIRequestLimitExceeded,
InvalidAPIEndpoint,
BuildNotAvailable,
ConcurrentEditError,
ContentNotFound,
CharacterNotFound,
CloudScriptNotFound,
ContentQuotaExceeded,
InvalidCharacterStatistics,
PhotonNotEnabledForTitle,
PhotonApplicationNotFound,
PhotonApplicationNotAssociatedWithTitle,
InvalidEmailOrPassword,
FacebookAPIError,
InvalidContentType,
KeyLengthExceeded,
DataLengthExceeded,
TooManyKeys,
FreeTierCannotHaveVirtualCurrency,
MissingAmazonSharedKey,
AmazonValidationError,
InvalidPSNIssuerId,
PSNInaccessible,
ExpiredAuthToken,
FailedToGetEntitlements,
FailedToConsumeEntitlement,
TradeAcceptingUserNotAllowed,
TradeInventoryItemIsAssignedToCharacter,
TradeInventoryItemIsBundle,
TradeStatusNotValidForCancelling,
TradeStatusNotValidForAccepting,
TradeDoesNotExist,
TradeCancelled,
TradeAlreadyFilled,
TradeWaitForStatusTimeout,
TradeInventoryItemExpired,
TradeMissingOfferedAndAcceptedItems,
TradeAcceptedItemIsBundle,
TradeAcceptedItemIsStackable,
TradeInventoryItemInvalidStatus,
TradeAcceptedCatalogItemInvalid,
TradeAllowedUsersInvalid,
TradeInventoryItemDoesNotExist,
TradeInventoryItemIsConsumed,
TradeInventoryItemIsStackable,
TradeAcceptedItemsMismatch,
InvalidKongregateToken,
FeatureNotConfiguredForTitle,
NoMatchingCatalogItemForReceipt,
InvalidCurrencyCode,
NoRealMoneyPriceForCatalogItem,
TradeInventoryItemIsNotTradable,
TradeAcceptedCatalogItemIsNotTradable,
UsersAlreadyFriends,
LinkedIdentifierAlreadyClaimed,
CustomIdNotLinked,
TotalDataSizeExceeded,
DeleteKeyConflict,
InvalidXboxLiveToken,
ExpiredXboxLiveToken,
ResettableStatisticVersionRequired,
NotAuthorizedByTitle,
NoPartnerEnabled,
InvalidPartnerResponse,
APINotEnabledForGameServerAccess,
StatisticNotFound,
StatisticNameConflict,
StatisticVersionClosedForWrites,
StatisticVersionInvalid,
APIClientRequestRateLimitExceeded,
InvalidJSONContent,
InvalidDropTable,
StatisticVersionAlreadyIncrementedForScheduledInterval,
StatisticCountLimitExceeded,
StatisticVersionIncrementRateExceeded,
ContainerKeyInvalid,
CloudScriptExecutionTimeLimitExceeded,
NoWritePermissionsForEvent,
CloudScriptFunctionArgumentSizeExceeded,
CloudScriptAPIRequestCountExceeded,
CloudScriptAPIRequestError,
CloudScriptHTTPRequestError,
InsufficientGuildRole,
GuildNotFound,
OverLimit,
EventNotFound,
InvalidEventField,
InvalidEventName,
CatalogNotConfigured,
OperationNotSupportedForPlatform,
SegmentNotFound,
StoreNotFound,
InvalidStatisticName,
TitleNotQualifiedForLimit,
InvalidServiceLimitLevel,
ServiceLimitLevelInTransition,
CouponAlreadyRedeemed,
GameServerBuildSizeLimitExceeded,
GameServerBuildCountLimitExceeded,
VirtualCurrencyCountLimitExceeded,
VirtualCurrencyCodeExists,
TitleNewsItemCountLimitExceeded,
InvalidTwitchToken,
TwitchResponseError,
ProfaneDisplayName,
UserAlreadyAdded,
InvalidVirtualCurrencyCode,
VirtualCurrencyCannotBeDeleted,
IdentifierAlreadyClaimed,
IdentifierNotLinked,
InvalidContinuationToken,
ExpiredContinuationToken,
InvalidSegment,
InvalidSessionId,
SessionLogNotFound,
InvalidSearchTerm,
TwoFactorAuthenticationTokenRequired,
GameServerHostCountLimitExceeded,
PlayerTagCountLimitExceeded,
RequestAlreadyRunning,
ActionGroupNotFound,
MaximumSegmentBulkActionJobsRunning,
NoActionsOnPlayersInSegmentJob,
DuplicateStatisticName,
ScheduledTaskNameConflict,
ScheduledTaskCreateConflict,
InvalidScheduledTaskName,
InvalidTaskSchedule,
SteamNotEnabledForTitle,
LimitNotAnUpgradeOption,
NoSecretKeyEnabledForCloudScript,
TaskNotFound,
TaskInstanceNotFound,
InvalidIdentityProviderId,
MisconfiguredIdentityProvider,
InvalidScheduledTaskType,
BillingInformationRequired,
LimitedEditionItemUnavailable,
InvalidAdPlacementAndReward,
AllAdPlacementViewsAlreadyConsumed,
GoogleOAuthNotConfiguredForTitle,
GoogleOAuthError,
UserNotFriend,
InvalidSignature,
InvalidPublicKey,
GoogleOAuthNoIdTokenIncludedInResponse,
StatisticUpdateInProgress,
LeaderboardVersionNotAvailable,
StatisticAlreadyHasPrizeTable,
PrizeTableHasOverlappingRanks,
PrizeTableHasMissingRanks,
PrizeTableRankStartsAtZero,
InvalidStatistic,
ExpressionParseFailure,
ExpressionInvokeFailure,
ExpressionTooLong,
DataUpdateRateExceeded,
RestrictedEmailDomain,
EncryptionKeyDisabled,
EncryptionKeyMissing,
EncryptionKeyBroken,
NoSharedSecretKeyConfigured,
SecretKeyNotFound,
PlayerSecretAlreadyConfigured,
APIRequestsDisabledForTitle,
InvalidSharedSecretKey,
PrizeTableHasNoRanks,
ProfileDoesNotExist,
ContentS3OriginBucketNotConfigured,
InvalidEnvironmentForReceipt,
EncryptedRequestNotAllowed,
SignedRequestNotAllowed,
RequestViewConstraintParamsNotAllowed,
BadPartnerConfiguration,
XboxBPCertificateFailure,
XboxXASSExchangeFailure,
InvalidEntityId,
StatisticValueAggregationOverflow,
EmailMessageFromAddressIsMissing,
EmailMessageToAddressIsMissing,
SmtpServerAuthenticationError,
SmtpServerLimitExceeded,
SmtpServerInsufficientStorage,
SmtpServerCommunicationError,
SmtpServerGeneralFailure,
EmailClientTimeout,
EmailClientCanceledTask,
EmailTemplateMissing,
InvalidHostForTitleId,
EmailConfirmationTokenDoesNotExist,
EmailConfirmationTokenExpired,
AccountDeleted,
PlayerSecretNotConfigured,
InvalidSignatureTime,
NoContactEmailAddressFound,
InvalidAuthToken,
AuthTokenDoesNotExist,
AuthTokenExpired,
AuthTokenAlreadyUsedToResetPassword,
MembershipNameTooLong,
MembershipNotFound,
GoogleServiceAccountInvalid,
GoogleServiceAccountParseFailure,
EntityTokenMissing,
EntityTokenInvalid,
EntityTokenExpired,
EntityTokenRevoked,
InvalidProductForSubscription,
XboxInaccessible,
SubscriptionAlreadyTaken,
SmtpAddonNotEnabled,
APIConcurrentRequestLimitExceeded,
XboxRejectedXSTSExchangeRequest,
VariableNotDefined,
TemplateVersionNotDefined,
FileTooLarge,
TitleDeleted,
TitleContainsUserAccounts,
TitleDeletionPlayerCleanupFailure,
EntityFileOperationPending,
NoEntityFileOperationPending,
EntityProfileVersionMismatch,
TemplateVersionTooOld,
MembershipDefinitionInUse,
PaymentPageNotConfigured,
FailedLoginAttemptRateLimitExceeded,
EntityBlockedByGroup,
RoleDoesNotExist,
EntityIsAlreadyMember,
DuplicateRoleId,
GroupInvitationNotFound,
GroupApplicationNotFound,
OutstandingInvitationAcceptedInstead,
OutstandingApplicationAcceptedInstead,
RoleIsGroupDefaultMember,
RoleIsGroupAdmin,
RoleNameNotAvailable,
GroupNameNotAvailable,
EmailReportAlreadySent,
EmailReportRecipientBlacklisted,
EventNamespaceNotAllowed,
EventEntityNotAllowed,
InvalidEntityType,
NullTokenResultFromAad,
InvalidTokenResultFromAad,
NoValidCertificateForAad,
InvalidCertificateForAad,
DuplicateDropTableId,
MultiplayerServerError,
MultiplayerServerTooManyRequests,
MultiplayerServerNoContent,
MultiplayerServerBadRequest,
MultiplayerServerUnauthorized,
MultiplayerServerForbidden,
MultiplayerServerNotFound,
MultiplayerServerConflict,
MultiplayerServerInternalServerError,
MultiplayerServerUnavailable,
ExplicitContentDetected,
PIIContentDetected,
InvalidScheduledTaskParameter,
PerEntityEventRateLimitExceeded,
TitleDefaultLanguageNotSet,
EmailTemplateMissingDefaultVersion,
FacebookInstantGamesIdNotLinked,
InvalidFacebookInstantGamesSignature,
FacebookInstantGamesAuthNotConfiguredForTitle,
EntityProfileConstraintValidationFailed,
TelemetryIngestionKeyPending,
TelemetryIngestionKeyNotFound,
StatisticTagRequired,
StatisticTagInvalid,
DataIntegrityError,
VirtualCurrencyCannotBeSetToOlderVersion,
VirtualCurrencyMustBeWithinIntegerRange,
EmailTemplateInvalidSyntax,
EmailTemplateMissingCallback,
PushNotificationTemplateInvalidPayload,
InvalidLocalizedPushNotificationLanguage,
MissingLocalizedPushNotificationMessage,
PushNotificationTemplateMissingPlatformPayload,
PushNotificationTemplatePayloadContainsInvalidJson,
PushNotificationTemplateContainsInvalidIosPayload,
PushNotificationTemplateContainsInvalidAndroidPayload,
PushNotificationTemplateIosPayloadMissingNotificationBody,
PushNotificationTemplateAndroidPayloadMissingNotificationBody,
PushNotificationTemplateNotFound,
PushNotificationTemplateMissingDefaultVersion,
PushNotificationTemplateInvalidSyntax,
PushNotificationTemplateNoCustomPayloadForV1,
MatchmakingEntityInvalid,
MatchmakingPlayerAttributesInvalid,
MatchmakingCreateRequestMissing,
MatchmakingCreateRequestCreatorMissing,
MatchmakingCreateRequestCreatorIdMissing,
MatchmakingCreateRequestUserListMissing,
MatchmakingCreateRequestGiveUpAfterInvalid,
MatchmakingTicketIdMissing,
MatchmakingMatchIdMissing,
MatchmakingMatchIdIdMissing,
MatchmakingQueueNameMissing,
MatchmakingTitleIdMissing,
MatchmakingTicketIdIdMissing,
MatchmakingPlayerIdMissing,
MatchmakingJoinRequestUserMissing,
MatchmakingQueueConfigNotFound,
MatchmakingMatchNotFound,
MatchmakingTicketNotFound,
MatchmakingCreateTicketServerIdentityInvalid,
MatchmakingCreateTicketClientIdentityInvalid,
MatchmakingGetTicketUserMismatch,
MatchmakingJoinTicketServerIdentityInvalid,
MatchmakingJoinTicketUserIdentityMismatch,
MatchmakingCancelTicketServerIdentityInvalid,
MatchmakingCancelTicketUserIdentityMismatch,
MatchmakingGetMatchIdentityMismatch,
MatchmakingPlayerIdentityMismatch,
MatchmakingAlreadyJoinedTicket,
MatchmakingTicketAlreadyCompleted,
MatchmakingQueueNameInvalid,
MatchmakingQueueConfigInvalid,
MatchmakingMemberProfileInvalid,
WriteAttemptedDuringExport,
NintendoSwitchDeviceIdNotLinked,
MatchmakingNotEnabled,
MatchmakingGetStatisticsIdentityInvalid,
MatchmakingStatisticsIdMissing,
CannotEnableMultiplayerServersForTitle
}
/// <summary>
/// Request has no paramaters.
/// </summary>
[Serializable]
public class GetAllSegmentsRequest : PlayFabRequestCommon
{
}
[Serializable]
public class GetAllSegmentsResult : PlayFabResultCommon
{
/// <summary>
/// Array of segments for this title.
/// </summary>
public List<GetSegmentResult> Segments;
}
[Serializable]
public class GetCatalogItemsRequest : PlayFabRequestCommon
{
/// <summary>
/// Which catalog is being requested. If null, uses the default catalog.
/// </summary>
public string CatalogVersion;
}
[Serializable]
public class GetCatalogItemsResult : PlayFabResultCommon
{
/// <summary>
/// Array of items which can be purchased.
/// </summary>
public List<CatalogItem> Catalog;
}
/// <summary>
/// Data is stored as JSON key-value pairs. If the Keys parameter is provided,
/// the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set
/// of custom user data will be returned.
/// </summary>
[Serializable]
public class GetCharacterDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// The version that currently exists according to the caller. The call will return the data for all of the keys if the
/// version in the system is greater than this.
/// </summary>
public uint? IfChangedFromDataVersion;
/// <summary>
/// Specific keys to search for in the custom user data.
/// </summary>
public List<string> Keys;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetCharacterDataResult : PlayFabResultCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// User specific data for this title.
/// </summary>
public Dictionary<string,UserDataRecord> Data;
/// <summary>
/// Indicates the current version of the data that has been set. This is incremented with every set call for that type of
/// data (read-only, internal, etc). This version can be provided in Get calls to find updated data.
/// </summary>
public uint DataVersion;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// All items currently in the character inventory will be returned, irrespective of how they were acquired
/// (via purchasing, grants, coupons, etc.). Items that are expired, fully consumed, or are no longer valid are not
/// considered to be
/// in the user's current inventory, and so will not be not included. Also returns their virtual currency balances.
/// </summary>
[Serializable]
public class GetCharacterInventoryRequest : PlayFabRequestCommon
{
/// <summary>
/// Used to limit results to only those from a specific catalog version.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetCharacterInventoryResult : PlayFabResultCommon
{
/// <summary>
/// Unique identifier of the character for this inventory.
/// </summary>
public string CharacterId;
/// <summary>
/// Array of inventory items belonging to the character.
/// </summary>
public List<ItemInstance> Inventory;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Array of virtual currency balance(s) belonging to the character.
/// </summary>
public Dictionary<string,int> VirtualCurrency;
/// <summary>
/// Array of remaining times and timestamps for virtual currencies.
/// </summary>
public Dictionary<string,VirtualCurrencyRechargeTime> VirtualCurrencyRechargeTimes;
}
[Serializable]
public class GetCharacterLeaderboardRequest : PlayFabRequestCommon
{
/// <summary>
/// Optional character type on which to filter the leaderboard entries.
/// </summary>
public string CharacterType;
/// <summary>
/// Maximum number of entries to retrieve.
/// </summary>
public int MaxResultsCount;
/// <summary>
/// First entry in the leaderboard to be retrieved.
/// </summary>
public int StartPosition;
/// <summary>
/// Unique identifier for the title-specific statistic for the leaderboard.
/// </summary>
public string StatisticName;
}
/// <summary>
/// Note that the Position of the character in the results is for the overall leaderboard.
/// </summary>
[Serializable]
public class GetCharacterLeaderboardResult : PlayFabResultCommon
{
/// <summary>
/// Ordered list of leaderboard entries.
/// </summary>
public List<CharacterLeaderboardEntry> Leaderboard;
}
/// <summary>
/// Character statistics are similar to user statistics in that they are numeric values which
/// may only be updated by a server operation, in order to minimize the opportunity for unauthorized changes. In addition to
/// being available for use by the title, the statistics are used for all leaderboard operations in PlayFab.
/// </summary>
[Serializable]
public class GetCharacterStatisticsRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetCharacterStatisticsResult : PlayFabResultCommon
{
/// <summary>
/// Unique identifier of the character for the statistics.
/// </summary>
public string CharacterId;
/// <summary>
/// Character statistics for the requested user.
/// </summary>
public Dictionary<string,int> CharacterStatistics;
/// <summary>
/// PlayFab unique identifier of the user whose character statistics are being returned.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetContentDownloadUrlRequest : PlayFabRequestCommon
{
/// <summary>
/// HTTP method to fetch item - GET or HEAD. Use HEAD when only fetching metadata. Default is GET.
/// </summary>
public string HttpMethod;
/// <summary>
/// Key of the content item to fetch, usually formatted as a path, e.g. images/a.png
/// </summary>
public string Key;
/// <summary>
/// True to download through CDN. CDN provides higher download bandwidth and lower latency. However, if you want the latest,
/// non-cached version of the content during development, set this to false. Default is true.
/// </summary>
public bool? ThruCDN;
}
[Serializable]
public class GetContentDownloadUrlResult : PlayFabResultCommon
{
/// <summary>
/// URL for downloading content via HTTP GET or HEAD method. The URL will expire in approximately one hour.
/// </summary>
public string URL;
}
[Serializable]
public class GetFriendLeaderboardRequest : PlayFabRequestCommon
{
/// <summary>
/// Indicates whether Facebook friends should be included in the response. Default is true.
/// </summary>
public bool? IncludeFacebookFriends;
/// <summary>
/// Indicates whether Steam service friends should be included in the response. Default is true.
/// </summary>
public bool? IncludeSteamFriends;
/// <summary>
/// Maximum number of entries to retrieve.
/// </summary>
public int MaxResultsCount;
/// <summary>
/// The player whose friend leaderboard to get
/// </summary>
public string PlayFabId;
/// <summary>
/// If non-null, this determines which properties of the resulting player profiles to return. For API calls from the client,
/// only the allowed client profile properties for the title may be requested. These allowed properties are configured in
/// the Game Manager "Client Profile Options" tab in the "Settings" section.
/// </summary>
public PlayerProfileViewConstraints ProfileConstraints;
/// <summary>
/// Position in the leaderboard to start this listing (defaults to the first entry).
/// </summary>
public int StartPosition;
/// <summary>
/// Statistic used to rank friends for this leaderboard.
/// </summary>
public string StatisticName;
/// <summary>
/// The version of the leaderboard to get.
/// </summary>
public int? Version;
/// <summary>
/// Xbox token if Xbox friends should be included. Requires Xbox be configured on PlayFab.
/// </summary>
public string XboxToken;
}
[Serializable]
public class GetFriendsListRequest : PlayFabRequestCommon
{
/// <summary>
/// Indicates whether Facebook friends should be included in the response. Default is true.
/// </summary>
public bool? IncludeFacebookFriends;
/// <summary>
/// Indicates whether Steam service friends should be included in the response. Default is true.
/// </summary>
public bool? IncludeSteamFriends;
/// <summary>
/// PlayFab identifier of the player whose friend list to get.
/// </summary>
public string PlayFabId;
/// <summary>
/// If non-null, this determines which properties of the resulting player profiles to return. For API calls from the client,
/// only the allowed client profile properties for the title may be requested. These allowed properties are configured in
/// the Game Manager "Client Profile Options" tab in the "Settings" section.
/// </summary>
public PlayerProfileViewConstraints ProfileConstraints;
/// <summary>
/// Xbox token if Xbox friends should be included. Requires Xbox be configured on PlayFab.
/// </summary>
public string XboxToken;
}
/// <summary>
/// If any additional services are queried for the user's friends, those friends who also have a PlayFab account registered
/// for the title will be returned in the results. For Facebook, user has to have logged into the title's Facebook app
/// recently, and only friends who also plays this game will be included.
/// </summary>
[Serializable]
public class GetFriendsListResult : PlayFabResultCommon
{
/// <summary>
/// Array of friends found.
/// </summary>
public List<FriendInfo> Friends;
}
[Serializable]
public class GetLeaderboardAroundCharacterRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Optional character type on which to filter the leaderboard entries.
/// </summary>
public string CharacterType;
/// <summary>
/// Maximum number of entries to retrieve.
/// </summary>
public int MaxResultsCount;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique identifier for the title-specific statistic for the leaderboard.
/// </summary>
public string StatisticName;
}
/// <summary>
/// Note: When calling 'GetLeaderboardAround...' APIs, the position of the character defaults to 0 when the character does
/// not have the corresponding statistic.
/// </summary>
[Serializable]
public class GetLeaderboardAroundCharacterResult : PlayFabResultCommon
{
/// <summary>
/// Ordered list of leaderboard entries.
/// </summary>
public List<CharacterLeaderboardEntry> Leaderboard;
}
[Serializable]
public class GetLeaderboardAroundUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Maximum number of entries to retrieve.
/// </summary>
public int MaxResultsCount;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// If non-null, this determines which properties of the resulting player profiles to return. For API calls from the client,
/// only the allowed client profile properties for the title may be requested. These allowed properties are configured in
/// the Game Manager "Client Profile Options" tab in the "Settings" section.
/// </summary>
public PlayerProfileViewConstraints ProfileConstraints;
/// <summary>
/// Unique identifier for the title-specific statistic for the leaderboard.
/// </summary>
public string StatisticName;
/// <summary>
/// The version of the leaderboard to get.
/// </summary>
public int? Version;
}
/// <summary>
/// Note: When calling 'GetLeaderboardAround...' APIs, the position of the user defaults to 0 when the user does not have
/// the corresponding statistic.
/// </summary>
[Serializable]
public class GetLeaderboardAroundUserResult : PlayFabResultCommon
{
/// <summary>
/// Ordered listing of users and their positions in the requested leaderboard.
/// </summary>
public List<PlayerLeaderboardEntry> Leaderboard;
/// <summary>
/// The time the next scheduled reset will occur. Null if the leaderboard does not reset on a schedule.
/// </summary>
public DateTime? NextReset;
/// <summary>
/// The version of the leaderboard returned.
/// </summary>
public int Version;
}
[Serializable]
public class GetLeaderboardForUsersCharactersRequest : PlayFabRequestCommon
{
/// <summary>
/// Maximum number of entries to retrieve.
/// </summary>
public int MaxResultsCount;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique identifier for the title-specific statistic for the leaderboard.
/// </summary>
public string StatisticName;
}
/// <summary>
/// Note that the Position of the user in the results is for the overall leaderboard.
/// </summary>
[Serializable]
public class GetLeaderboardForUsersCharactersResult : PlayFabResultCommon
{
/// <summary>
/// Ordered list of leaderboard entries.
/// </summary>
public List<CharacterLeaderboardEntry> Leaderboard;
}
[Serializable]
public class GetLeaderboardRequest : PlayFabRequestCommon
{
/// <summary>
/// Maximum number of entries to retrieve.
/// </summary>
public int MaxResultsCount;
/// <summary>
/// If non-null, this determines which properties of the resulting player profiles to return. For API calls from the client,
/// only the allowed client profile properties for the title may be requested. These allowed properties are configured in
/// the Game Manager "Client Profile Options" tab in the "Settings" section.
/// </summary>
public PlayerProfileViewConstraints ProfileConstraints;
/// <summary>
/// First entry in the leaderboard to be retrieved.
/// </summary>
public int StartPosition;
/// <summary>
/// Unique identifier for the title-specific statistic for the leaderboard.
/// </summary>
public string StatisticName;
/// <summary>
/// The version of the leaderboard to get.
/// </summary>
public int? Version;
}
/// <summary>
/// Note that the Position of the user in the results is for the overall leaderboard.
/// </summary>
[Serializable]
public class GetLeaderboardResult : PlayFabResultCommon
{
/// <summary>
/// Ordered listing of users and their positions in the requested leaderboard.
/// </summary>
public List<PlayerLeaderboardEntry> Leaderboard;
/// <summary>
/// The time the next scheduled reset will occur. Null if the leaderboard does not reset on a schedule.
/// </summary>
public DateTime? NextReset;
/// <summary>
/// The version of the leaderboard returned.
/// </summary>
public int Version;
}
[Serializable]
public class GetPlayerCombinedInfoRequest : PlayFabRequestCommon
{
/// <summary>
/// Flags for which pieces of info to return for the user.
/// </summary>
public GetPlayerCombinedInfoRequestParams InfoRequestParameters;
/// <summary>
/// PlayFabId of the user whose data will be returned
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetPlayerCombinedInfoRequestParams
{
/// <summary>
/// Whether to get character inventories. Defaults to false.
/// </summary>
public bool GetCharacterInventories;
/// <summary>
/// Whether to get the list of characters. Defaults to false.
/// </summary>
public bool GetCharacterList;
/// <summary>
/// Whether to get player profile. Defaults to false.
/// </summary>
public bool GetPlayerProfile;
/// <summary>
/// Whether to get player statistics. Defaults to false.
/// </summary>
public bool GetPlayerStatistics;
/// <summary>
/// Whether to get title data. Defaults to false.
/// </summary>
public bool GetTitleData;
/// <summary>
/// Whether to get the player's account Info. Defaults to false
/// </summary>
public bool GetUserAccountInfo;
/// <summary>
/// Whether to get the player's custom data. Defaults to false
/// </summary>
public bool GetUserData;
/// <summary>
/// Whether to get the player's inventory. Defaults to false
/// </summary>
public bool GetUserInventory;
/// <summary>
/// Whether to get the player's read only data. Defaults to false
/// </summary>
public bool GetUserReadOnlyData;
/// <summary>
/// Whether to get the player's virtual currency balances. Defaults to false
/// </summary>
public bool GetUserVirtualCurrency;
/// <summary>
/// Specific statistics to retrieve. Leave null to get all keys. Has no effect if GetPlayerStatistics is false
/// </summary>
public List<string> PlayerStatisticNames;
/// <summary>
/// Specifies the properties to return from the player profile. Defaults to returning the player's display name.
/// </summary>
public PlayerProfileViewConstraints ProfileConstraints;
/// <summary>
/// Specific keys to search for in the custom data. Leave null to get all keys. Has no effect if GetTitleData is false
/// </summary>
public List<string> TitleDataKeys;
/// <summary>
/// Specific keys to search for in the custom data. Leave null to get all keys. Has no effect if GetUserData is false
/// </summary>
public List<string> UserDataKeys;
/// <summary>
/// Specific keys to search for in the custom data. Leave null to get all keys. Has no effect if GetUserReadOnlyData is
/// false
/// </summary>
public List<string> UserReadOnlyDataKeys;
}
[Serializable]
public class GetPlayerCombinedInfoResult : PlayFabResultCommon
{
/// <summary>
/// Results for requested info.
/// </summary>
public GetPlayerCombinedInfoResultPayload InfoResultPayload;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetPlayerCombinedInfoResultPayload
{
/// <summary>
/// Account information for the user. This is always retrieved.
/// </summary>
public UserAccountInfo AccountInfo;
/// <summary>
/// Inventories for each character for the user.
/// </summary>
public List<CharacterInventory> CharacterInventories;
/// <summary>
/// List of characters for the user.
/// </summary>
public List<CharacterResult> CharacterList;
/// <summary>
/// The profile of the players. This profile is not guaranteed to be up-to-date. For a new player, this profile will not
/// exist.
/// </summary>
public PlayerProfileModel PlayerProfile;
/// <summary>
/// List of statistics for this player.
/// </summary>
public List<StatisticValue> PlayerStatistics;
/// <summary>
/// Title data for this title.
/// </summary>
public Dictionary<string,string> TitleData;
/// <summary>
/// User specific custom data.
/// </summary>
public Dictionary<string,UserDataRecord> UserData;
/// <summary>
/// The version of the UserData that was returned.
/// </summary>
public uint UserDataVersion;
/// <summary>
/// Array of inventory items in the user's current inventory.
/// </summary>
public List<ItemInstance> UserInventory;
/// <summary>
/// User specific read-only data.
/// </summary>
public Dictionary<string,UserDataRecord> UserReadOnlyData;
/// <summary>
/// The version of the Read-Only UserData that was returned.
/// </summary>
public uint UserReadOnlyDataVersion;
/// <summary>
/// Dictionary of virtual currency balance(s) belonging to the user.
/// </summary>
public Dictionary<string,int> UserVirtualCurrency;
/// <summary>
/// Dictionary of remaining times and timestamps for virtual currencies.
/// </summary>
public Dictionary<string,VirtualCurrencyRechargeTime> UserVirtualCurrencyRechargeTimes;
}
/// <summary>
/// This API allows for access to details regarding a user in the PlayFab service, usually for purposes of
/// customer support. Note that data returned may be Personally Identifying Information (PII), such as email address, and so
/// care should be
/// taken in how this data is stored and managed. Since this call will always return the relevant information for users who
/// have accessed
/// the title, the recommendation is to not store this data locally.
/// </summary>
[Serializable]
public class GetPlayerProfileRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// If non-null, this determines which properties of the resulting player profiles to return. For API calls from the client,
/// only the allowed client profile properties for the title may be requested. These allowed properties are configured in
/// the Game Manager "Client Profile Options" tab in the "Settings" section.
/// </summary>
public PlayerProfileViewConstraints ProfileConstraints;
}
[Serializable]
public class GetPlayerProfileResult : PlayFabResultCommon
{
/// <summary>
/// The profile of the player. This profile is not guaranteed to be up-to-date. For a new player, this profile will not
/// exist.
/// </summary>
public PlayerProfileModel PlayerProfile;
}
[Serializable]
public class GetPlayerSegmentsResult : PlayFabResultCommon
{
/// <summary>
/// Array of segments the requested player currently belongs to.
/// </summary>
public List<GetSegmentResult> Segments;
}
/// <summary>
/// Initial request must contain at least a Segment ID. Subsequent requests must contain the Segment ID as well as the
/// Continuation Token. Failure to send the Continuation Token will result in a new player segment list being generated.
/// Each time the Continuation Token is passed in the length of the Total Seconds to Live is refreshed. If too much time
/// passes between requests to the point that a subsequent request is past the Total Seconds to Live an error will be
/// returned and paging will be terminated. This API is resource intensive and should not be used in scenarios which might
/// generate high request volumes. Only one request to this API at a time should be made per title. Concurrent requests to
/// the API may be rejected with the APIConcurrentRequestLimitExceeded error.
/// </summary>
[Serializable]
public class GetPlayersInSegmentRequest : PlayFabRequestCommon
{
/// <summary>
/// Continuation token if retrieving subsequent pages of results.
/// </summary>
public string ContinuationToken;
/// <summary>
/// Maximum number of profiles to load. Default is 1,000. Maximum is 10,000.
/// </summary>
public uint? MaxBatchSize;
/// <summary>
/// Number of seconds to keep the continuation token active. After token expiration it is not possible to continue paging
/// results. Default is 300 (5 minutes). Maximum is 1,800 (30 minutes).
/// </summary>
public uint? SecondsToLive;
/// <summary>
/// Unique identifier for this segment.
/// </summary>
public string SegmentId;
}
[Serializable]
public class GetPlayersInSegmentResult : PlayFabResultCommon
{
/// <summary>
/// Continuation token to use to retrieve subsequent pages of results. If token returns null there are no more results.
/// </summary>
public string ContinuationToken;
/// <summary>
/// Array of player profiles in this segment.
/// </summary>
public List<PlayerProfile> PlayerProfiles;
/// <summary>
/// Count of profiles matching this segment.
/// </summary>
public int ProfilesInSegment;
}
[Serializable]
public class GetPlayersSegmentsRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetPlayerStatisticsRequest : PlayFabRequestCommon
{
/// <summary>
/// user for whom statistics are being requested
/// </summary>
public string PlayFabId;
/// <summary>
/// statistics to return
/// </summary>
public List<string> StatisticNames;
/// <summary>
/// statistics to return, if StatisticNames is not set (only statistics which have a version matching that provided will be
/// returned)
/// </summary>
public List<StatisticNameVersion> StatisticNameVersions;
}
/// <summary>
/// In addition to being available for use by the title, the statistics are used for all leaderboard operations in PlayFab.
/// </summary>
[Serializable]
public class GetPlayerStatisticsResult : PlayFabResultCommon
{
/// <summary>
/// PlayFab unique identifier of the user whose statistics are being returned
/// </summary>
public string PlayFabId;
/// <summary>
/// User statistics for the requested user.
/// </summary>
public List<StatisticValue> Statistics;
}
[Serializable]
public class GetPlayerStatisticVersionsRequest : PlayFabRequestCommon
{
/// <summary>
/// unique name of the statistic
/// </summary>
public string StatisticName;
}
[Serializable]
public class GetPlayerStatisticVersionsResult : PlayFabResultCommon
{
/// <summary>
/// version change history of the statistic
/// </summary>
public List<PlayerStatisticVersion> StatisticVersions;
}
/// <summary>
/// This API will return a list of canonical tags which includes both namespace and tag's name. If namespace is not
/// provided, the result is a list of all canonical tags. TagName can be used for segmentation and Namespace is limited to
/// 128 characters.
/// </summary>
[Serializable]
public class GetPlayerTagsRequest : PlayFabRequestCommon
{
/// <summary>
/// Optional namespace to filter results by
/// </summary>
public string Namespace;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetPlayerTagsResult : PlayFabResultCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Canonical tags (including namespace and tag's name) for the requested user
/// </summary>
public List<string> Tags;
}
[Serializable]
public class GetPlayFabIDsFromFacebookIDsRequest : PlayFabRequestCommon
{
/// <summary>
/// Array of unique Facebook identifiers for which the title needs to get PlayFab identifiers.
/// </summary>
public List<string> FacebookIDs;
}
/// <summary>
/// For Facebook identifiers which have not been linked to PlayFab accounts, null will be returned.
/// </summary>
[Serializable]
public class GetPlayFabIDsFromFacebookIDsResult : PlayFabResultCommon
{
/// <summary>
/// Mapping of Facebook identifiers to PlayFab identifiers.
/// </summary>
public List<FacebookPlayFabIdPair> Data;
}
[Serializable]
public class GetPlayFabIDsFromFacebookInstantGamesIdsRequest : PlayFabRequestCommon
{
/// <summary>
/// Array of unique Facebook Instant Games identifiers for which the title needs to get PlayFab identifiers.
/// </summary>
public List<string> FacebookInstantGamesIds;
}
/// <summary>
/// For Facebook Instant Games identifiers which have not been linked to PlayFab accounts, null will be returned.
/// </summary>
[Serializable]
public class GetPlayFabIDsFromFacebookInstantGamesIdsResult : PlayFabResultCommon
{
/// <summary>
/// Mapping of Facebook Instant Games identifiers to PlayFab identifiers.
/// </summary>
public List<FacebookInstantGamesPlayFabIdPair> Data;
}
[Serializable]
public class GetPlayFabIDsFromNintendoSwitchDeviceIdsRequest : PlayFabRequestCommon
{
/// <summary>
/// Array of unique Nintendo Switch Device identifiers for which the title needs to get PlayFab identifiers.
/// </summary>
public List<string> NintendoSwitchDeviceIds;
}
/// <summary>
/// For Nintendo Switch Device identifiers which have not been linked to PlayFab accounts, null will be returned.
/// </summary>
[Serializable]
public class GetPlayFabIDsFromNintendoSwitchDeviceIdsResult : PlayFabResultCommon
{
/// <summary>
/// Mapping of Nintendo Switch Device identifiers to PlayFab identifiers.
/// </summary>
public List<NintendoSwitchPlayFabIdPair> Data;
}
[Serializable]
public class GetPlayFabIDsFromSteamIDsRequest : PlayFabRequestCommon
{
/// <summary>
/// Array of unique Steam identifiers (Steam profile IDs) for which the title needs to get PlayFab identifiers.
/// </summary>
public List<string> SteamStringIDs;
}
/// <summary>
/// For Steam identifiers which have not been linked to PlayFab accounts, null will be returned.
/// </summary>
[Serializable]
public class GetPlayFabIDsFromSteamIDsResult : PlayFabResultCommon
{
/// <summary>
/// Mapping of Steam identifiers to PlayFab identifiers.
/// </summary>
public List<SteamPlayFabIdPair> Data;
}
[Serializable]
public class GetPlayFabIDsFromXboxLiveIDsRequest : PlayFabRequestCommon
{
/// <summary>
/// The ID of Xbox Live sandbox.
/// </summary>
public string Sandbox;
/// <summary>
/// Array of unique Xbox Live account identifiers for which the title needs to get PlayFab identifiers.
/// </summary>
public List<string> XboxLiveAccountIDs;
}
/// <summary>
/// For XboxLive identifiers which have not been linked to PlayFab accounts, null will be returned.
/// </summary>
[Serializable]
public class GetPlayFabIDsFromXboxLiveIDsResult : PlayFabResultCommon
{
/// <summary>
/// Mapping of PlayStation Network identifiers to PlayFab identifiers.
/// </summary>
public List<XboxLiveAccountPlayFabIdPair> Data;
}
/// <summary>
/// This API is designed to return publisher-specific values which can be read, but not written to, by the client. This data
/// is shared across all
/// titles assigned to a particular publisher, and can be used for cross-game coordination. Only titles assigned to a
/// publisher can use this API.
/// For more information email devrel@playfab.com. Note that there may up to a minute delay in between updating title data
/// and this API call returning
/// the newest value.
/// </summary>
[Serializable]
public class GetPublisherDataRequest : PlayFabRequestCommon
{
/// <summary>
/// array of keys to get back data from the Publisher data blob, set by the admin tools
/// </summary>
public List<string> Keys;
}
[Serializable]
public class GetPublisherDataResult : PlayFabResultCommon
{
/// <summary>
/// a dictionary object of key / value pairs
/// </summary>
public Dictionary<string,string> Data;
}
[Serializable]
public class GetRandomResultTablesRequest : PlayFabRequestCommon
{
/// <summary>
/// Specifies the catalog version that should be used to retrieve the Random Result Tables. If unspecified, uses
/// default/primary catalog.
/// </summary>
public string CatalogVersion;
/// <summary>
/// The unique identifier of the Random Result Table to use.
/// </summary>
public List<string> TableIDs;
}
/// <summary>
/// Note that if a specified Random Result Table contains no entries, or does not exist in the catalog, an InvalidDropTable
/// error will be returned.
/// </summary>
[Serializable]
public class GetRandomResultTablesResult : PlayFabResultCommon
{
/// <summary>
/// array of random result tables currently available
/// </summary>
public Dictionary<string,RandomResultTableListing> Tables;
}
[Serializable]
public class GetSegmentResult : PlayFabResultCommon
{
/// <summary>
/// Identifier of the segments AB Test, if it is attached to one.
/// </summary>
public string ABTestParent;
/// <summary>
/// Unique identifier for this segment.
/// </summary>
public string Id;
/// <summary>
/// Segment name.
/// </summary>
public string Name;
}
[Serializable]
public class GetServerCustomIDsFromPlayFabIDsRequest : PlayFabRequestCommon
{
/// <summary>
/// Array of unique PlayFab player identifiers for which the title needs to get server custom identifiers. Cannot contain
/// more than 25 identifiers.
/// </summary>
public List<string> PlayFabIDs;
}
/// <summary>
/// For a PlayFab account that isn't associated with a server custom identity, ServerCustomId will be null.
/// </summary>
[Serializable]
public class GetServerCustomIDsFromPlayFabIDsResult : PlayFabResultCommon
{
/// <summary>
/// Mapping of server custom player identifiers to PlayFab identifiers.
/// </summary>
public List<ServerCustomIDPlayFabIDPair> Data;
}
[Serializable]
public class GetSharedGroupDataRequest : PlayFabRequestCommon
{
/// <summary>
/// If true, return the list of all members of the shared group.
/// </summary>
public bool? GetMembers;
/// <summary>
/// Specific keys to retrieve from the shared group (if not specified, all keys will be returned, while an empty array
/// indicates that no keys should be returned).
/// </summary>
public List<string> Keys;
/// <summary>
/// Unique identifier for the shared group.
/// </summary>
public string SharedGroupId;
}
[Serializable]
public class GetSharedGroupDataResult : PlayFabResultCommon
{
/// <summary>
/// Data for the requested keys.
/// </summary>
public Dictionary<string,SharedGroupDataRecord> Data;
/// <summary>
/// List of PlayFabId identifiers for the members of this group, if requested.
/// </summary>
public List<string> Members;
}
/// <summary>
/// This query retrieves the current time from one of the servers in PlayFab. Please note that due to clock drift between
/// servers,
/// there is a potential variance of up to 5 seconds.
/// </summary>
[Serializable]
public class GetTimeRequest : PlayFabRequestCommon
{
}
/// <summary>
/// Time is always returned as Coordinated Universal Time (UTC).
/// </summary>
[Serializable]
public class GetTimeResult : PlayFabResultCommon
{
/// <summary>
/// Current server time when the request was received, in UTC
/// </summary>
public DateTime Time;
}
/// <summary>
/// This API is designed to return title specific values which can be read, but not written to, by the client. For example,
/// a developer
/// could choose to store values which modify the user experience, such as enemy spawn rates, weapon strengths, movement
/// speeds, etc. This allows a developer to update
/// the title without the need to create, test, and ship a new build. Note that there may up to a minute delay in between
/// updating title data and this API call returning
/// the newest value.
/// </summary>
[Serializable]
public class GetTitleDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Specific keys to search for in the title data (leave null to get all keys)
/// </summary>
public List<string> Keys;
}
[Serializable]
public class GetTitleDataResult : PlayFabResultCommon
{
/// <summary>
/// a dictionary object of key / value pairs
/// </summary>
public Dictionary<string,string> Data;
}
[Serializable]
public class GetTitleNewsRequest : PlayFabRequestCommon
{
/// <summary>
/// Limits the results to the last n entries. Defaults to 10 if not set.
/// </summary>
public int? Count;
}
[Serializable]
public class GetTitleNewsResult : PlayFabResultCommon
{
/// <summary>
/// Array of news items.
/// </summary>
public List<TitleNewsItem> News;
}
/// <summary>
/// This API allows for access to details regarding a user in the PlayFab service, usually for purposes of
/// customer support. Note that data returned may be Personally Identifying Information (PII), such as email address, and so
/// care should be
/// taken in how this data is stored and managed. Since this call will always return the relevant information for users who
/// have accessed
/// the title, the recommendation is to not store this data locally.
/// </summary>
[Serializable]
public class GetUserAccountInfoRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetUserAccountInfoResult : PlayFabResultCommon
{
/// <summary>
/// Account details for the user whose information was requested.
/// </summary>
public UserAccountInfo UserInfo;
}
/// <summary>
/// Get all bans for a user, including inactive and expired bans.
/// </summary>
[Serializable]
public class GetUserBansRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetUserBansResult : PlayFabResultCommon
{
/// <summary>
/// Information about the bans
/// </summary>
public List<BanInfo> BanData;
}
/// <summary>
/// Data is stored as JSON key-value pairs. If the Keys parameter is provided,
/// the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom
/// user
/// data will be returned.
/// </summary>
[Serializable]
public class GetUserDataRequest : PlayFabRequestCommon
{
/// <summary>
/// The version that currently exists according to the caller. The call will return the data for all of the keys if the
/// version in the system is greater than this.
/// </summary>
public uint? IfChangedFromDataVersion;
/// <summary>
/// Specific keys to search for in the custom user data.
/// </summary>
public List<string> Keys;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetUserDataResult : PlayFabResultCommon
{
/// <summary>
/// User specific data for this title.
/// </summary>
public Dictionary<string,UserDataRecord> Data;
/// <summary>
/// Indicates the current version of the data that has been set. This is incremented with every set call for that type of
/// data (read-only, internal, etc). This version can be provided in Get calls to find updated data.
/// </summary>
public uint DataVersion;
/// <summary>
/// PlayFab unique identifier of the user whose custom data is being returned.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// All items currently in the user inventory will be returned, irrespective of how they were acquired
/// (via purchasing, grants, coupons, etc.). Items that are expired, fully consumed, or are no longer valid are not
/// considered to be
/// in the user's current inventory, and so will not be not included.
/// </summary>
[Serializable]
public class GetUserInventoryRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GetUserInventoryResult : PlayFabResultCommon
{
/// <summary>
/// Array of inventory items belonging to the user.
/// </summary>
public List<ItemInstance> Inventory;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Array of virtual currency balance(s) belonging to the user.
/// </summary>
public Dictionary<string,int> VirtualCurrency;
/// <summary>
/// Array of remaining times and timestamps for virtual currencies.
/// </summary>
public Dictionary<string,VirtualCurrencyRechargeTime> VirtualCurrencyRechargeTimes;
}
/// <summary>
/// Grants a character to the user of the type and name specified in the request.
/// </summary>
[Serializable]
public class GrantCharacterToUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Non-unique display name of the character being granted (1-20 characters in length).
/// </summary>
public string CharacterName;
/// <summary>
/// Type of the character being granted; statistics can be sliced based on this value.
/// </summary>
public string CharacterType;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GrantCharacterToUserResult : PlayFabResultCommon
{
/// <summary>
/// Unique identifier tagged to this character.
/// </summary>
public string CharacterId;
}
/// <summary>
/// Result of granting an item to a user
/// </summary>
[Serializable]
public class GrantedItemInstance
{
/// <summary>
/// Game specific comment associated with this instance when it was added to the user inventory.
/// </summary>
public string Annotation;
/// <summary>
/// Array of unique items that were awarded when this catalog item was purchased.
/// </summary>
public List<string> BundleContents;
/// <summary>
/// Unique identifier for the parent inventory item, as defined in the catalog, for object which were added from a bundle or
/// container.
/// </summary>
public string BundleParent;
/// <summary>
/// Catalog version for the inventory item, when this instance was created.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// A set of custom key-value pairs on the inventory item.
/// </summary>
public Dictionary<string,string> CustomData;
/// <summary>
/// CatalogItem.DisplayName at the time this item was purchased.
/// </summary>
public string DisplayName;
/// <summary>
/// Timestamp for when this instance will expire.
/// </summary>
public DateTime? Expiration;
/// <summary>
/// Class name for the inventory item, as defined in the catalog.
/// </summary>
public string ItemClass;
/// <summary>
/// Unique identifier for the inventory item, as defined in the catalog.
/// </summary>
public string ItemId;
/// <summary>
/// Unique item identifier for this specific instance of the item.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Timestamp for when this instance was purchased.
/// </summary>
public DateTime? PurchaseDate;
/// <summary>
/// Total number of remaining uses, if this is a consumable item.
/// </summary>
public int? RemainingUses;
/// <summary>
/// Result of this operation.
/// </summary>
public bool Result;
/// <summary>
/// Currency type for the cost of the catalog item.
/// </summary>
public string UnitCurrency;
/// <summary>
/// Cost of the catalog item in the given currency.
/// </summary>
public uint UnitPrice;
/// <summary>
/// The number of uses that were added or removed to this item in this call.
/// </summary>
public int? UsesIncrementedBy;
}
/// <summary>
/// This function directly adds inventory items to the character's inventories. As
/// a result of this operations, the user will not be charged any transaction fee, regardless of the inventory item
/// catalog definition. Please note that the processing time for inventory grants and purchases increases fractionally
/// the more items are in the inventory, and the more items are in the grant/purchase operation.
/// </summary>
[Serializable]
public class GrantItemsToCharacterRequest : PlayFabRequestCommon
{
/// <summary>
/// String detailing any additional information concerning this operation.
/// </summary>
public string Annotation;
/// <summary>
/// Catalog version from which items are to be granted.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Array of itemIds to grant to the user.
/// </summary>
public List<string> ItemIds;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class GrantItemsToCharacterResult : PlayFabResultCommon
{
/// <summary>
/// Array of items granted to users.
/// </summary>
public List<GrantedItemInstance> ItemGrantResults;
}
/// <summary>
/// This function directly adds inventory items to the user's inventories. As a result of this operations, the user
/// will not be charged any transaction fee, regardless of the inventory item catalog definition. Please note that the
/// processing time for
/// inventory grants and purchases increases fractionally the more items are in the inventory, and the more items are in the
/// grant/purchase
/// operation.
/// </summary>
[Serializable]
public class GrantItemsToUserRequest : PlayFabRequestCommon
{
/// <summary>
/// String detailing any additional information concerning this operation.
/// </summary>
public string Annotation;
/// <summary>
/// Catalog version from which items are to be granted.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Array of itemIds to grant to the user.
/// </summary>
public List<string> ItemIds;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// Please note that the order of the items in the response may not match the order of items in the request.
/// </summary>
[Serializable]
public class GrantItemsToUserResult : PlayFabResultCommon
{
/// <summary>
/// Array of items granted to users.
/// </summary>
public List<GrantedItemInstance> ItemGrantResults;
}
/// <summary>
/// This function directly adds inventory items to user inventories. As a result of this operations, the user
/// will not be charged any transaction fee, regardless of the inventory item catalog definition. Please note that the
/// processing time for
/// inventory grants and purchases increases fractionally the more items are in the inventory, and the more items are in the
/// grant/purchase
/// operation.
/// </summary>
[Serializable]
public class GrantItemsToUsersRequest : PlayFabRequestCommon
{
/// <summary>
/// Catalog version from which items are to be granted.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Array of items to grant and the users to whom the items are to be granted.
/// </summary>
public List<ItemGrant> ItemGrants;
}
/// <summary>
/// Please note that the order of the items in the response may not match the order of items in the request.
/// </summary>
[Serializable]
public class GrantItemsToUsersResult : PlayFabResultCommon
{
/// <summary>
/// Array of items granted to users.
/// </summary>
public List<GrantedItemInstance> ItemGrantResults;
}
[Serializable]
public class ItemGrant
{
/// <summary>
/// String detailing any additional information concerning this operation.
/// </summary>
public string Annotation;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Key-value pairs to be written to the custom data. Note that keys are trimmed of whitespace, are limited in size, and may
/// not begin with a '!' character or be null.
/// </summary>
public Dictionary<string,string> Data;
/// <summary>
/// Unique identifier of the catalog item to be granted to the user.
/// </summary>
public string ItemId;
/// <summary>
/// Optional list of Data-keys to remove from UserData. Some SDKs cannot insert null-values into Data due to language
/// constraints. Use this to delete the keys directly.
/// </summary>
public List<string> KeysToRemove;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// A unique instance of an item in a user's inventory. Note, to retrieve additional information for an item instance (such
/// as Tags, Description, or Custom Data that are set on the root catalog item), a call to GetCatalogItems is required. The
/// Item ID of the instance can then be matched to a catalog entry, which contains the additional information. Also note
/// that Custom Data is only set here from a call to UpdateUserInventoryItemCustomData.
/// </summary>
[Serializable]
public class ItemInstance
{
/// <summary>
/// Game specific comment associated with this instance when it was added to the user inventory.
/// </summary>
public string Annotation;
/// <summary>
/// Array of unique items that were awarded when this catalog item was purchased.
/// </summary>
public List<string> BundleContents;
/// <summary>
/// Unique identifier for the parent inventory item, as defined in the catalog, for object which were added from a bundle or
/// container.
/// </summary>
public string BundleParent;
/// <summary>
/// Catalog version for the inventory item, when this instance was created.
/// </summary>
public string CatalogVersion;
/// <summary>
/// A set of custom key-value pairs on the inventory item.
/// </summary>
public Dictionary<string,string> CustomData;
/// <summary>
/// CatalogItem.DisplayName at the time this item was purchased.
/// </summary>
public string DisplayName;
/// <summary>
/// Timestamp for when this instance will expire.
/// </summary>
public DateTime? Expiration;
/// <summary>
/// Class name for the inventory item, as defined in the catalog.
/// </summary>
public string ItemClass;
/// <summary>
/// Unique identifier for the inventory item, as defined in the catalog.
/// </summary>
public string ItemId;
/// <summary>
/// Unique item identifier for this specific instance of the item.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Timestamp for when this instance was purchased.
/// </summary>
public DateTime? PurchaseDate;
/// <summary>
/// Total number of remaining uses, if this is a consumable item.
/// </summary>
public int? RemainingUses;
/// <summary>
/// Currency type for the cost of the catalog item.
/// </summary>
public string UnitCurrency;
/// <summary>
/// Cost of the catalog item in the given currency.
/// </summary>
public uint UnitPrice;
/// <summary>
/// The number of uses that were added or removed to this item in this call.
/// </summary>
public int? UsesIncrementedBy;
}
[Serializable]
public class LinkedPlatformAccountModel
{
/// <summary>
/// Linked account email of the user on the platform, if available
/// </summary>
public string Email;
/// <summary>
/// Authentication platform
/// </summary>
public LoginIdentityProvider? Platform;
/// <summary>
/// Unique account identifier of the user on the platform
/// </summary>
public string PlatformUserId;
/// <summary>
/// Linked account username of the user on the platform, if available
/// </summary>
public string Username;
}
[Serializable]
public class LinkXboxAccountRequest : PlayFabRequestCommon
{
/// <summary>
/// If another user is already linked to the account, unlink the other user and re-link.
/// </summary>
public bool? ForceLink;
/// <summary>
/// Unique PlayFab identifier for a user, or null if no PlayFab account is linked to the Xbox Live identifier.
/// </summary>
public string PlayFabId;
/// <summary>
/// Token provided by the Xbox Live SDK/XDK method GetTokenAndSignatureAsync("POST", "https://playfabapi.com", "").
/// </summary>
public string XboxToken;
}
[Serializable]
public class LinkXboxAccountResult : PlayFabResultCommon
{
}
/// <summary>
/// Returns a list of every character that currently belongs to a user.
/// </summary>
[Serializable]
public class ListUsersCharactersRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class ListUsersCharactersResult : PlayFabResultCommon
{
/// <summary>
/// The requested list of characters.
/// </summary>
public List<CharacterResult> Characters;
}
[Serializable]
public class LocationModel
{
/// <summary>
/// City name.
/// </summary>
public string City;
/// <summary>
/// The two-character continent code for this location
/// </summary>
public ContinentCode? ContinentCode;
/// <summary>
/// The two-character ISO 3166-1 country code for the country associated with the location
/// </summary>
public CountryCode? CountryCode;
/// <summary>
/// Latitude coordinate of the geographic location.
/// </summary>
public double? Latitude;
/// <summary>
/// Longitude coordinate of the geographic location.
/// </summary>
public double? Longitude;
}
public enum LoginIdentityProvider
{
Unknown,
PlayFab,
Custom,
GameCenter,
GooglePlay,
Steam,
XBoxLive,
PSN,
Kongregate,
Facebook,
IOSDevice,
AndroidDevice,
Twitch,
WindowsHello,
GameServer,
CustomServer,
NintendoSwitch,
FacebookInstantGames,
OpenIdConnect
}
[Serializable]
public class LoginWithServerCustomIdRequest : PlayFabRequestCommon
{
/// <summary>
/// Automatically create a PlayFab account if one is not currently linked to this ID.
/// </summary>
public bool? CreateAccount;
/// <summary>
/// Flags for which pieces of info to return for the user.
/// </summary>
public GetPlayerCombinedInfoRequestParams InfoRequestParameters;
/// <summary>
/// Formerly triggered an Entity login with a normal client login. This is now automatic, and always-on.
/// </summary>
[Obsolete("No longer available", true)]
public bool? LoginTitlePlayerAccountEntity;
/// <summary>
/// Player secret that is used to verify API request signatures (Enterprise Only).
/// </summary>
public string PlayerSecret;
/// <summary>
/// The backend server identifier for this player.
/// </summary>
public string ServerCustomId;
}
/// <summary>
/// If this is the first time a user has signed in with the Xbox Live account and CreateAccount
/// is set to true, a new PlayFab account will be created and linked to the Xbox Live account. In this case, no email or
/// username will be
/// associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the Xbox Live account, an error
/// indicating this will
/// be returned, so that the title can guide the user through creation of a PlayFab account.
/// </summary>
[Serializable]
public class LoginWithXboxRequest : PlayFabRequestCommon
{
/// <summary>
/// Automatically create a PlayFab account if one is not currently linked to this ID.
/// </summary>
public bool? CreateAccount;
/// <summary>
/// Flags for which pieces of info to return for the user.
/// </summary>
public GetPlayerCombinedInfoRequestParams InfoRequestParameters;
/// <summary>
/// Formerly triggered an Entity login with a normal client login. This is now automatic, and always-on.
/// </summary>
[Obsolete("No longer available", true)]
public bool? LoginTitlePlayerAccountEntity;
/// <summary>
/// Token provided by the Xbox Live SDK/XDK method GetTokenAndSignatureAsync("POST", "https://playfabapi.com", "").
/// </summary>
public string XboxToken;
}
[Serializable]
public class LogStatement
{
/// <summary>
/// Optional object accompanying the message as contextual information
/// </summary>
public object Data;
/// <summary>
/// 'Debug', 'Info', or 'Error'
/// </summary>
public string Level;
public string Message;
}
[Serializable]
public class MembershipModel
{
/// <summary>
/// Whether this membership is active. That is, whether the MembershipExpiration time has been reached.
/// </summary>
public bool IsActive;
/// <summary>
/// The time this membership expires
/// </summary>
public DateTime MembershipExpiration;
/// <summary>
/// The id of the membership
/// </summary>
public string MembershipId;
/// <summary>
/// Membership expirations can be explicitly overridden (via game manager or the admin api). If this membership has been
/// overridden, this will be the new expiration time.
/// </summary>
public DateTime? OverrideExpiration;
/// <summary>
/// The list of subscriptions that this player has for this membership
/// </summary>
public List<SubscriptionModel> Subscriptions;
}
[Serializable]
public class ModifyCharacterVirtualCurrencyResult : PlayFabResultCommon
{
/// <summary>
/// Balance of the virtual currency after modification.
/// </summary>
public int Balance;
/// <summary>
/// Name of the virtual currency which was modified.
/// </summary>
public string VirtualCurrency;
}
/// <summary>
/// This function can both add and remove uses of an inventory item. If the number of uses drops below zero, the item will
/// be removed from active inventory.
/// </summary>
[Serializable]
public class ModifyItemUsesRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique instance identifier of the item to be modified.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// PlayFab unique identifier of the user whose item is being modified.
/// </summary>
public string PlayFabId;
/// <summary>
/// Number of uses to add to the item. Can be negative to remove uses.
/// </summary>
public int UsesToAdd;
}
[Serializable]
public class ModifyItemUsesResult : PlayFabResultCommon
{
/// <summary>
/// Unique instance identifier of the item with uses consumed.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Number of uses remaining on the item.
/// </summary>
public int RemainingUses;
}
[Serializable]
public class ModifyUserVirtualCurrencyResult : PlayFabResultCommon
{
/// <summary>
/// Balance of the virtual currency after modification.
/// </summary>
public int Balance;
/// <summary>
/// Amount added or subtracted from the user's virtual currency. Maximum VC balance is Int32 (2,147,483,647). Any increase
/// over this value will be discarded.
/// </summary>
public int BalanceChange;
/// <summary>
/// User currency was subtracted from.
/// </summary>
public string PlayFabId;
/// <summary>
/// Name of the virtual currency which was modified.
/// </summary>
public string VirtualCurrency;
}
/// <summary>
/// Transfers an item from a character to another character that is owned by the same
/// user. This will remove the item from the character's inventory (until and unless it is moved back), and will enable the
/// other character to make use of the item instead.
/// </summary>
[Serializable]
public class MoveItemToCharacterFromCharacterRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the character that currently has the item.
/// </summary>
public string GivingCharacterId;
/// <summary>
/// Unique PlayFab assigned instance identifier of the item
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique identifier of the character that will be receiving the item.
/// </summary>
public string ReceivingCharacterId;
}
[Serializable]
public class MoveItemToCharacterFromCharacterResult : PlayFabResultCommon
{
}
/// <summary>
/// Transfers an item from a user to a character she owns. This will remove
/// the item from the user's inventory (until and unless it is moved back), and will enable the
/// character to make use of the item instead.
/// </summary>
[Serializable]
public class MoveItemToCharacterFromUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned instance identifier of the item
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class MoveItemToCharacterFromUserResult : PlayFabResultCommon
{
}
/// <summary>
/// Transfers an item from a character to the owning user. This will remove
/// the item from the character's inventory (until and unless it is moved back), and will enable the
/// user to make use of the item instead.
/// </summary>
[Serializable]
public class MoveItemToUserFromCharacterRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned instance identifier of the item
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class MoveItemToUserFromCharacterResult : PlayFabResultCommon
{
}
[Serializable]
public class NintendoSwitchPlayFabIdPair
{
/// <summary>
/// Unique Nintendo Switch Device identifier for a user.
/// </summary>
public string NintendoSwitchDeviceId;
/// <summary>
/// Unique PlayFab identifier for a user, or null if no PlayFab account is linked to the Nintendo Switch Device identifier.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class NotifyMatchmakerPlayerLeftRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Instance the user is leaving.
/// </summary>
public string LobbyId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class NotifyMatchmakerPlayerLeftResult : PlayFabResultCommon
{
/// <summary>
/// State of user leaving the Game Server Instance.
/// </summary>
public PlayerConnectionState? PlayerState;
}
public enum PlayerConnectionState
{
Unassigned,
Connecting,
Participating,
Participated
}
[Serializable]
public class PlayerLeaderboardEntry
{
/// <summary>
/// Title-specific display name of the user for this leaderboard entry.
/// </summary>
public string DisplayName;
/// <summary>
/// PlayFab unique identifier of the user for this leaderboard entry.
/// </summary>
public string PlayFabId;
/// <summary>
/// User's overall position in the leaderboard.
/// </summary>
public int Position;
/// <summary>
/// The profile of the user, if requested.
/// </summary>
public PlayerProfileModel Profile;
/// <summary>
/// Specific value of the user's statistic.
/// </summary>
public int StatValue;
}
[Serializable]
public class PlayerLinkedAccount
{
/// <summary>
/// Linked account's email
/// </summary>
public string Email;
/// <summary>
/// Authentication platform
/// </summary>
public LoginIdentityProvider? Platform;
/// <summary>
/// Platform user identifier
/// </summary>
public string PlatformUserId;
/// <summary>
/// Linked account's username
/// </summary>
public string Username;
}
[Serializable]
public class PlayerLocation
{
/// <summary>
/// City of the player's geographic location.
/// </summary>
public string City;
/// <summary>
/// The two-character continent code for this location
/// </summary>
public ContinentCode ContinentCode;
/// <summary>
/// The two-character ISO 3166-1 country code for the country associated with the location
/// </summary>
public CountryCode CountryCode;
/// <summary>
/// Latitude coordinate of the player's geographic location.
/// </summary>
public double? Latitude;
/// <summary>
/// Longitude coordinate of the player's geographic location.
/// </summary>
public double? Longitude;
}
[Serializable]
public class PlayerProfile
{
/// <summary>
/// Array of ad campaigns player has been attributed to
/// </summary>
public List<AdCampaignAttribution> AdCampaignAttributions;
/// <summary>
/// Image URL of the player's avatar.
/// </summary>
public string AvatarUrl;
/// <summary>
/// Banned until UTC Date. If permanent ban this is set for 20 years after the original ban date.
/// </summary>
public DateTime? BannedUntil;
/// <summary>
/// Array of contact email addresses associated with the player
/// </summary>
public List<ContactEmailInfo> ContactEmailAddresses;
/// <summary>
/// Player record created
/// </summary>
public DateTime? Created;
/// <summary>
/// Player Display Name
/// </summary>
public string DisplayName;
/// <summary>
/// Last login
/// </summary>
public DateTime? LastLogin;
/// <summary>
/// Array of third party accounts linked to this player
/// </summary>
public List<PlayerLinkedAccount> LinkedAccounts;
/// <summary>
/// Dictionary of player's locations by type.
/// </summary>
public Dictionary<string,PlayerLocation> Locations;
/// <summary>
/// Player account origination
/// </summary>
public LoginIdentityProvider? Origination;
/// <summary>
/// PlayFab Player ID
/// </summary>
public string PlayerId;
/// <summary>
/// Array of player statistics
/// </summary>
public List<PlayerStatistic> PlayerStatistics;
/// <summary>
/// Publisher this player belongs to
/// </summary>
public string PublisherId;
/// <summary>
/// Array of configured push notification end points
/// </summary>
public List<PushNotificationRegistration> PushNotificationRegistrations;
/// <summary>
/// Dictionary of player's statistics using only the latest version's value
/// </summary>
public Dictionary<string,int> Statistics;
/// <summary>
/// List of player's tags for segmentation.
/// </summary>
public List<string> Tags;
/// <summary>
/// Title ID this profile applies to
/// </summary>
public string TitleId;
/// <summary>
/// A sum of player's total purchases in USD across all currencies.
/// </summary>
public uint? TotalValueToDateInUSD;
/// <summary>
/// Dictionary of player's total purchases by currency.
/// </summary>
public Dictionary<string,uint> ValuesToDate;
/// <summary>
/// Dictionary of player's virtual currency balances
/// </summary>
public Dictionary<string,int> VirtualCurrencyBalances;
}
[Serializable]
public class PlayerProfileModel
{
/// <summary>
/// List of advertising campaigns the player has been attributed to
/// </summary>
public List<AdCampaignAttributionModel> AdCampaignAttributions;
/// <summary>
/// URL of the player's avatar image
/// </summary>
public string AvatarUrl;
/// <summary>
/// If the player is currently banned, the UTC Date when the ban expires
/// </summary>
public DateTime? BannedUntil;
/// <summary>
/// List of all contact email info associated with the player account
/// </summary>
public List<ContactEmailInfoModel> ContactEmailAddresses;
/// <summary>
/// Player record created
/// </summary>
public DateTime? Created;
/// <summary>
/// Player display name
/// </summary>
public string DisplayName;
/// <summary>
/// UTC time when the player most recently logged in to the title
/// </summary>
public DateTime? LastLogin;
/// <summary>
/// List of all authentication systems linked to this player account
/// </summary>
public List<LinkedPlatformAccountModel> LinkedAccounts;
/// <summary>
/// List of geographic locations from which the player has logged in to the title
/// </summary>
public List<LocationModel> Locations;
/// <summary>
/// List of memberships for the player, along with whether are expired.
/// </summary>
public List<MembershipModel> Memberships;
/// <summary>
/// Player account origination
/// </summary>
public LoginIdentityProvider? Origination;
/// <summary>
/// PlayFab player account unique identifier
/// </summary>
public string PlayerId;
/// <summary>
/// Publisher this player belongs to
/// </summary>
public string PublisherId;
/// <summary>
/// List of configured end points registered for sending the player push notifications
/// </summary>
public List<PushNotificationRegistrationModel> PushNotificationRegistrations;
/// <summary>
/// List of leaderboard statistic values for the player
/// </summary>
public List<StatisticModel> Statistics;
/// <summary>
/// List of player's tags for segmentation
/// </summary>
public List<TagModel> Tags;
/// <summary>
/// Title ID this player profile applies to
/// </summary>
public string TitleId;
/// <summary>
/// Sum of the player's purchases made with real-money currencies, converted to US dollars equivalent and represented as a
/// whole number of cents (1/100 USD). For example, 999 indicates nine dollars and ninety-nine cents.
/// </summary>
public uint? TotalValueToDateInUSD;
/// <summary>
/// List of the player's lifetime purchase totals, summed by real-money currency
/// </summary>
public List<ValueToDateModel> ValuesToDate;
}
[Serializable]
public class PlayerProfileViewConstraints
{
/// <summary>
/// Whether to show player's avatar URL. Defaults to false
/// </summary>
public bool ShowAvatarUrl;
/// <summary>
/// Whether to show the banned until time. Defaults to false
/// </summary>
public bool ShowBannedUntil;
/// <summary>
/// Whether to show campaign attributions. Defaults to false
/// </summary>
public bool ShowCampaignAttributions;
/// <summary>
/// Whether to show contact email addresses. Defaults to false
/// </summary>
public bool ShowContactEmailAddresses;
/// <summary>
/// Whether to show the created date. Defaults to false
/// </summary>
public bool ShowCreated;
/// <summary>
/// Whether to show the display name. Defaults to false
/// </summary>
public bool ShowDisplayName;
/// <summary>
/// Whether to show the last login time. Defaults to false
/// </summary>
public bool ShowLastLogin;
/// <summary>
/// Whether to show the linked accounts. Defaults to false
/// </summary>
public bool ShowLinkedAccounts;
/// <summary>
/// Whether to show player's locations. Defaults to false
/// </summary>
public bool ShowLocations;
/// <summary>
/// Whether to show player's membership information. Defaults to false
/// </summary>
public bool ShowMemberships;
/// <summary>
/// Whether to show origination. Defaults to false
/// </summary>
public bool ShowOrigination;
/// <summary>
/// Whether to show push notification registrations. Defaults to false
/// </summary>
public bool ShowPushNotificationRegistrations;
/// <summary>
/// Reserved for future development
/// </summary>
public bool ShowStatistics;
/// <summary>
/// Whether to show tags. Defaults to false
/// </summary>
public bool ShowTags;
/// <summary>
/// Whether to show the total value to date in usd. Defaults to false
/// </summary>
public bool ShowTotalValueToDateInUsd;
/// <summary>
/// Whether to show the values to date. Defaults to false
/// </summary>
public bool ShowValuesToDate;
}
[Serializable]
public class PlayerStatistic
{
/// <summary>
/// Statistic ID
/// </summary>
public string Id;
/// <summary>
/// Statistic name
/// </summary>
public string Name;
/// <summary>
/// Current statistic value
/// </summary>
public int StatisticValue;
/// <summary>
/// Statistic version (0 if not a versioned statistic)
/// </summary>
public int StatisticVersion;
}
[Serializable]
public class PlayerStatisticVersion
{
/// <summary>
/// time when the statistic version became active
/// </summary>
public DateTime ActivationTime;
/// <summary>
/// time when the statistic version became inactive due to statistic version incrementing
/// </summary>
public DateTime? DeactivationTime;
/// <summary>
/// time at which the statistic version was scheduled to become active, based on the configured ResetInterval
/// </summary>
public DateTime? ScheduledActivationTime;
/// <summary>
/// time at which the statistic version was scheduled to become inactive, based on the configured ResetInterval
/// </summary>
public DateTime? ScheduledDeactivationTime;
/// <summary>
/// name of the statistic when the version became active
/// </summary>
public string StatisticName;
/// <summary>
/// version of the statistic
/// </summary>
public uint Version;
}
[Serializable]
public class PushNotificationPackage
{
/// <summary>
/// Numerical badge to display on App icon (iOS only)
/// </summary>
public int Badge;
/// <summary>
/// This must be a JSON formatted object. For use with developer-created custom Push Notification plugins
/// </summary>
public string CustomData;
/// <summary>
/// Icon file to display with the message (Not supported for iOS)
/// </summary>
public string Icon;
/// <summary>
/// Content of the message (all platforms)
/// </summary>
public string Message;
/// <summary>
/// Sound file to play with the message (all platforms)
/// </summary>
public string Sound;
/// <summary>
/// Title/Subject of the message. Not supported for iOS
/// </summary>
public string Title;
}
public enum PushNotificationPlatform
{
ApplePushNotificationService,
GoogleCloudMessaging
}
[Serializable]
public class PushNotificationRegistration
{
/// <summary>
/// Notification configured endpoint
/// </summary>
public string NotificationEndpointARN;
/// <summary>
/// Push notification platform
/// </summary>
public PushNotificationPlatform? Platform;
}
[Serializable]
public class PushNotificationRegistrationModel
{
/// <summary>
/// Notification configured endpoint
/// </summary>
public string NotificationEndpointARN;
/// <summary>
/// Push notification platform
/// </summary>
public PushNotificationPlatform? Platform;
}
[Serializable]
public class RandomResultTableListing
{
/// <summary>
/// Catalog version this table is associated with
/// </summary>
public string CatalogVersion;
/// <summary>
/// Child nodes that indicate what kind of drop table item this actually is.
/// </summary>
public List<ResultTableNode> Nodes;
/// <summary>
/// Unique name for this drop table
/// </summary>
public string TableId;
}
/// <summary>
/// Coupon codes can be created for any item, or set of items, in the catalog for the title. This
/// operation causes the coupon to be consumed, and the specific items to be awarded to the user. Attempting to re-use an
/// already
/// consumed code, or a code which has not yet been created in the service, will result in an error.
/// </summary>
[Serializable]
public class RedeemCouponRequest : PlayFabRequestCommon
{
/// <summary>
/// Catalog version of the coupon.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Optional identifier for the Character that should receive the item. If null, item is added to the player
/// </summary>
public string CharacterId;
/// <summary>
/// Generated coupon code to redeem.
/// </summary>
public string CouponCode;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class RedeemCouponResult : PlayFabResultCommon
{
/// <summary>
/// Items granted to the player as a result of redeeming the coupon.
/// </summary>
public List<ItemInstance> GrantedItems;
}
/// <summary>
/// This function is used by a Game Server Instance to validate with the PlayFab service that a user has been
/// registered as connected to the server. The Ticket is provided to the client either as a result of a call to StartGame or
/// Matchmake, each
/// of which return a Ticket specific to the Game Server Instance. This function will fail in any case where the Ticket
/// presented is not valid
/// for the specific Game Server Instance making the call. Note that data returned may be Personally Identifying Information
/// (PII), such as
/// email address, and so care should be taken in how this data is stored and managed. Since this call will always return
/// the relevant information
/// for users who have accessed the title, the recommendation is to not store this data locally.
/// </summary>
[Serializable]
public class RedeemMatchmakerTicketRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance that is asking for validation of the authorization ticket.
/// </summary>
public string LobbyId;
/// <summary>
/// Server authorization ticket passed back from a call to Matchmake or StartGame.
/// </summary>
public string Ticket;
}
[Serializable]
public class RedeemMatchmakerTicketResult : PlayFabResultCommon
{
/// <summary>
/// Error value if the ticket was not validated.
/// </summary>
public string Error;
/// <summary>
/// Boolean indicating whether the ticket was validated by the PlayFab service.
/// </summary>
public bool TicketIsValid;
/// <summary>
/// User account information for the user validated.
/// </summary>
public UserAccountInfo UserInfo;
}
[Serializable]
public class RefreshGameServerInstanceHeartbeatRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance for which the heartbeat is updated.
/// </summary>
public string LobbyId;
}
[Serializable]
public class RefreshGameServerInstanceHeartbeatResult : PlayFabResultCommon
{
}
public enum Region
{
USCentral,
USEast,
EUWest,
Singapore,
Japan,
Brazil,
Australia
}
[Serializable]
public class RegisterGameRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the build running on the Game Server Instance.
/// </summary>
public string Build;
/// <summary>
/// Game Mode the Game Server instance is running. Note that this must be defined in the Game Modes tab in the PlayFab Game
/// Manager, along with the Build ID (the same Game Mode can be defined for multiple Build IDs).
/// </summary>
public string GameMode;
/// <summary>
/// Previous lobby id if re-registering an existing game.
/// </summary>
public string LobbyId;
/// <summary>
/// Region in which the Game Server Instance is running. For matchmaking using non-AWS region names, set this to any AWS
/// region and use Tags (below) to specify your custom region.
/// </summary>
public Region Region;
/// <summary>
/// IPV4 address of the game server instance.
/// </summary>
public string ServerIPV4Address;
/// <summary>
/// IPV6 address (if any) of the game server instance.
/// </summary>
public string ServerIPV6Address;
/// <summary>
/// Port number for communication with the Game Server Instance.
/// </summary>
public string ServerPort;
/// <summary>
/// Public DNS name (if any) of the server
/// </summary>
public string ServerPublicDNSName;
/// <summary>
/// Tags for the Game Server Instance
/// </summary>
public Dictionary<string,string> Tags;
}
[Serializable]
public class RegisterGameResponse : PlayFabResultCommon
{
/// <summary>
/// Unique identifier generated for the Game Server Instance that is registered. If LobbyId is specified in request and the
/// game still exists in PlayFab, the LobbyId in request is returned. Otherwise a new lobby id will be returned.
/// </summary>
public string LobbyId;
}
[Serializable]
public class RemoveFriendRequest : PlayFabRequestCommon
{
/// <summary>
/// PlayFab identifier of the friend account which is to be removed.
/// </summary>
public string FriendPlayFabId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// This API will trigger a player_tag_removed event and remove a tag with the given TagName and PlayFabID from the
/// corresponding player profile. TagName can be used for segmentation and it is limited to 256 characters
/// </summary>
[Serializable]
public class RemovePlayerTagRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique tag for player profile.
/// </summary>
public string TagName;
}
[Serializable]
public class RemovePlayerTagResult : PlayFabResultCommon
{
}
[Serializable]
public class RemoveSharedGroupMembersRequest : PlayFabRequestCommon
{
/// <summary>
/// An array of unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public List<string> PlayFabIds;
/// <summary>
/// Unique identifier for the shared group.
/// </summary>
public string SharedGroupId;
}
[Serializable]
public class RemoveSharedGroupMembersResult : PlayFabResultCommon
{
}
[Serializable]
public class ReportPlayerServerRequest : PlayFabRequestCommon
{
/// <summary>
/// Optional additional comment by reporting player.
/// </summary>
public string Comment;
/// <summary>
/// Unique PlayFab identifier of the reported player.
/// </summary>
public string ReporteeId;
/// <summary>
/// PlayFabId of the reporting player.
/// </summary>
public string ReporterId;
}
/// <summary>
/// Players are currently limited to five reports per day. Attempts by a single user account to submit reports beyond five
/// will result in Updated being returned as false.
/// </summary>
[Serializable]
public class ReportPlayerServerResult : PlayFabResultCommon
{
/// <summary>
/// The number of remaining reports which may be filed today by this reporting player.
/// </summary>
public int SubmissionsRemaining;
}
[Serializable]
public class ResultTableNode
{
/// <summary>
/// Either an ItemId, or the TableId of another random result table
/// </summary>
public string ResultItem;
/// <summary>
/// Whether this entry in the table is an item or a link to another table
/// </summary>
public ResultTableNodeType ResultItemType;
/// <summary>
/// How likely this is to be rolled - larger numbers add more weight
/// </summary>
public int Weight;
}
public enum ResultTableNodeType
{
ItemId,
TableId
}
/// <summary>
/// Setting the active state of all non-expired bans for a user to Inactive. Expired bans with an Active state will be
/// ignored, however. Returns information about applied updates only.
/// </summary>
[Serializable]
public class RevokeAllBansForUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class RevokeAllBansForUserResult : PlayFabResultCommon
{
/// <summary>
/// Information on the bans that were revoked.
/// </summary>
public List<BanInfo> BanData;
}
/// <summary>
/// Setting the active state of all bans requested to Inactive regardless of whether that ban has already expired. BanIds
/// that do not exist will be skipped. Returns information about applied updates only.
/// </summary>
[Serializable]
public class RevokeBansRequest : PlayFabRequestCommon
{
/// <summary>
/// Ids of the bans to be revoked. Maximum 100.
/// </summary>
public List<string> BanIds;
}
[Serializable]
public class RevokeBansResult : PlayFabResultCommon
{
/// <summary>
/// Information on the bans that were revoked
/// </summary>
public List<BanInfo> BanData;
}
[Serializable]
public class RevokeInventoryItem
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned instance identifier of the item
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// In cases where the inventory item in question is a "crate", and the items it contained have already been dispensed, this
/// will not revoke access or otherwise remove the items which were dispensed.
/// </summary>
[Serializable]
public class RevokeInventoryItemRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned instance identifier of the item
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// In cases where the inventory item in question is a "crate", and the items it contained have already been dispensed, this
/// will not revoke access or otherwise remove the items which were dispensed.
/// </summary>
[Serializable]
public class RevokeInventoryItemsRequest : PlayFabRequestCommon
{
/// <summary>
/// Array of player items to revoke, between 1 and 25 items.
/// </summary>
public List<RevokeInventoryItem> Items;
}
[Serializable]
public class RevokeInventoryItemsResult : PlayFabResultCommon
{
/// <summary>
/// Collection of any errors that occurred during processing.
/// </summary>
public List<RevokeItemError> Errors;
}
[Serializable]
public class RevokeInventoryResult : PlayFabResultCommon
{
}
[Serializable]
public class RevokeItemError
{
/// <summary>
/// Specific error that was encountered.
/// </summary>
public GenericErrorCodes? Error;
/// <summary>
/// Item information that failed to be revoked.
/// </summary>
public RevokeInventoryItem Item;
}
[Serializable]
public class ScriptExecutionError
{
/// <summary>
/// Error code, such as CloudScriptNotFound, JavascriptException, CloudScriptFunctionArgumentSizeExceeded,
/// CloudScriptAPIRequestCountExceeded, CloudScriptAPIRequestError, or CloudScriptHTTPRequestError
/// </summary>
public string Error;
/// <summary>
/// Details about the error
/// </summary>
public string Message;
/// <summary>
/// Point during the execution of the script at which the error occurred, if any
/// </summary>
public string StackTrace;
}
/// <summary>
/// PlayFab accounts which have valid email address or username will be able to receive a password reset email using this
/// API.The email sent must be an account recovery email template. The username or email can be passed in to send the email
/// </summary>
[Serializable]
public class SendCustomAccountRecoveryEmailRequest : PlayFabRequestCommon
{
/// <summary>
/// User email address attached to their account
/// </summary>
public string Email;
/// <summary>
/// The email template id of the account recovery email template to send.
/// </summary>
public string EmailTemplateId;
/// <summary>
/// The user's username requesting an account recovery.
/// </summary>
public string Username;
}
[Serializable]
public class SendCustomAccountRecoveryEmailResult : PlayFabResultCommon
{
}
/// <summary>
/// Sends an email for only players that have contact emails associated with them. Takes in an email template ID
/// specifyingthe email template to send.
/// </summary>
[Serializable]
public class SendEmailFromTemplateRequest : PlayFabRequestCommon
{
/// <summary>
/// The email template id of the email template to send.
/// </summary>
public string EmailTemplateId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class SendEmailFromTemplateResult : PlayFabResultCommon
{
}
[Serializable]
public class SendPushNotificationRequest : PlayFabRequestCommon
{
/// <summary>
/// Allows you to provide precisely formatted json to target devices. This is an advanced feature, allowing you to deliver
/// to custom plugin logic, fields, or functionality not natively supported by PlayFab.
/// </summary>
public List<AdvancedPushPlatformMsg> AdvancedPlatformDelivery;
/// <summary>
/// Text of message to send.
/// </summary>
public string Message;
/// <summary>
/// Defines all possible push attributes like message, title, icon, etc. Some parameters are device specific - please see
/// the PushNotificationPackage documentation for details.
/// </summary>
public PushNotificationPackage Package;
/// <summary>
/// PlayFabId of the recipient of the push notification.
/// </summary>
public string Recipient;
/// <summary>
/// Subject of message to send (may not be displayed in all platforms)
/// </summary>
public string Subject;
/// <summary>
/// Target Platforms that should receive the Message or Package. If omitted, we will send to all available platforms.
/// </summary>
public List<PushNotificationPlatform> TargetPlatforms;
}
[Serializable]
public class SendPushNotificationResult : PlayFabResultCommon
{
}
[Serializable]
public class ServerCustomIDPlayFabIDPair
{
/// <summary>
/// Unique PlayFab identifier.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique server custom identifier for this player.
/// </summary>
public string ServerCustomId;
}
[Serializable]
public class ServerLoginResult : PlayFabResultCommon
{
/// <summary>
/// If LoginTitlePlayerAccountEntity flag is set on the login request the title_player_account will also be logged in and
/// returned.
/// </summary>
public EntityTokenResponse EntityToken;
/// <summary>
/// Results for requested info.
/// </summary>
public GetPlayerCombinedInfoResultPayload InfoResultPayload;
/// <summary>
/// The time of this user's previous login. If there was no previous login, then it's DateTime.MinValue
/// </summary>
public DateTime? LastLoginTime;
/// <summary>
/// True if the account was newly created on this login.
/// </summary>
public bool NewlyCreated;
/// <summary>
/// Player's unique PlayFabId.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique token authorizing the user and game at the server level, for the current session.
/// </summary>
public string SessionTicket;
/// <summary>
/// Settings specific to this user.
/// </summary>
public UserSettings SettingsForUser;
}
/// <summary>
/// This operation is not additive. It will completely replace the tag list for the specified user.
/// Please note that only users in the PlayFab friends list can be assigned tags. Attempting to set a tag on a friend only
/// included
/// in the friends list from a social site integration (such as Facebook or Steam) will return the AccountNotFound error.
/// </summary>
[Serializable]
public class SetFriendTagsRequest : PlayFabRequestCommon
{
/// <summary>
/// PlayFab identifier of the friend account to which the tag(s) should be applied.
/// </summary>
public string FriendPlayFabId;
/// <summary>
/// PlayFab identifier of the player whose friend is to be updated.
/// </summary>
public string PlayFabId;
/// <summary>
/// Array of tags to set on the friend account.
/// </summary>
public List<string> Tags;
}
[Serializable]
public class SetGameServerInstanceDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Custom data to set for the specified game server instance.
/// </summary>
public string GameServerData;
/// <summary>
/// Unique identifier of the Game Instance to be updated, in decimal format.
/// </summary>
public string LobbyId;
}
[Serializable]
public class SetGameServerInstanceDataResult : PlayFabResultCommon
{
}
[Serializable]
public class SetGameServerInstanceStateRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Instance to be updated, in decimal format.
/// </summary>
public string LobbyId;
/// <summary>
/// State to set for the specified game server instance.
/// </summary>
public GameInstanceState State;
}
[Serializable]
public class SetGameServerInstanceStateResult : PlayFabResultCommon
{
}
[Serializable]
public class SetGameServerInstanceTagsRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance to be updated.
/// </summary>
public string LobbyId;
/// <summary>
/// Tags to set for the specified Game Server Instance. Note that this is the complete list of tags to be associated with
/// the Game Server Instance.
/// </summary>
public Dictionary<string,string> Tags;
}
[Serializable]
public class SetGameServerInstanceTagsResult : PlayFabResultCommon
{
}
/// <summary>
/// APIs that require signatures require that the player have a configured Player Secret Key that is used to sign all
/// requests. Players that don't have a secret will be blocked from making API calls until it is configured. To create a
/// signature header add a SHA256 hashed string containing UTF8 encoded JSON body as it will be sent to the server, the
/// current time in UTC formatted to ISO 8601, and the players secret formatted as 'body.date.secret'. Place the resulting
/// hash into the header X-PlayFab-Signature, along with a header X-PlayFab-Timestamp of the same UTC timestamp used in the
/// signature.
/// </summary>
[Serializable]
public class SetPlayerSecretRequest : PlayFabRequestCommon
{
/// <summary>
/// Player secret that is used to verify API request signatures (Enterprise Only).
/// </summary>
public string PlayerSecret;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class SetPlayerSecretResult : PlayFabResultCommon
{
}
/// <summary>
/// This API is designed to store publisher-specific values which can be read, but not written to, by the client. This data
/// is shared across all
/// titles assigned to a particular publisher, and can be used for cross-game coordination. Only titles assigned to a
/// publisher can use this API. This operation is additive.
/// If a Key does not exist in the current dataset, it will be added with
/// the specified Value. If it already exists, the Value for that key will be overwritten with the new Value. For more
/// information email devrel@playfab.com
/// </summary>
[Serializable]
public class SetPublisherDataRequest : PlayFabRequestCommon
{
/// <summary>
/// key we want to set a value on (note, this is additive - will only replace an existing key's value if they are the same
/// name.) Keys are trimmed of whitespace. Keys may not begin with the '!' character.
/// </summary>
public string Key;
/// <summary>
/// new value to set. Set to null to remove a value
/// </summary>
public string Value;
}
[Serializable]
public class SetPublisherDataResult : PlayFabResultCommon
{
}
/// <summary>
/// This API is designed to store title specific values which can be read, but not written to, by the client. For example, a
/// developer
/// could choose to store values which modify the user experience, such as enemy spawn rates, weapon strengths, movement
/// speeds, etc. This allows a developer to update
/// the title without the need to create, test, and ship a new build. This operation is additive. If a Key does not exist in
/// the current dataset, it will be added with
/// the specified Value. If it already exists, the Value for that key will be overwritten with the new Value.
/// </summary>
[Serializable]
public class SetTitleDataRequest : PlayFabRequestCommon
{
/// <summary>
/// key we want to set a value on (note, this is additive - will only replace an existing key's value if they are the same
/// name.) Keys are trimmed of whitespace. Keys may not begin with the '!' character.
/// </summary>
public string Key;
/// <summary>
/// new value to set. Set to null to remove a value
/// </summary>
public string Value;
}
[Serializable]
public class SetTitleDataResult : PlayFabResultCommon
{
}
[Serializable]
public class SharedGroupDataRecord
{
/// <summary>
/// Timestamp for when this data was last updated.
/// </summary>
public DateTime LastUpdated;
/// <summary>
/// PlayFabId of the user to last update this value.
/// </summary>
public string LastUpdatedBy;
/// <summary>
/// Indicates whether this data can be read by all users (public) or only members of the group (private).
/// </summary>
public UserDataPermission? Permission;
/// <summary>
/// Data stored for the specified group data key.
/// </summary>
public string Value;
}
[Serializable]
public class StatisticModel
{
/// <summary>
/// Statistic name
/// </summary>
public string Name;
/// <summary>
/// Statistic value
/// </summary>
public int Value;
/// <summary>
/// Statistic version (0 if not a versioned statistic)
/// </summary>
public int Version;
}
[Serializable]
public class StatisticNameVersion
{
/// <summary>
/// unique name of the statistic
/// </summary>
public string StatisticName;
/// <summary>
/// the version of the statistic to be returned
/// </summary>
public uint Version;
}
[Serializable]
public class StatisticUpdate
{
/// <summary>
/// unique name of the statistic
/// </summary>
public string StatisticName;
/// <summary>
/// statistic value for the player
/// </summary>
public int Value;
/// <summary>
/// for updates to an existing statistic value for a player, the version of the statistic when it was loaded. Null when
/// setting the statistic value for the first time.
/// </summary>
public uint? Version;
}
[Serializable]
public class StatisticValue
{
/// <summary>
/// unique name of the statistic
/// </summary>
public string StatisticName;
/// <summary>
/// statistic value for the player
/// </summary>
public int Value;
/// <summary>
/// for updates to an existing statistic value for a player, the version of the statistic when it was loaded
/// </summary>
public uint Version;
}
[Serializable]
public class SteamPlayFabIdPair
{
/// <summary>
/// Unique PlayFab identifier for a user, or null if no PlayFab account is linked to the Steam identifier.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique Steam identifier for a user.
/// </summary>
public string SteamStringId;
}
[Serializable]
public class SubscriptionModel
{
/// <summary>
/// When this subscription expires.
/// </summary>
public DateTime Expiration;
/// <summary>
/// The time the subscription was orignially purchased
/// </summary>
public DateTime InitialSubscriptionTime;
/// <summary>
/// Whether this subscription is currently active. That is, if Expiration > now.
/// </summary>
public bool IsActive;
/// <summary>
/// The status of this subscription, according to the subscription provider.
/// </summary>
public SubscriptionProviderStatus? Status;
/// <summary>
/// The id for this subscription
/// </summary>
public string SubscriptionId;
/// <summary>
/// The item id for this subscription from the primary catalog
/// </summary>
public string SubscriptionItemId;
/// <summary>
/// The provider for this subscription. Apple or Google Play are supported today.
/// </summary>
public string SubscriptionProvider;
}
public enum SubscriptionProviderStatus
{
NoError,
Cancelled,
UnknownError,
BillingError,
ProductUnavailable,
CustomerDidNotAcceptPriceChange,
FreeTrial,
PaymentPending
}
[Serializable]
public class SubtractCharacterVirtualCurrencyRequest : PlayFabRequestCommon
{
/// <summary>
/// Amount to be subtracted from the user balance of the specified virtual currency.
/// </summary>
public int Amount;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Name of the virtual currency which is to be decremented.
/// </summary>
public string VirtualCurrency;
}
[Serializable]
public class SubtractUserVirtualCurrencyRequest : PlayFabRequestCommon
{
/// <summary>
/// Amount to be subtracted from the user balance of the specified virtual currency.
/// </summary>
public int Amount;
/// <summary>
/// PlayFab unique identifier of the user whose virtual currency balance is to be decreased.
/// </summary>
public string PlayFabId;
/// <summary>
/// Name of the virtual currency which is to be decremented.
/// </summary>
public string VirtualCurrency;
}
[Serializable]
public class TagModel
{
/// <summary>
/// Full value of the tag, including namespace
/// </summary>
public string TagValue;
}
public enum TitleActivationStatus
{
None,
ActivatedTitleKey,
PendingSteam,
ActivatedSteam,
RevokedSteam
}
[Serializable]
public class TitleNewsItem
{
/// <summary>
/// News item text.
/// </summary>
public string Body;
/// <summary>
/// Unique identifier of news item.
/// </summary>
public string NewsId;
/// <summary>
/// Date and time when the news items was posted.
/// </summary>
public DateTime Timestamp;
/// <summary>
/// Title of the news item.
/// </summary>
public string Title;
}
[Serializable]
public class UnlinkXboxAccountRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab identifier for a user, or null if no PlayFab account is linked to the Xbox Live identifier.
/// </summary>
public string PlayFabId;
/// <summary>
/// Token provided by the Xbox Live SDK/XDK method GetTokenAndSignatureAsync("POST", "https://playfabapi.com", "").
/// </summary>
public string XboxToken;
}
[Serializable]
public class UnlinkXboxAccountResult : PlayFabResultCommon
{
}
/// <summary>
/// Specify the container and optionally the catalogVersion for the container to open
/// </summary>
[Serializable]
public class UnlockContainerInstanceRequest : PlayFabRequestCommon
{
/// <summary>
/// Specifies the catalog version that should be used to determine container contents. If unspecified, uses catalog
/// associated with the item instance.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// ItemInstanceId of the container to unlock.
/// </summary>
public string ContainerItemInstanceId;
/// <summary>
/// ItemInstanceId of the key that will be consumed by unlocking this container. If the container requires a key, this
/// parameter is required.
/// </summary>
public string KeyItemInstanceId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// Specify the type of container to open and optionally the catalogVersion for the container to open
/// </summary>
[Serializable]
public class UnlockContainerItemRequest : PlayFabRequestCommon
{
/// <summary>
/// Specifies the catalog version that should be used to determine container contents. If unspecified, uses default/primary
/// catalog.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Catalog ItemId of the container type to unlock.
/// </summary>
public string ContainerItemId;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// The items and vc found within the container. These will be added and stacked in your inventory as appropriate.
/// </summary>
[Serializable]
public class UnlockContainerItemResult : PlayFabResultCommon
{
/// <summary>
/// Items granted to the player as a result of unlocking the container.
/// </summary>
public List<ItemInstance> GrantedItems;
/// <summary>
/// Unique instance identifier of the container unlocked.
/// </summary>
public string UnlockedItemInstanceId;
/// <summary>
/// Unique instance identifier of the key used to unlock the container, if applicable.
/// </summary>
public string UnlockedWithItemInstanceId;
/// <summary>
/// Virtual currency granted to the player as a result of unlocking the container.
/// </summary>
public Dictionary<string,uint> VirtualCurrency;
}
[Serializable]
public class UpdateAvatarUrlRequest : PlayFabRequestCommon
{
/// <summary>
/// URL of the avatar image. If empty, it removes the existing avatar URL.
/// </summary>
public string ImageUrl;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// Represents a single update ban request.
/// </summary>
[Serializable]
public class UpdateBanRequest : PlayFabRequestCommon
{
/// <summary>
/// The updated active state for the ban. Null for no change.
/// </summary>
public bool? Active;
/// <summary>
/// The id of the ban to be updated.
/// </summary>
public string BanId;
/// <summary>
/// The updated expiration date for the ban. Null for no change.
/// </summary>
public DateTime? Expires;
/// <summary>
/// The updated IP address for the ban. Null for no change.
/// </summary>
public string IPAddress;
/// <summary>
/// The updated MAC address for the ban. Null for no change.
/// </summary>
public string MACAddress;
/// <summary>
/// Whether to make this ban permanent. Set to true to make this ban permanent. This will not modify Active state.
/// </summary>
public bool? Permanent;
/// <summary>
/// The updated reason for the ban to be updated. Maximum 140 characters. Null for no change.
/// </summary>
public string Reason;
}
/// <summary>
/// For each ban, only updates the values that are set. Leave any value to null for no change. If a ban could not be found,
/// the rest are still applied. Returns information about applied updates only.
/// </summary>
[Serializable]
public class UpdateBansRequest : PlayFabRequestCommon
{
/// <summary>
/// List of bans to be updated. Maximum 100.
/// </summary>
public List<UpdateBanRequest> Bans;
}
[Serializable]
public class UpdateBansResult : PlayFabResultCommon
{
/// <summary>
/// Information on the bans that were updated
/// </summary>
public List<BanInfo> BanData;
}
/// <summary>
/// This function performs an additive update of the arbitrary JSON object containing
/// the custom data for the user. In updating the custom data object, keys which already exist in the object will have
/// their values overwritten, while keys with null values will be removed. No other key-value pairs will be changed apart
/// from those specified in the call.
/// </summary>
[Serializable]
public class UpdateCharacterDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Key-value pairs to be written to the custom data. Note that keys are trimmed of whitespace, are limited in size, and may
/// not begin with a '!' character or be null.
/// </summary>
public Dictionary<string,string> Data;
/// <summary>
/// Optional list of Data-keys to remove from UserData. Some SDKs cannot insert null-values into Data due to language
/// constraints. Use this to delete the keys directly.
/// </summary>
public List<string> KeysToRemove;
/// <summary>
/// Permission to be applied to all user data keys written in this request. Defaults to "private" if not set.
/// </summary>
public UserDataPermission? Permission;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class UpdateCharacterDataResult : PlayFabResultCommon
{
/// <summary>
/// Indicates the current version of the data that has been set. This is incremented with every set call for that type of
/// data (read-only, internal, etc). This version can be provided in Get calls to find updated data.
/// </summary>
public uint DataVersion;
}
/// <summary>
/// Character statistics are similar to user statistics in that they are numeric values which
/// may only be updated by a server operation, in order to minimize the opportunity for unauthorized changes. In addition to
/// being available for use by the title, the statistics are used for all leaderboard operations in PlayFab.
/// </summary>
[Serializable]
public class UpdateCharacterStatisticsRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Statistics to be updated with the provided values.
/// </summary>
public Dictionary<string,int> CharacterStatistics;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class UpdateCharacterStatisticsResult : PlayFabResultCommon
{
}
/// <summary>
/// This operation is additive. Statistics not currently defined will be added,
/// while those already defined will be updated with the given values. All other user statistics will remain unchanged.
/// </summary>
[Serializable]
public class UpdatePlayerStatisticsRequest : PlayFabRequestCommon
{
/// <summary>
/// Indicates whether the statistics provided should be set, regardless of the aggregation method set on the statistic.
/// Default is false.
/// </summary>
public bool? ForceUpdate;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// Statistics to be updated with the provided values
/// </summary>
public List<StatisticUpdate> Statistics;
}
[Serializable]
public class UpdatePlayerStatisticsResult : PlayFabResultCommon
{
}
/// <summary>
/// Note that in the case of multiple calls to write to the same shared group data keys, the
/// last write received by the PlayFab service will determine the value available to subsequent read operations. For
/// scenarios
/// requiring coordination of data updates, it is recommended that titles make use of user data with read permission set to
/// public, or a combination of user data and shared group data.
/// </summary>
[Serializable]
public class UpdateSharedGroupDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Key-value pairs to be written to the custom data. Note that keys are trimmed of whitespace, are limited in size, and may
/// not begin with a '!' character or be null.
/// </summary>
public Dictionary<string,string> Data;
/// <summary>
/// Optional list of Data-keys to remove from UserData. Some SDKs cannot insert null-values into Data due to language
/// constraints. Use this to delete the keys directly.
/// </summary>
public List<string> KeysToRemove;
/// <summary>
/// Permission to be applied to all user data keys in this request.
/// </summary>
public UserDataPermission? Permission;
/// <summary>
/// Unique identifier for the shared group.
/// </summary>
public string SharedGroupId;
}
[Serializable]
public class UpdateSharedGroupDataResult : PlayFabResultCommon
{
}
/// <summary>
/// This function performs an additive update of the arbitrary JSON object containing the custom data for the user.
/// In updating the custom data object, keys which already exist in the object will have their values overwritten, while
/// keys with null values will
/// be removed. No other key-value pairs will be changed apart from those specified in the call.
/// </summary>
[Serializable]
public class UpdateUserDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Key-value pairs to be written to the custom data. Note that keys are trimmed of whitespace, are limited in size, and may
/// not begin with a '!' character or be null.
/// </summary>
public Dictionary<string,string> Data;
/// <summary>
/// Optional list of Data-keys to remove from UserData. Some SDKs cannot insert null-values into Data due to language
/// constraints. Use this to delete the keys directly.
/// </summary>
public List<string> KeysToRemove;
/// <summary>
/// Permission to be applied to all user data keys written in this request. Defaults to "private" if not set.
/// </summary>
public UserDataPermission? Permission;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class UpdateUserDataResult : PlayFabResultCommon
{
/// <summary>
/// Indicates the current version of the data that has been set. This is incremented with every set call for that type of
/// data (read-only, internal, etc). This version can be provided in Get calls to find updated data.
/// </summary>
public uint DataVersion;
}
/// <summary>
/// This function performs an additive update of the arbitrary JSON object containing the custom data for the user.
/// In updating the custom data object, keys which already exist in the object will have their values overwritten, keys with
/// null values will be
/// removed. No other key-value pairs will be changed apart from those specified in the call.
/// </summary>
[Serializable]
public class UpdateUserInternalDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Key-value pairs to be written to the custom data. Note that keys are trimmed of whitespace, are limited in size, and may
/// not begin with a '!' character or be null.
/// </summary>
public Dictionary<string,string> Data;
/// <summary>
/// Optional list of Data-keys to remove from UserData. Some SDKs cannot insert null-values into Data due to language
/// constraints. Use this to delete the keys directly.
/// </summary>
public List<string> KeysToRemove;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// This function performs an additive update of the arbitrary JSON object containing the custom data for the item instance
/// which belongs to the specified user. In updating the custom data object, keys which already exist in the object will
/// have their values overwritten, while
/// keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call.
/// </summary>
[Serializable]
public class UpdateUserInventoryItemDataRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// Key-value pairs to be written to the custom data. Note that keys are trimmed of whitespace, are limited in size, and may
/// not begin with a '!' character or be null.
/// </summary>
public Dictionary<string,string> Data;
/// <summary>
/// Unique PlayFab assigned instance identifier of the item
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Optional list of Data-keys to remove from UserData. Some SDKs cannot insert null-values into Data due to language
/// constraints. Use this to delete the keys directly.
/// </summary>
public List<string> KeysToRemove;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class UserAccountInfo
{
/// <summary>
/// User Android device information, if an Android device has been linked
/// </summary>
public UserAndroidDeviceInfo AndroidDeviceInfo;
/// <summary>
/// Timestamp indicating when the user account was created
/// </summary>
public DateTime Created;
/// <summary>
/// Custom ID information, if a custom ID has been assigned
/// </summary>
public UserCustomIdInfo CustomIdInfo;
/// <summary>
/// User Facebook information, if a Facebook account has been linked
/// </summary>
public UserFacebookInfo FacebookInfo;
/// <summary>
/// Facebook Instant Games account information, if a Facebook Instant Games account has been linked
/// </summary>
public UserFacebookInstantGamesIdInfo FacebookInstantGamesIdInfo;
/// <summary>
/// User Gamecenter information, if a Gamecenter account has been linked
/// </summary>
public UserGameCenterInfo GameCenterInfo;
/// <summary>
/// User Google account information, if a Google account has been linked
/// </summary>
public UserGoogleInfo GoogleInfo;
/// <summary>
/// User iOS device information, if an iOS device has been linked
/// </summary>
public UserIosDeviceInfo IosDeviceInfo;
/// <summary>
/// User Kongregate account information, if a Kongregate account has been linked
/// </summary>
public UserKongregateInfo KongregateInfo;
/// <summary>
/// Nintendo Switch account information, if a Nintendo Switch account has been linked
/// </summary>
public UserNintendoSwitchDeviceIdInfo NintendoSwitchDeviceIdInfo;
/// <summary>
/// OpenID Connect information, if any OpenID Connect accounts have been linked
/// </summary>
public List<UserOpenIdInfo> OpenIdInfo;
/// <summary>
/// Unique identifier for the user account
/// </summary>
public string PlayFabId;
/// <summary>
/// Personal information for the user which is considered more sensitive
/// </summary>
public UserPrivateAccountInfo PrivateInfo;
/// <summary>
/// User PSN account information, if a PSN account has been linked
/// </summary>
public UserPsnInfo PsnInfo;
/// <summary>
/// User Steam information, if a Steam account has been linked
/// </summary>
public UserSteamInfo SteamInfo;
/// <summary>
/// Title-specific information for the user account
/// </summary>
public UserTitleInfo TitleInfo;
/// <summary>
/// User Twitch account information, if a Twitch account has been linked
/// </summary>
public UserTwitchInfo TwitchInfo;
/// <summary>
/// User account name in the PlayFab service
/// </summary>
public string Username;
/// <summary>
/// Windows Hello account information, if a Windows Hello account has been linked
/// </summary>
public UserWindowsHelloInfo WindowsHelloInfo;
/// <summary>
/// User XBox account information, if a XBox account has been linked
/// </summary>
public UserXboxInfo XboxInfo;
}
[Serializable]
public class UserAndroidDeviceInfo
{
/// <summary>
/// Android device ID
/// </summary>
public string AndroidDeviceId;
}
[Serializable]
public class UserCustomIdInfo
{
/// <summary>
/// Custom ID
/// </summary>
public string CustomId;
}
/// <summary>
/// Indicates whether a given data key is private (readable only by the player) or public (readable by all players). When a
/// player makes a GetUserData request about another player, only keys marked Public will be returned.
/// </summary>
public enum UserDataPermission
{
Private,
Public
}
[Serializable]
public class UserDataRecord
{
/// <summary>
/// Timestamp for when this data was last updated.
/// </summary>
public DateTime LastUpdated;
/// <summary>
/// Indicates whether this data can be read by all users (public) or only the user (private). This is used for GetUserData
/// requests being made by one player about another player.
/// </summary>
public UserDataPermission? Permission;
/// <summary>
/// Data stored for the specified user data key.
/// </summary>
public string Value;
}
[Serializable]
public class UserFacebookInfo
{
/// <summary>
/// Facebook identifier
/// </summary>
public string FacebookId;
/// <summary>
/// Facebook full name
/// </summary>
public string FullName;
}
[Serializable]
public class UserFacebookInstantGamesIdInfo
{
/// <summary>
/// Facebook Instant Games ID
/// </summary>
public string FacebookInstantGamesId;
}
[Serializable]
public class UserGameCenterInfo
{
/// <summary>
/// Gamecenter identifier
/// </summary>
public string GameCenterId;
}
[Serializable]
public class UserGoogleInfo
{
/// <summary>
/// Email address of the Google account
/// </summary>
public string GoogleEmail;
/// <summary>
/// Gender information of the Google account
/// </summary>
public string GoogleGender;
/// <summary>
/// Google ID
/// </summary>
public string GoogleId;
/// <summary>
/// Locale of the Google account
/// </summary>
public string GoogleLocale;
}
[Serializable]
public class UserIosDeviceInfo
{
/// <summary>
/// iOS device ID
/// </summary>
public string IosDeviceId;
}
[Serializable]
public class UserKongregateInfo
{
/// <summary>
/// Kongregate ID
/// </summary>
public string KongregateId;
/// <summary>
/// Kongregate Username
/// </summary>
public string KongregateName;
}
[Serializable]
public class UserNintendoSwitchDeviceIdInfo
{
/// <summary>
/// Nintendo Switch Device ID
/// </summary>
public string NintendoSwitchDeviceId;
}
[Serializable]
public class UserOpenIdInfo
{
/// <summary>
/// OpenID Connection ID
/// </summary>
public string ConnectionId;
/// <summary>
/// OpenID Issuer
/// </summary>
public string Issuer;
/// <summary>
/// OpenID Subject
/// </summary>
public string Subject;
}
public enum UserOrigination
{
Organic,
Steam,
Google,
Amazon,
Facebook,
Kongregate,
GamersFirst,
Unknown,
IOS,
LoadTest,
Android,
PSN,
GameCenter,
CustomId,
XboxLive,
Parse,
Twitch,
WindowsHello,
ServerCustomId,
NintendoSwitchDeviceId,
FacebookInstantGamesId,
OpenIdConnect
}
[Serializable]
public class UserPrivateAccountInfo
{
/// <summary>
/// user email address
/// </summary>
public string Email;
}
[Serializable]
public class UserPsnInfo
{
/// <summary>
/// PSN account ID
/// </summary>
public string PsnAccountId;
/// <summary>
/// PSN online ID
/// </summary>
public string PsnOnlineId;
}
[Serializable]
public class UserSettings
{
/// <summary>
/// Boolean for whether this player is eligible for gathering device info.
/// </summary>
public bool GatherDeviceInfo;
/// <summary>
/// Boolean for whether this player should report OnFocus play-time tracking.
/// </summary>
public bool GatherFocusInfo;
/// <summary>
/// Boolean for whether this player is eligible for ad tracking.
/// </summary>
public bool NeedsAttribution;
}
[Serializable]
public class UserSteamInfo
{
/// <summary>
/// what stage of game ownership the user is listed as being in, from Steam
/// </summary>
public TitleActivationStatus? SteamActivationStatus;
/// <summary>
/// the country in which the player resides, from Steam data
/// </summary>
public string SteamCountry;
/// <summary>
/// currency type set in the user Steam account
/// </summary>
public Currency? SteamCurrency;
/// <summary>
/// Steam identifier
/// </summary>
public string SteamId;
}
[Serializable]
public class UserTitleInfo
{
/// <summary>
/// URL to the player's avatar.
/// </summary>
public string AvatarUrl;
/// <summary>
/// timestamp indicating when the user was first associated with this game (this can differ significantly from when the user
/// first registered with PlayFab)
/// </summary>
public DateTime Created;
/// <summary>
/// name of the user, as it is displayed in-game
/// </summary>
public string DisplayName;
/// <summary>
/// timestamp indicating when the user first signed into this game (this can differ from the Created timestamp, as other
/// events, such as issuing a beta key to the user, can associate the title to the user)
/// </summary>
public DateTime? FirstLogin;
/// <summary>
/// boolean indicating whether or not the user is currently banned for a title
/// </summary>
public bool? isBanned;
/// <summary>
/// timestamp for the last user login for this title
/// </summary>
public DateTime? LastLogin;
/// <summary>
/// source by which the user first joined the game, if known
/// </summary>
public UserOrigination? Origination;
/// <summary>
/// Title player account entity for this user
/// </summary>
public EntityKey TitlePlayerAccount;
}
[Serializable]
public class UserTwitchInfo
{
/// <summary>
/// Twitch ID
/// </summary>
public string TwitchId;
/// <summary>
/// Twitch Username
/// </summary>
public string TwitchUserName;
}
[Serializable]
public class UserWindowsHelloInfo
{
/// <summary>
/// Windows Hello Device Name
/// </summary>
public string WindowsHelloDeviceName;
/// <summary>
/// Windows Hello Public Key Hash
/// </summary>
public string WindowsHelloPublicKeyHash;
}
[Serializable]
public class UserXboxInfo
{
/// <summary>
/// XBox user ID
/// </summary>
public string XboxUserId;
}
[Serializable]
public class ValueToDateModel
{
/// <summary>
/// ISO 4217 code of the currency used in the purchases
/// </summary>
public string Currency;
/// <summary>
/// Total value of the purchases in a whole number of 1/100 monetary units. For example, 999 indicates nine dollars and
/// ninety-nine cents when Currency is 'USD')
/// </summary>
public uint TotalValue;
/// <summary>
/// Total value of the purchases in a string representation of decimal monetary units. For example, '9.99' indicates nine
/// dollars and ninety-nine cents when Currency is 'USD'.
/// </summary>
public string TotalValueAsDecimal;
}
[Serializable]
public class VirtualCurrencyRechargeTime
{
/// <summary>
/// Maximum value to which the regenerating currency will automatically increment. Note that it can exceed this value
/// through use of the AddUserVirtualCurrency API call. However, it will not regenerate automatically until it has fallen
/// below this value.
/// </summary>
public int RechargeMax;
/// <summary>
/// Server timestamp in UTC indicating the next time the virtual currency will be incremented.
/// </summary>
public DateTime RechargeTime;
/// <summary>
/// Time remaining (in seconds) before the next recharge increment of the virtual currency.
/// </summary>
public int SecondsToRecharge;
}
[Serializable]
public class WriteEventResponse : PlayFabResultCommon
{
/// <summary>
/// The unique identifier of the event. The values of this identifier consist of ASCII characters and are not constrained to
/// any particular format.
/// </summary>
public string EventId;
}
/// <summary>
/// This API is designed to write a multitude of different event types into PlayStream. It supports a flexible JSON schema,
/// which allowsfor arbitrary key-value pairs to describe any character-based event. The created event will be locked to the
/// authenticated title.
/// </summary>
[Serializable]
public class WriteServerCharacterEventRequest : PlayFabRequestCommon
{
/// <summary>
/// Custom event properties. Each property consists of a name (string) and a value (JSON object).
/// </summary>
public Dictionary<string,object> Body;
/// <summary>
/// Unique PlayFab assigned ID for a specific character owned by a user
/// </summary>
public string CharacterId;
/// <summary>
/// The name of the event, within the namespace scoped to the title. The naming convention is up to the caller, but it
/// commonly follows the subject_verb_object pattern (e.g. player_logged_in).
/// </summary>
public string EventName;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// The time (in UTC) associated with this event. The value dafaults to the current time.
/// </summary>
public DateTime? Timestamp;
}
/// <summary>
/// This API is designed to write a multitude of different event types into PlayStream. It supports a flexible JSON schema,
/// which allowsfor arbitrary key-value pairs to describe any player-based event. The created event will be locked to the
/// authenticated title.
/// </summary>
[Serializable]
public class WriteServerPlayerEventRequest : PlayFabRequestCommon
{
/// <summary>
/// Custom data properties associated with the event. Each property consists of a name (string) and a value (JSON object).
/// </summary>
public Dictionary<string,object> Body;
/// <summary>
/// The name of the event, within the namespace scoped to the title. The naming convention is up to the caller, but it
/// commonly follows the subject_verb_object pattern (e.g. player_logged_in).
/// </summary>
public string EventName;
/// <summary>
/// Unique PlayFab assigned ID of the user on whom the operation will be performed.
/// </summary>
public string PlayFabId;
/// <summary>
/// The time (in UTC) associated with this event. The value dafaults to the current time.
/// </summary>
public DateTime? Timestamp;
}
/// <summary>
/// This API is designed to write a multitude of different event types into PlayStream. It supports a flexible JSON schema,
/// which allowsfor arbitrary key-value pairs to describe any title-based event. The created event will be locked to the
/// authenticated title.
/// </summary>
[Serializable]
public class WriteTitleEventRequest : PlayFabRequestCommon
{
/// <summary>
/// Custom event properties. Each property consists of a name (string) and a value (JSON object).
/// </summary>
public Dictionary<string,object> Body;
/// <summary>
/// The name of the event, within the namespace scoped to the title. The naming convention is up to the caller, but it
/// commonly follows the subject_verb_object pattern (e.g. player_logged_in).
/// </summary>
public string EventName;
/// <summary>
/// The time (in UTC) associated with this event. The value dafaults to the current time.
/// </summary>
public DateTime? Timestamp;
}
[Serializable]
public class XboxLiveAccountPlayFabIdPair
{
/// <summary>
/// Unique PlayFab identifier for a user, or null if no PlayFab account is linked to the Xbox Live identifier.
/// </summary>
public string PlayFabId;
/// <summary>
/// Unique Xbox Live identifier for a user.
/// </summary>
public string XboxLiveAccountId;
}
}
#endif
| 34.27526 | 132 | 0.609268 | [
"MIT"
] | BrianPeek/Scavenger | src/Unity/Assets/PlayFabSdk/Server/PlayFabServerModels.cs | 207,948 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Linq;
using System.Reflection;
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using FluentAssertions;
using Nest;
using System.Runtime.Serialization;
using Tests.Core.Xunit;
using Tests.Framework;
namespace Tests.CodeStandards
{
[ProjectReferenceOnly]
public class QueriesStandards
{
protected static PropertyInfo[] QueryProperties = typeof(IQueryContainer).GetProperties();
protected static PropertyInfo[] QueryPlaceHolderProperties = typeof(IQueryContainer).GetProperties()
.Where(a=>!a.GetCustomAttributes<IgnoreDataMemberAttribute>().Any()).ToArray();
/*
* All properties must be either marked with IgnoreDataMemberAttribute or DataMemberAttribute
*/
[U] public void InterfacePropertiesMustBeMarkedExplicitly()
{
var properties = from p in QueryProperties
let a = p.GetCustomAttributes<IgnoreDataMemberAttribute>()
.Concat<Attribute>(p.GetCustomAttributes<DataMemberAttribute>())
where a.Count() != 1
select p;
properties.Should().BeEmpty();
}
[U] public void StaticQueryExposesAll()
{
var staticProperties = from p in typeof(Query<>).GetMethods()
let name = p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name
select name;
var placeHolders = QueryPlaceHolderProperties.Select(p => p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name);
staticProperties.Distinct().Should().Contain(placeHolders.Distinct());
}
[U] public void FluentDescriptorExposesAll()
{
var fluentMethods = from p in typeof(QueryContainerDescriptor<>).GetMethods()
let name = p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name
select name;
var placeHolders = QueryPlaceHolderProperties.Select(p => p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name);
fluentMethods.Distinct().Should().Contain(placeHolders.Distinct());
}
[U] public void VisitorVisitsAll()
{
var skipQueryImplementations = new[]
{
typeof(IFieldNameQuery),
typeof(IFuzzyQuery<,>),
typeof(IConditionlessQuery),
typeof(ISpanGapQuery)
};
var queries = typeof(IQuery).Assembly.ExportedTypes
.Where(t => t.IsInterface && typeof(IQuery).IsAssignableFrom(t))
.Where(t => !skipQueryImplementations.Contains(t))
.ToList();
queries.Should().NotBeEmpty();
var visitMethods = typeof(IQueryVisitor).GetMethods().Where(m => m.Name == "Visit");
visitMethods.Should().NotBeEmpty();
var missingTypes = from q in queries
let visitMethod = visitMethods.FirstOrDefault(m => m.GetParameters().First().ParameterType == q)
where visitMethod == null
select q;
missingTypes.Should().BeEmpty();
}
}
}
| 36.182927 | 115 | 0.695315 | [
"Apache-2.0"
] | Brightspace/elasticsearch-net | tests/Tests/CodeStandards/Queries.doc.cs | 2,969 | C# |
namespace ml_lme
{
static class Settings
{
static bool ms_enabled = false;
static bool ms_leapHmdMode = false;
static bool ms_headRoot = false;
static bool ms_sdk3Parameters = false;
static bool ms_fingersTracking = false;
static float ms_desktopOffsetY = -0.5f;
static float ms_desktopOffsetZ = 0.4f;
static float ms_hmdOffsetY = -0.15f;
static float ms_hmdOffsetZ = 0.15f;
static float ms_rootRotation = 0f;
public static void LoadSettings()
{
MelonLoader.MelonPreferences.CreateCategory("LME", "Leap Motion extension");
MelonLoader.MelonPreferences.CreateEntry("LME", "Enabled", ms_enabled, "Enable hands tracking");
MelonLoader.MelonPreferences.CreateEntry("LME", "LeapHmdMode", ms_leapHmdMode, "HMD mode");
MelonLoader.MelonPreferences.CreateEntry("LME", "HeadRoot", ms_headRoot, "Head as root point");
MelonLoader.MelonPreferences.CreateEntry("LME", "Sdk3Parameters", ms_sdk3Parameters, "Set avatar SDK3 parameters");
MelonLoader.MelonPreferences.CreateEntry("LME", "FingersTracking", ms_fingersTracking, "Fingers tracking only");
MelonLoader.MelonPreferences.CreateEntry("LME", "DesktopOffsetY", ms_desktopOffsetY, "Desktop Y axis (up) offset");
MelonLoader.MelonPreferences.CreateEntry("LME", "DesktopOffsetZ", ms_desktopOffsetZ, "Desktop Z axis (forward) offset");
MelonLoader.MelonPreferences.CreateEntry("LME", "HmdOffsetY", ms_hmdOffsetY, "HMD Y axis (up) offset");
MelonLoader.MelonPreferences.CreateEntry("LME", "HmdOffsetZ", ms_hmdOffsetZ, "HMD Z axis (forward) offset");
MelonLoader.MelonPreferences.CreateEntry("LME", "RootRotation", ms_rootRotation, "Root X axis rotation (for neck mounts)");
ReloadSettings();
}
public static void ReloadSettings()
{
ms_enabled = MelonLoader.MelonPreferences.GetEntryValue<bool>("LME", "Enabled");
ms_leapHmdMode = MelonLoader.MelonPreferences.GetEntryValue<bool>("LME", "LeapHmdMode");
ms_headRoot = MelonLoader.MelonPreferences.GetEntryValue<bool>("LME", "HeadRoot");
ms_sdk3Parameters = MelonLoader.MelonPreferences.GetEntryValue<bool>("LME", "Sdk3Parameters");
ms_fingersTracking = MelonLoader.MelonPreferences.GetEntryValue<bool>("LME", "FingersTracking");
ms_desktopOffsetY = MelonLoader.MelonPreferences.GetEntryValue<float>("LME", "DesktopOffsetY");
ms_desktopOffsetZ = MelonLoader.MelonPreferences.GetEntryValue<float>("LME", "DesktopOffsetZ");
ms_hmdOffsetY = MelonLoader.MelonPreferences.GetEntryValue<float>("LME", "HmdOffsetY");
ms_hmdOffsetZ = MelonLoader.MelonPreferences.GetEntryValue<float>("LME", "HmdOffsetZ");
ms_rootRotation = MelonLoader.MelonPreferences.GetEntryValue<float>("LME", "RootRotation");
}
public static bool Enabled
{
get => ms_enabled;
}
public static bool LeapHmdMode
{
get => ms_leapHmdMode;
}
public static bool HeadRoot
{
get => ms_headRoot;
}
public static bool SDK3Parameters
{
get => ms_sdk3Parameters;
}
public static bool FingersTracking
{
get => ms_fingersTracking;
}
public static float DesktopOffsetY
{
get => ms_desktopOffsetY;
}
public static float DesktopOffsetZ
{
get => ms_desktopOffsetZ;
}
public static float HmdOffsetY
{
get => ms_hmdOffsetY;
}
public static float HmdOffsetZ
{
get => ms_hmdOffsetZ;
}
public static float RootRotation
{
get => ms_rootRotation;
}
}
}
| 40.336735 | 135 | 0.636226 | [
"MIT"
] | nonce-twice/ml_mods | ml_lme/Settings.cs | 3,955 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// Defines a SCIM user.
/// </summary>
[DataContract]
public partial class ScimV2User : IEquatable<ScimV2User>
{
/// <summary>
/// Initializes a new instance of the <see cref="ScimV2User" /> class.
/// </summary>
/// <param name="Schemas">The list of supported schemas..</param>
/// <param name="Active">Indicates whether the user's administrative status is active..</param>
/// <param name="UserName">The user's Genesys Cloud email address. Must be unique..</param>
/// <param name="DisplayName">The display name of the user..</param>
/// <param name="Password">The new password for the Genesys Cloud user. Does not return an existing password. When creating a user, if a password is not supplied, then a password will be randomly generated that is 40 characters in length and contains five characters from each of the password policy groups..</param>
/// <param name="Title">The user's title..</param>
/// <param name="PhoneNumbers">The list of the user's phone numbers..</param>
/// <param name="Emails">The list of the user's email addresses..</param>
/// <param name="ExternalId">The external ID of the user. Set by the provisioning client. \"caseExact\" is set to \"true\". \"mutability\" is set to \"readWrite\"..</param>
/// <param name="Groups">The list of groups that the user is a member of..</param>
/// <param name="Roles">The list of roles assigned to the user..</param>
/// <param name="Urnietfparamsscimschemasextensionenterprise20User">The URI of the schema for the enterprise user..</param>
/// <param name="Urnietfparamsscimschemasextensiongenesyspurecloud20User">The URI of the schema for the Genesys Cloud user..</param>
/// <param name="Meta">The metadata of the SCIM resource..</param>
public ScimV2User(List<string> Schemas = null, bool? Active = null, string UserName = null, string DisplayName = null, string Password = null, string Title = null, List<ScimPhoneNumber> PhoneNumbers = null, List<ScimEmail> Emails = null, string ExternalId = null, List<ScimV2GroupReference> Groups = null, List<ScimUserRole> Roles = null, ScimV2EnterpriseUser Urnietfparamsscimschemasextensionenterprise20User = null, ScimUserExtensions Urnietfparamsscimschemasextensiongenesyspurecloud20User = null, ScimMetadata Meta = null)
{
this.Schemas = Schemas;
this.Active = Active;
this.UserName = UserName;
this.DisplayName = DisplayName;
this.Password = Password;
this.Title = Title;
this.PhoneNumbers = PhoneNumbers;
this.Emails = Emails;
this.ExternalId = ExternalId;
this.Groups = Groups;
this.Roles = Roles;
this.Urnietfparamsscimschemasextensionenterprise20User = Urnietfparamsscimschemasextensionenterprise20User;
this.Urnietfparamsscimschemasextensiongenesyspurecloud20User = Urnietfparamsscimschemasextensiongenesyspurecloud20User;
this.Meta = Meta;
}
/// <summary>
/// The ID of the SCIM resource. Set by the service provider. \"caseExact\" is set to \"true\". \"mutability\" is set to \"readOnly\". \"returned\" is set to \"always\".
/// </summary>
/// <value>The ID of the SCIM resource. Set by the service provider. \"caseExact\" is set to \"true\". \"mutability\" is set to \"readOnly\". \"returned\" is set to \"always\".</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; private set; }
/// <summary>
/// The list of supported schemas.
/// </summary>
/// <value>The list of supported schemas.</value>
[DataMember(Name="schemas", EmitDefaultValue=false)]
public List<string> Schemas { get; set; }
/// <summary>
/// Indicates whether the user's administrative status is active.
/// </summary>
/// <value>Indicates whether the user's administrative status is active.</value>
[DataMember(Name="active", EmitDefaultValue=false)]
public bool? Active { get; set; }
/// <summary>
/// The user's Genesys Cloud email address. Must be unique.
/// </summary>
/// <value>The user's Genesys Cloud email address. Must be unique.</value>
[DataMember(Name="userName", EmitDefaultValue=false)]
public string UserName { get; set; }
/// <summary>
/// The display name of the user.
/// </summary>
/// <value>The display name of the user.</value>
[DataMember(Name="displayName", EmitDefaultValue=false)]
public string DisplayName { get; set; }
/// <summary>
/// The new password for the Genesys Cloud user. Does not return an existing password. When creating a user, if a password is not supplied, then a password will be randomly generated that is 40 characters in length and contains five characters from each of the password policy groups.
/// </summary>
/// <value>The new password for the Genesys Cloud user. Does not return an existing password. When creating a user, if a password is not supplied, then a password will be randomly generated that is 40 characters in length and contains five characters from each of the password policy groups.</value>
[DataMember(Name="password", EmitDefaultValue=false)]
public string Password { get; set; }
/// <summary>
/// The user's title.
/// </summary>
/// <value>The user's title.</value>
[DataMember(Name="title", EmitDefaultValue=false)]
public string Title { get; set; }
/// <summary>
/// The list of the user's phone numbers.
/// </summary>
/// <value>The list of the user's phone numbers.</value>
[DataMember(Name="phoneNumbers", EmitDefaultValue=false)]
public List<ScimPhoneNumber> PhoneNumbers { get; set; }
/// <summary>
/// The list of the user's email addresses.
/// </summary>
/// <value>The list of the user's email addresses.</value>
[DataMember(Name="emails", EmitDefaultValue=false)]
public List<ScimEmail> Emails { get; set; }
/// <summary>
/// The external ID of the user. Set by the provisioning client. \"caseExact\" is set to \"true\". \"mutability\" is set to \"readWrite\".
/// </summary>
/// <value>The external ID of the user. Set by the provisioning client. \"caseExact\" is set to \"true\". \"mutability\" is set to \"readWrite\".</value>
[DataMember(Name="externalId", EmitDefaultValue=false)]
public string ExternalId { get; set; }
/// <summary>
/// The list of groups that the user is a member of.
/// </summary>
/// <value>The list of groups that the user is a member of.</value>
[DataMember(Name="groups", EmitDefaultValue=false)]
public List<ScimV2GroupReference> Groups { get; set; }
/// <summary>
/// The list of roles assigned to the user.
/// </summary>
/// <value>The list of roles assigned to the user.</value>
[DataMember(Name="roles", EmitDefaultValue=false)]
public List<ScimUserRole> Roles { get; set; }
/// <summary>
/// The URI of the schema for the enterprise user.
/// </summary>
/// <value>The URI of the schema for the enterprise user.</value>
[DataMember(Name="urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", EmitDefaultValue=false)]
public ScimV2EnterpriseUser Urnietfparamsscimschemasextensionenterprise20User { get; set; }
/// <summary>
/// The URI of the schema for the Genesys Cloud user.
/// </summary>
/// <value>The URI of the schema for the Genesys Cloud user.</value>
[DataMember(Name="urn:ietf:params:scim:schemas:extension:genesys:purecloud:2.0:User", EmitDefaultValue=false)]
public ScimUserExtensions Urnietfparamsscimschemasextensiongenesyspurecloud20User { get; set; }
/// <summary>
/// The metadata of the SCIM resource.
/// </summary>
/// <value>The metadata of the SCIM resource.</value>
[DataMember(Name="meta", EmitDefaultValue=false)]
public ScimMetadata Meta { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ScimV2User {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Schemas: ").Append(Schemas).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" UserName: ").Append(UserName).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" Title: ").Append(Title).Append("\n");
sb.Append(" PhoneNumbers: ").Append(PhoneNumbers).Append("\n");
sb.Append(" Emails: ").Append(Emails).Append("\n");
sb.Append(" ExternalId: ").Append(ExternalId).Append("\n");
sb.Append(" Groups: ").Append(Groups).Append("\n");
sb.Append(" Roles: ").Append(Roles).Append("\n");
sb.Append(" Urnietfparamsscimschemasextensionenterprise20User: ").Append(Urnietfparamsscimschemasextensionenterprise20User).Append("\n");
sb.Append(" Urnietfparamsscimschemasextensiongenesyspurecloud20User: ").Append(Urnietfparamsscimschemasextensiongenesyspurecloud20User).Append("\n");
sb.Append(" Meta: ").Append(Meta).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ScimV2User);
}
/// <summary>
/// Returns true if ScimV2User instances are equal
/// </summary>
/// <param name="other">Instance of ScimV2User to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ScimV2User other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Schemas == other.Schemas ||
this.Schemas != null &&
this.Schemas.SequenceEqual(other.Schemas)
) &&
(
this.Active == other.Active ||
this.Active != null &&
this.Active.Equals(other.Active)
) &&
(
this.UserName == other.UserName ||
this.UserName != null &&
this.UserName.Equals(other.UserName)
) &&
(
this.DisplayName == other.DisplayName ||
this.DisplayName != null &&
this.DisplayName.Equals(other.DisplayName)
) &&
(
this.Password == other.Password ||
this.Password != null &&
this.Password.Equals(other.Password)
) &&
(
this.Title == other.Title ||
this.Title != null &&
this.Title.Equals(other.Title)
) &&
(
this.PhoneNumbers == other.PhoneNumbers ||
this.PhoneNumbers != null &&
this.PhoneNumbers.SequenceEqual(other.PhoneNumbers)
) &&
(
this.Emails == other.Emails ||
this.Emails != null &&
this.Emails.SequenceEqual(other.Emails)
) &&
(
this.ExternalId == other.ExternalId ||
this.ExternalId != null &&
this.ExternalId.Equals(other.ExternalId)
) &&
(
this.Groups == other.Groups ||
this.Groups != null &&
this.Groups.SequenceEqual(other.Groups)
) &&
(
this.Roles == other.Roles ||
this.Roles != null &&
this.Roles.SequenceEqual(other.Roles)
) &&
(
this.Urnietfparamsscimschemasextensionenterprise20User == other.Urnietfparamsscimschemasextensionenterprise20User ||
this.Urnietfparamsscimschemasextensionenterprise20User != null &&
this.Urnietfparamsscimschemasextensionenterprise20User.Equals(other.Urnietfparamsscimschemasextensionenterprise20User)
) &&
(
this.Urnietfparamsscimschemasextensiongenesyspurecloud20User == other.Urnietfparamsscimschemasextensiongenesyspurecloud20User ||
this.Urnietfparamsscimschemasextensiongenesyspurecloud20User != null &&
this.Urnietfparamsscimschemasextensiongenesyspurecloud20User.Equals(other.Urnietfparamsscimschemasextensiongenesyspurecloud20User)
) &&
(
this.Meta == other.Meta ||
this.Meta != null &&
this.Meta.Equals(other.Meta)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Schemas != null)
hash = hash * 59 + this.Schemas.GetHashCode();
if (this.Active != null)
hash = hash * 59 + this.Active.GetHashCode();
if (this.UserName != null)
hash = hash * 59 + this.UserName.GetHashCode();
if (this.DisplayName != null)
hash = hash * 59 + this.DisplayName.GetHashCode();
if (this.Password != null)
hash = hash * 59 + this.Password.GetHashCode();
if (this.Title != null)
hash = hash * 59 + this.Title.GetHashCode();
if (this.PhoneNumbers != null)
hash = hash * 59 + this.PhoneNumbers.GetHashCode();
if (this.Emails != null)
hash = hash * 59 + this.Emails.GetHashCode();
if (this.ExternalId != null)
hash = hash * 59 + this.ExternalId.GetHashCode();
if (this.Groups != null)
hash = hash * 59 + this.Groups.GetHashCode();
if (this.Roles != null)
hash = hash * 59 + this.Roles.GetHashCode();
if (this.Urnietfparamsscimschemasextensionenterprise20User != null)
hash = hash * 59 + this.Urnietfparamsscimschemasextensionenterprise20User.GetHashCode();
if (this.Urnietfparamsscimschemasextensiongenesyspurecloud20User != null)
hash = hash * 59 + this.Urnietfparamsscimschemasextensiongenesyspurecloud20User.GetHashCode();
if (this.Meta != null)
hash = hash * 59 + this.Meta.GetHashCode();
return hash;
}
}
}
}
| 39.896842 | 534 | 0.53327 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/ScimV2User.cs | 18,951 | C# |
namespace DotNetPivotalTrackerApi.Models.Stories
{
public class PivotalLabel : PivotalModel
{
public int? Id { get; set; }
public string Name { get; set; }
public int? ProjectId { get; set; }
}
}
| 23.3 | 49 | 0.613734 | [
"MIT"
] | mbrewerton/DotNetPivotalTrackerApi | PivotalTrackerApi/Models/Stories/PivotalLabel.cs | 235 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WorkData.ControlCenter.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WorkData.ControlCenter.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆盖当前线程的 CurrentUICulture 属性
/// 使用此强类型的资源类的资源查找。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 34.111111 | 188 | 0.577769 | [
"MIT"
] | wulaiwei/WorkData.KeySpaceCallback | WorkData.ControlCenter/Properties/Resources.Designer.cs | 2,786 | C# |
using System.Web;
using System.Web.Mvc;
namespace MVCChat
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 18.571429 | 80 | 0.65 | [
"MIT"
] | LesterAGarciaA97/Project_EDII | Solucion/ApiChat/MVCChat/App_Start/FilterConfig.cs | 262 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace PlatformSpecificLabels.WinPhone81
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Xamarin.Forms.Platform.WinRT.WindowsPhonePage
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
LoadApplication(new PlatformSpecificLabels.App());
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
}
}
| 34.901961 | 94 | 0.68427 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter08/PlatformSpecificLabels/PlatformSpecificLabels/PlatformSpecificLabels.WinPhone81/MainPage.xaml.cs | 1,782 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using mbs.cardlandia.chat.webapi.Areas.HelpPage.ModelDescriptions;
using mbs.cardlandia.chat.webapi.Areas.HelpPage.Models;
namespace mbs.cardlandia.chat.webapi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| 51.547009 | 196 | 0.62328 | [
"MIT"
] | jcapellman/Cards-of-Phantasia | Src/mbs.cardlandia.chat.webapi/Areas/HelpPage/HelpPageConfigurationExtensions.cs | 24,124 | C# |
using Highcharts4Net.Library.Helpers;
namespace Highcharts4Net.Library.Options
{
public class SeriesDataMarker
{
/// <summary>
/// Enable or disable the point marker.
/// Default: true
/// </summary>
public bool? Enabled { get; set; }
/// <summary>
/// The fill color of the point marker. When <code>null</code>, the series' or point's color is used.
/// </summary>
public ColorOrGradient FillColor { get; set; }
/// <summary>
/// The color of the point marker's outline. When <code>null</code>, the series' or point's color is used.
/// Default: #FFFFFF
/// </summary>
public string LineColor { get; set; }
/// <summary>
/// The width of the point marker's outline.
/// Default: 0
/// </summary>
public HighchartsDataPoint? LineWidth { get; set; }
/// <summary>
/// The radius of the point marker.
/// Default: 4
/// </summary>
public HighchartsDataPoint? Radius { get; set; }
public SeriesDataMarkerStates States { get; set; }
/// <summary>
/// <p>A predefined shape or symbol for the marker. When null, the symbol is pulled from options.symbols. Other possible values are 'circle', 'square', 'diamond', 'triangle' and 'triangle-down'.</p><p>Additionally, the URL to a graphic can be given on this form: 'url(graphic.png)'. Note that for the image to be applied to exported charts, its URL needs to be accessible by the export server.</p><p>Custom callbacks for symbol path generation can also be added to <code>Highcharts.SVGRenderer.prototype.symbols</code>. The callback is then used by its method name, as shown in the demo.</p>
/// </summary>
public string Symbol { get; set; }
}
} | 35.340426 | 594 | 0.680915 | [
"MIT"
] | davcs86/Highcharts4Net | Highcharts4Net/Library/Options/SeriesDataMarker.cs | 1,661 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace pxr {
public class NdrRegistry : global::System.IDisposable {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
protected bool swigCMemOwn;
internal NdrRegistry(global::System.IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(NdrRegistry obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
throw new global::System.MethodAccessException("C++ destructor does not have public access");
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
global::System.GC.SuppressFinalize(this);
}
}
public static NdrRegistry GetInstance() {
NdrRegistry ret = new NdrRegistry(UsdCsPINVOKE.NdrRegistry_GetInstance(), false);
return ret;
}
public void SetExtraDiscoveryPlugins(SWIGTYPE_p_TfDeclarePtrsT_NdrDiscoveryPlugin_t__RefPtrVector plugins) {
UsdCsPINVOKE.NdrRegistry_SetExtraDiscoveryPlugins__SWIG_0(swigCPtr, SWIGTYPE_p_TfDeclarePtrsT_NdrDiscoveryPlugin_t__RefPtrVector.getCPtr(plugins));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public void SetExtraDiscoveryPlugins(TfTypeVector pluginTypes) {
UsdCsPINVOKE.NdrRegistry_SetExtraDiscoveryPlugins__SWIG_1(swigCPtr, TfTypeVector.getCPtr(pluginTypes));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public void SetExtraParserPlugins(TfTypeVector pluginTypes) {
UsdCsPINVOKE.NdrRegistry_SetExtraParserPlugins(swigCPtr, TfTypeVector.getCPtr(pluginTypes));
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
}
public NdrNode GetNodeFromAsset(SdfAssetPath asset, SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t metadata, TfToken subIdentifier, TfToken sourceType) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeFromAsset__SWIG_0(swigCPtr, SdfAssetPath.getCPtr(asset), SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t.getCPtr(metadata), TfToken.getCPtr(subIdentifier), TfToken.getCPtr(sourceType));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeFromAsset(SdfAssetPath asset, SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t metadata, TfToken subIdentifier) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeFromAsset__SWIG_1(swigCPtr, SdfAssetPath.getCPtr(asset), SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t.getCPtr(metadata), TfToken.getCPtr(subIdentifier));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeFromAsset(SdfAssetPath asset, SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t metadata) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeFromAsset__SWIG_2(swigCPtr, SdfAssetPath.getCPtr(asset), SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t.getCPtr(metadata));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeFromSourceCode(string sourceCode, TfToken sourceType, SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t metadata) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeFromSourceCode(swigCPtr, sourceCode, TfToken.getCPtr(sourceType), SWIGTYPE_p_std__unordered_mapT_TfToken_std__string_TfToken__HashFunctor_t.getCPtr(metadata));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public StdStringVector GetSearchURIs() {
StdStringVector ret = new StdStringVector(UsdCsPINVOKE.NdrRegistry_GetSearchURIs(swigCPtr), true);
return ret;
}
public TfTokenVector GetNodeIdentifiers(TfToken family, NdrVersionFilter filter) {
TfTokenVector ret = new TfTokenVector(UsdCsPINVOKE.NdrRegistry_GetNodeIdentifiers__SWIG_0(swigCPtr, TfToken.getCPtr(family), (int)filter), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public TfTokenVector GetNodeIdentifiers(TfToken family) {
TfTokenVector ret = new TfTokenVector(UsdCsPINVOKE.NdrRegistry_GetNodeIdentifiers__SWIG_1(swigCPtr, TfToken.getCPtr(family)), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public TfTokenVector GetNodeIdentifiers() {
TfTokenVector ret = new TfTokenVector(UsdCsPINVOKE.NdrRegistry_GetNodeIdentifiers__SWIG_2(swigCPtr), true);
return ret;
}
public StdStringVector GetNodeNames(TfToken family) {
StdStringVector ret = new StdStringVector(UsdCsPINVOKE.NdrRegistry_GetNodeNames__SWIG_0(swigCPtr, TfToken.getCPtr(family)), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public StdStringVector GetNodeNames() {
StdStringVector ret = new StdStringVector(UsdCsPINVOKE.NdrRegistry_GetNodeNames__SWIG_1(swigCPtr), true);
return ret;
}
public NdrNode GetNodeByIdentifier(TfToken identifier, TfTokenVector typePriority) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByIdentifier__SWIG_0(swigCPtr, TfToken.getCPtr(identifier), TfTokenVector.getCPtr(typePriority));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeByIdentifier(TfToken identifier) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByIdentifier__SWIG_1(swigCPtr, TfToken.getCPtr(identifier));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeByIdentifierAndType(TfToken identifier, TfToken nodeType) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByIdentifierAndType(swigCPtr, TfToken.getCPtr(identifier), TfToken.getCPtr(nodeType));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeByName(string name, TfTokenVector typePriority, NdrVersionFilter filter) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByName__SWIG_0(swigCPtr, name, TfTokenVector.getCPtr(typePriority), (int)filter);
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeByName(string name, TfTokenVector typePriority) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByName__SWIG_1(swigCPtr, name, TfTokenVector.getCPtr(typePriority));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeByName(string name) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByName__SWIG_2(swigCPtr, name);
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeByNameAndType(string name, TfToken nodeType, NdrVersionFilter filter) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByNameAndType__SWIG_0(swigCPtr, name, TfToken.getCPtr(nodeType), (int)filter);
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public NdrNode GetNodeByNameAndType(string name, TfToken nodeType) {
global::System.IntPtr cPtr = UsdCsPINVOKE.NdrRegistry_GetNodeByNameAndType__SWIG_1(swigCPtr, name, TfToken.getCPtr(nodeType));
NdrNode ret = (cPtr == global::System.IntPtr.Zero) ? null : new NdrNode(cPtr, false);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_std__vectorT_NdrNode_const_p_t GetNodesByIdentifier(TfToken identifier) {
SWIGTYPE_p_std__vectorT_NdrNode_const_p_t ret = new SWIGTYPE_p_std__vectorT_NdrNode_const_p_t(UsdCsPINVOKE.NdrRegistry_GetNodesByIdentifier(swigCPtr, TfToken.getCPtr(identifier)), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_std__vectorT_NdrNode_const_p_t GetNodesByName(string name, NdrVersionFilter filter) {
SWIGTYPE_p_std__vectorT_NdrNode_const_p_t ret = new SWIGTYPE_p_std__vectorT_NdrNode_const_p_t(UsdCsPINVOKE.NdrRegistry_GetNodesByName__SWIG_0(swigCPtr, name, (int)filter), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_std__vectorT_NdrNode_const_p_t GetNodesByName(string name) {
SWIGTYPE_p_std__vectorT_NdrNode_const_p_t ret = new SWIGTYPE_p_std__vectorT_NdrNode_const_p_t(UsdCsPINVOKE.NdrRegistry_GetNodesByName__SWIG_1(swigCPtr, name), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_std__vectorT_NdrNode_const_p_t GetNodesByFamily(TfToken family, NdrVersionFilter filter) {
SWIGTYPE_p_std__vectorT_NdrNode_const_p_t ret = new SWIGTYPE_p_std__vectorT_NdrNode_const_p_t(UsdCsPINVOKE.NdrRegistry_GetNodesByFamily__SWIG_0(swigCPtr, TfToken.getCPtr(family), (int)filter), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_std__vectorT_NdrNode_const_p_t GetNodesByFamily(TfToken family) {
SWIGTYPE_p_std__vectorT_NdrNode_const_p_t ret = new SWIGTYPE_p_std__vectorT_NdrNode_const_p_t(UsdCsPINVOKE.NdrRegistry_GetNodesByFamily__SWIG_1(swigCPtr, TfToken.getCPtr(family)), true);
if (UsdCsPINVOKE.SWIGPendingException.Pending) throw UsdCsPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public SWIGTYPE_p_std__vectorT_NdrNode_const_p_t GetNodesByFamily() {
SWIGTYPE_p_std__vectorT_NdrNode_const_p_t ret = new SWIGTYPE_p_std__vectorT_NdrNode_const_p_t(UsdCsPINVOKE.NdrRegistry_GetNodesByFamily__SWIG_2(swigCPtr), true);
return ret;
}
public TfTokenVector GetAllNodeSourceTypes() {
TfTokenVector ret = new TfTokenVector(UsdCsPINVOKE.NdrRegistry_GetAllNodeSourceTypes(swigCPtr), true);
return ret;
}
}
}
| 56.621005 | 276 | 0.788226 | [
"Apache-2.0"
] | MrDice/usd-unity-sdk | src/USD.NET/generated/pxr/usd/ndr/NdrRegistry.cs | 12,400 | C# |
// <auto-generated />
using System;
using Haro.AdminPanel.DataAccess;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Haro.AdminPanel.Migrations
{
[DbContext(typeof(AdminPanelContext))]
[Migration("20201109145238_init4")]
partial class init4
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.7")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.Column", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ColumnSize")
.HasColumnType("nvarchar(max)");
b.Property<int>("ColumnType")
.HasColumnType("int");
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.HasColumnType("nvarchar(max)");
b.Property<int>("FormOrder")
.HasColumnType("int");
b.Property<int>("Max")
.HasColumnType("int");
b.Property<int>("Min")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<bool>("ShowInList")
.HasColumnType("bit");
b.Property<long>("TableId")
.HasColumnType("bigint");
b.Property<long>("TargetColumnId")
.HasColumnType("bigint");
b.Property<string>("TargetTable")
.HasColumnType("nvarchar(max)");
b.Property<long>("TargetTableId")
.HasColumnType("bigint");
b.Property<string>("TargetTableTextColumn")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("TableId");
b.ToTable("Columns");
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.Language", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Code")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<string>("DisplayValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("Image")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Languages");
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.Module", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<int>("DisplayOrder")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Modules");
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.SiteInformation", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<string>("ProjectName")
.HasColumnType("nvarchar(max)");
b.Property<int>("SmtPort")
.HasColumnType("int");
b.Property<bool>("SmtpEnableSsl")
.HasColumnType("bit");
b.Property<string>("SmtpPassword")
.HasColumnType("nvarchar(max)");
b.Property<string>("SmtpServer")
.HasColumnType("nvarchar(max)");
b.Property<string>("SmtpUserName")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("SiteInformations");
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.Table", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<string>("DisplayName")
.HasColumnType("nvarchar(max)");
b.Property<long>("ModuleId")
.HasColumnType("bigint");
b.Property<bool>("MultipleLanguage")
.HasColumnType("bit");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<bool>("Show")
.HasColumnType("bit");
b.HasKey("Id");
b.HasIndex("ModuleId");
b.HasIndex("Name")
.IsUnique()
.HasFilter("[Name] IS NOT NULL");
b.ToTable("Tables");
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<int>("Role")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique()
.HasFilter("[Email] IS NOT NULL");
b.ToTable("Users");
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.UserModule", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2");
b.Property<long>("ModuleId")
.HasColumnType("bigint");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("ModuleId");
b.HasIndex("UserId");
b.ToTable("UserModules");
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.Column", b =>
{
b.HasOne("Haro.AdminPanel.Models.Entities.Table", "Table")
.WithMany("Columns")
.HasForeignKey("TableId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.Table", b =>
{
b.HasOne("Haro.AdminPanel.Models.Entities.Module", "Module")
.WithMany("Tables")
.HasForeignKey("ModuleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Haro.AdminPanel.Models.Entities.UserModule", b =>
{
b.HasOne("Haro.AdminPanel.Models.Entities.Module", "Module")
.WithMany("Users")
.HasForeignKey("ModuleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Haro.AdminPanel.Models.Entities.User", "User")
.WithMany("Modules")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.660839 | 125 | 0.467525 | [
"MIT"
] | harunmarangoz/Haro.AdminPanel | Haro.AdminPanel/Migrations/20201109145238_init4.Designer.cs | 10,487 | C# |
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
namespace BigCommerceSharp.Model {
/// <summary>
/// Data about the response, including pagination and collection totals.
/// </summary>
[DataContract]
public class PaginationFull1 {
/// <summary>
/// Total number of items in the result set.
/// </summary>
/// <value>Total number of items in the result set. </value>
[DataMember(Name="total", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "total")]
public int? Total { get; set; }
/// <summary>
/// Total number of items in the collection response.
/// </summary>
/// <value>Total number of items in the collection response. </value>
[DataMember(Name="count", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "count")]
public int? Count { get; set; }
/// <summary>
/// The amount of items returned in the collection per page, controlled by the limit parameter.
/// </summary>
/// <value>The amount of items returned in the collection per page, controlled by the limit parameter. </value>
[DataMember(Name="per_page", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "per_page")]
public int? PerPage { get; set; }
/// <summary>
/// The page you are currently on within the collection.
/// </summary>
/// <value>The page you are currently on within the collection. </value>
[DataMember(Name="current_page", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "current_page")]
public int? CurrentPage { get; set; }
/// <summary>
/// The total number of pages in the collection.
/// </summary>
/// <value>The total number of pages in the collection. </value>
[DataMember(Name="total_pages", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "total_pages")]
public int? TotalPages { get; set; }
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name="links", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "links")]
public PaginationFull1Links Links { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class PaginationFull1 {\n");
sb.Append(" Total: ").Append(Total).Append("\n");
sb.Append(" Count: ").Append(Count).Append("\n");
sb.Append(" PerPage: ").Append(PerPage).Append("\n");
sb.Append(" CurrentPage: ").Append(CurrentPage).Append("\n");
sb.Append(" TotalPages: ").Append(TotalPages).Append("\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| 35.471264 | 115 | 0.642579 | [
"MIT"
] | PrimePenguin/BigCommerceSharp | BigCommerceSharp/Model/PaginationFull1.cs | 3,086 | C# |
// <copyright file="TimerMode.cs" company="Traced-Ideas, Czech republic">
// Copyright (c) 1990-2021 All Right Reserved
// </copyright>
// <author>vl</author>
// <email></email>
// <date>2021-09-01</date>
// <summary>Part of Largo Composer</summary>
using JetBrains.Annotations;
namespace LargoSharedClasses.Music {
/// <summary>
/// Defines constants for the simple (multimedia) Timer's event types.
/// </summary>
public enum TimerMode {
/// <summary>
/// Timer event occurs once.
/// </summary>
[UsedImplicitly] OneShot,
/// <summary>
/// Timer event occurs periodically.
/// </summary>
Periodic
}
}
| 25.555556 | 74 | 0.608696 | [
"MIT"
] | Vladimir1965/LargoComposer | LargoSharedClasses/Music/TimerMode.cs | 690 | C# |
/* Copyright (c) 2014 Imazen See license.txt for your rights */
using System;
using System.Collections.Generic;
using System.Text;
using ImageResizer;
using System.IO;
using System.Drawing.Imaging;
using System.Collections.Specialized;
using System.Drawing;
using ImageResizer.Resizing;
using ImageResizer.Encoding;
using ImageResizer.Configuration;
using ImageResizer.Plugins.Basic;
namespace ImageResizer.Plugins.AnimatedGifs
{
/// <summary>
/// Adds support for resizing animated GIFs. Once added, animated GIFs will be resized while maintaining all animated frames. By default, .NET only saves the first frame of the GIF image.
/// </summary>
public class AnimatedGifs : BuilderExtension, IPlugin
{
Config c;
/// <summary>
/// Creates a new instance of the AnimatedGifs plugin.
/// </summary>
public AnimatedGifs(){}
/// <summary>
/// Adds the plugin to the given configuration container
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public IPlugin Install(Configuration.Config c) {
c.Plugins.add_plugin(this);
this.c = c;
return this;
}
/// <summary>
/// Removes the plugin from the given configuration container
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public bool Uninstall(Configuration.Config c) {
c.Plugins.remove_plugin(this);
return true;
}
/// <summary>
/// We cannot fix buildToBitmap, only buildToStream
/// </summary>
/// <param name="source"></param>
/// <param name="dest"></param>
/// <param name="job"></param>
protected override RequestedAction BuildJobBitmapToStream(ImageJob job, Bitmap source, Stream dest)
{
//Determines output format, includes code for saving in a variety of formats.
if (ImageFormat.Gif.Equals(source.RawFormat) && //If it's a GIF
job.Settings["frame"] == null && //With no frame specifier
source.FrameDimensionsList != null && source.FrameDimensionsList.Length > 0) { //With multiple frames
IEncoder enc = c.Plugins.EncoderProvider.GetEncoder(job.Settings, source);
if (enc.MimeType.Equals("image/gif", StringComparison.OrdinalIgnoreCase) && source.GetFrameCount(FrameDimension.Time) > 1) {
WriteAnimatedGif(source, dest, enc, job.Settings);
return RequestedAction.Cancel;
}
}
return RequestedAction.None;
}
private void WriteAnimatedGif(Bitmap src, Stream output, IEncoder ios, ResizeSettings queryString)
{
//http://www.fileformat.info/format/gif/egff.htm
//http://www.fileformat.info/format/gif/spec/44ed77668592476fb7a682c714a68bac/view.htm
//Heavily modified and patched from comments on http://bloggingabout.net/blogs/rick/archive/2005/05/10/3830.aspx
MemoryStream memoryStream = null;
BinaryWriter writer = null;
//Variable declaration
try
{
writer = new BinaryWriter(output);
memoryStream = new MemoryStream(4096);
//Write the GIF 89a sig
writer.Write(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'9', (byte)'a' });
//We parse this from the source image
int loops = GetLoops(src.PropertyItems);
int[] delays = GetDelays(src.PropertyItems);//20736 (delays) 20737 (loop);
int frames = src.GetFrameCount(FrameDimension.Time);
for (int frame = 0; frame < frames; frame++)
{
//Select the frame
src.SelectActiveFrame(FrameDimension.Time, frame);
// http://radio.weblogs.com/0122832/2005/10/20.html
//src.MakeTransparent(); This call makes some GIFs replicate the first image on all frames.. i.e. SelectActiveFrame doesn't work.
bool transparent = ios.SupportsTransparency;
using (Bitmap b = c.CurrentImageBuilder.Build(src,queryString,false)){
//Useful to check if animation is occurring - sometimes the problem isn't the output file, but the input frames are
//all the same.
//for (var i = 0; i < b.Height; i++) b.SetPixel(frame * 10, i, Color.Green);
// b.Save(memoryStream, ImageFormat.Gif);
if (ios is DefaultEncoder) {
//For both WIC Builder and DefaultBuilder
//We assume no transparency
transparent = false;
}
ios.Write(b, memoryStream); //Allows quantization and dithering
}
GifClass gif = new GifClass();
gif.LoadGifPicture(memoryStream);
if (frame == 0)
{
//Only one screen descriptor per file. Steal from the first image
writer.Write(gif.m_ScreenDescriptor.ToArray());
//How many times to loop the image (unless it is 1) IE and FF3 loop endlessly if loop=1
if (loops != 1)
writer.Write(GifCreator.CreateLoopBlock(loops));
}
//Restore frame delay
int delay = 0;
if (delays != null && delays.Length > frame) delay = delays[frame];
writer.Write(GifCreator.CreateGraphicControlExtensionBlock(delay, 0, transparent)); //The delay/transparent color block
writer.Write(gif.m_ImageDescriptor.ToArray()); //The image desc
writer.Write(gif.m_ColorTable.ToArray()); //The palette
writer.Write(gif.m_ImageData.ToArray()); //Image data
memoryStream.SetLength(0); //Clear the mem stream, but leave it allocated for now
memoryStream.Seek(0, SeekOrigin.Begin); //Reset memory buffer
}
writer.Write((byte)0x3B); //End file
}
finally
{
if (memoryStream != null) memoryStream.Dispose();
//if (writer != null) writer.Close
}
}
/// <summary>
/// Returns the first PropertyItem with a matching ID
/// </summary>
/// <param name="items"></param>
/// <param name="id"></param>
/// <returns></returns>
protected static PropertyItem getById(PropertyItem[] items, int id)
{
for (int i = 0; i < items.Length; i++)
if (items[i] != null && items[i].Id == id)
return items[i];
return null;
}
protected static int[] GetDelays(PropertyItem[] items)
{
//Property item ID 20736 http://bytes.com/groups/net-vb/692099-problem-animated-gifs
PropertyItem pi = getById(items, 20736);
if (pi == null) return null;
//Combine bytes into integers
int[] vals = new int[pi.Value.Length / 4];
for (int i = 0; i < pi.Value.Length; i+=4){
vals[i / 4] = BitConverter.ToInt32(pi.Value, i);
}
return vals;
}
protected static int GetLoops(PropertyItem[] items)
{
// http://weblogs.asp.net/justin_rogers/archive/2004/01/19/60424.aspx
//Property item ID 20737
PropertyItem pi = getById(items, 20737);
if (pi == null) return 0;
//Combine bytes into integers
return pi.Value[0] + (pi.Value[1] << 8);
}
}
}
| 44.091398 | 191 | 0.538715 | [
"MIT"
] | 2sic/resizer | Plugins/AnimatedGifs/AnimatedGifs.cs | 8,203 | C# |
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Github, 8087, "[WPF] View doesn't render when set IsClippedToBounds to true", PlatformAffected.WPF)]
public class Issue8087 : TestContentPage
{
protected override void Init()
{
var mainStackLayout = new StackLayout { Margin = new Thickness(100), IsClippedToBounds = true, BackgroundColor = Color.Red };
mainStackLayout.Children.Add(new Grid() { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, BackgroundColor = Color.Aqua, TranslationX = -50, TranslationY = -50 });
var button = new Button() { Text = "Toggle IsClippedToBounds" };
button.Clicked += (sender, e) => mainStackLayout.IsClippedToBounds = !mainStackLayout.IsClippedToBounds;
mainStackLayout.Children.Add(button);
this.Content = mainStackLayout;
}
}
} | 43.318182 | 213 | 0.759706 | [
"MIT"
] | 07101994/Xamarin.Forms | Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Issue8087.cs | 955 | C# |
using FtlSaveScummer.Properties;
using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace FtlSaveScummer
{
public partial class MainWindow : Form
{
readonly SoundPlayer loadSound = new SoundPlayer(Resources.bell);
readonly DirectoryInfo ourSaves = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FtlSaveScummer"));
FileInfo SaveLocation => new FileInfo(Path.Combine(Environment.ExpandEnvironmentVariables(pathBox.Text), "continue.sav"));
DateTime lastCopy = DateTime.MinValue;
bool active = false;
public MainWindow()
{
if (!ourSaves.Exists) ourSaves.Create();
InitializeComponent();
Text += $" v{Application.ProductVersion.Substring(0, Application.ProductVersion.IndexOf('.'))}";
void Add(string b) => iconSet.Images.Add(b, (Bitmap)Resources.ResourceManager.GetObject(b));
foreach (var t in tags) foreach (var s in t) Add(s);
}
FileInfo FileFromLabel(string label) => new FileInfo(Path.Combine(ourSaves.FullName, label.Replace(':', '_') + ".sav"));
static string LabelFromFile(FileInfo file) => Path.GetFileNameWithoutExtension(file.Name).Replace('_', ':');
static readonly Regex DefaultName = new Regex("^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d$");
static readonly Regex Tagged = new Regex("\\[(.+)\\]");
// Both of these only use the selected entry when the window is currently active. Otherwise (in
// headless/while-the-game-is-running mode), we should always just use the most recent entries.
ListViewItem SelectedOrFirstNonDefault => saveList.SelectedItems.Count == 1 && active ? saveList.SelectedItems[0] : (from ListViewItem i in saveList.Items where !DefaultName.IsMatch(i.Text) select i).FirstOrDefault();
ListViewItem SelectedOrTop => saveList.SelectedItems.Count == 1 && active ? saveList.SelectedItems[0] : (saveList.Items.Count == 0 ? null : saveList.Items[0]);
void PopulateList()
{
string selected = saveList.SelectedItems.Count == 1 ? saveList.SelectedItems[0].Text : null;
saveList.BeginUpdate();
saveList.Clear();
foreach (var save in ourSaves.EnumerateFiles("*.sav"))
{
var item = saveList.Items.Add(LabelFromFile(save));
var match = Tagged.Match(item.Text);
if (match.Success) item.ImageKey = match.Groups[1].Value;
}
if (!string.IsNullOrWhiteSpace(selected))
{
var item = saveList.FindItemWithText(selected);
if (item != null) item.Selected = true;
saveList.Select();
}
saveList.Sort();
saveList.EndUpdate();
}
void MainWindow_Load(object sender, EventArgs e)
{
PathBox_TextChanged(this, new EventArgs());
PopulateList();
}
void FileChanged(object sender, FileSystemEventArgs e) => Invoke(new Action(() => updateTimer.Start()));
void PathBox_TextChanged(object sender, EventArgs e)
{
var folder = SaveLocation.DirectoryName;
if (!Directory.Exists(folder)) return;
watcher.Path = folder;
}
void UpdateTimer_Tick(object sender, EventArgs e)
{
var path = SaveLocation;
if (path == null || !path.Exists) { updateTimer.Enabled = false; return; }
// Don't echo our own changes back
var sinceLastCopy = DateTime.UtcNow - lastCopy;
if (sinceLastCopy.TotalSeconds < 2) { updateTimer.Enabled = false; return; }
// Wait a little while for the file system to settle down
var sinceLastWrite = DateTime.UtcNow - path.LastWriteTimeUtc;
if (sinceLastWrite.TotalMilliseconds < 450) return;
updateTimer.Enabled = false;
path.CopyTo(FileFromLabel(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")).FullName, true);
PopulateList();
}
void SaveList_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
try
{
var before = FileFromLabel(saveList.Items[e.Item].Text);
if (!before.Exists) return;
var after = FileFromLabel(e.Label);
before.MoveTo(after.FullName);
string imageKey = null;
var match = Tagged.Match(e.Label);
if (match.Success) imageKey = match.Groups[1].Value;
saveList.Items[e.Item].ImageKey = imageKey;
}
catch { e.CancelEdit = true; }
}
void LoadState(string label)
{
if (label == null) return;
var file = FileFromLabel(label);
if (!file.Exists) return;
lastCopy = DateTime.UtcNow;
file.CopyTo(SaveLocation.FullName, true);
loadSound.Play();
}
void SaveList_ItemActivate(object sender, EventArgs e) => LoadState(saveList.SelectedItems.Count == 1 ? saveList.SelectedItems[0].Text : null);
void LoadClick(object sender, EventArgs e) => LoadState(SelectedOrFirstNonDefault?.Text ?? null);
void SaveList_KeyUp(object sender, KeyEventArgs e)
{
if (saveList.SelectedItems.Count != 1) return;
if (e.KeyCode == Keys.F2) { saveList.SelectedItems[0].BeginEdit(); return; }
if (e.KeyCode != Keys.Delete && e.KeyCode != Keys.Back) return;
var file = FileFromLabel(saveList.SelectedItems[0].Text);
FileSystem.DeleteFile(file.FullName, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
PopulateList();
}
private void CleanupClick(object sender, EventArgs e)
{
foreach (var save in ourSaves.EnumerateFiles("*.sav"))
if (DefaultName.IsMatch(LabelFromFile(save))) FileSystem.DeleteFile(save.FullName, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
PopulateList();
}
readonly List<string>[,] tags = {
{ new List<string>{ "laser1", "laser2" }, new List<string>{ "ion", "beam" }, new List<string>{ "missile", "bomb" }, new List<string>{ "drone1", "drone2" } },
{ new List<string>{ "scrap", "drones", "teleport", "cloak" }, new List<string>{ "clone", "mind", "hacking", "battery" }, new List<string>{ }, new List<string>{ } },
{ new List<string>{ }, new List<string>{ }, new List<string>{ }, new List<string>{ } }
};
void GlobalUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.F20:
case Keys.F21:
case Keys.F22:
case Keys.F23:
if (e.Shift && e.Control) break;
int c = e.KeyCode - Keys.F20;
int r = 0 + (e.Shift ? 1 : 0) + (e.Control ? 2 : 0);
var tagList = tags[r, c];
if (tagList.Count == 0) return;
SetTag(tagList);
break;
case Keys.F24:
if (e.Shift) CleanupClick(sender, e);
if (e.Control) LoadClick(sender, e);
break;
}
}
void SetTag(List<string> tagList)
{
var item = SelectedOrTop;
string tag = tagList[0];
string newLabel = $"{item.Text.Trim()} [{tag}]";
var match = Tagged.Match(item.Text);
if (match.Success)
{
var g = match.Groups[1];
tag = tagList[(tagList.IndexOf(g.Value) + 1) % tagList.Count];
newLabel = $"{item.Text.Substring(0, g.Index)}{tag}{item.Text.Substring(g.Index + g.Length)}";
}
var before = FileFromLabel(item.Text);
if (!before.Exists) return;
var after = FileFromLabel(newLabel);
before.MoveTo(after.FullName);
item.Text = newLabel;
item.ImageKey = tag;
}
void TagClick(object sender, EventArgs e)
{
var tag = (string)(sender as Button)?.Tag ?? null;
if (tag == null) return;
SetTag(new List<string>{ tag });
}
private void ClickOpenBackup(object sender, EventArgs e) => Process.Start(ourSaves.FullName);
// Keep track of when our whole process goes active/inactive
protected override void WndProc(ref Message m)
{
const int WM_ACTIVATEAPP = 0x1C;
if (m.Msg == WM_ACTIVATEAPP) active = m.WParam != IntPtr.Zero;
base.WndProc(ref m);
}
}
}
| 36.163866 | 223 | 0.60811 | [
"BSD-2-Clause"
] | npiegdon/ftl-save-scummer | MainWindow.cs | 8,609 | C# |
using System;
using System.Collections.Generic;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Querying;
namespace Umbraco.Core.Services
{
/// <summary>
/// Defines the MemberService, which is an easy access to operations involving (umbraco) members.
/// </summary>
public interface IMemberService : IMembershipMemberService
{
/// <summary>
/// Gets a list of paged <see cref="IMember"/> objects
/// </summary>
/// <remarks>An <see cref="IMember"/> can be of type <see cref="IMember"/> </remarks>
/// <param name="pageIndex">Current page index</param>
/// <param name="pageSize">Size of the page</param>
/// <param name="totalRecords">Total number of records found (out)</param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="memberTypeAlias"></param>
/// <param name="filter"></param>
/// <returns><see cref="IEnumerable{T}"/></returns>
IEnumerable<IMember> GetAll(int pageIndex, int pageSize, out int totalRecords,
string orderBy, Direction orderDirection, string memberTypeAlias = null, string filter = "");
/// <summary>
/// Creates an <see cref="IMember"/> object without persisting it
/// </summary>
/// <remarks>This method is convenient for when you need to add properties to a new Member
/// before persisting it in order to limit the amount of times its saved.
/// Also note that the returned <see cref="IMember"/> will not have an Id until its saved.</remarks>
/// <param name="username">Username of the Member to create</param>
/// <param name="email">Email of the Member to create</param>
/// <param name="name">Name of the Member to create</param>
/// <param name="memberTypeAlias">Alias of the MemberType the Member should be based on</param>
/// <returns><see cref="IMember"/></returns>
IMember CreateMember(string username, string email, string name, string memberTypeAlias);
/// <summary>
/// Creates an <see cref="IMember"/> object without persisting it
/// </summary>
/// <remarks>This method is convenient for when you need to add properties to a new Member
/// before persisting it in order to limit the amount of times its saved.
/// Also note that the returned <see cref="IMember"/> will not have an Id until its saved.</remarks>
/// <param name="username">Username of the Member to create</param>
/// <param name="email">Email of the Member to create</param>
/// <param name="name">Name of the Member to create</param>
/// <param name="memberType">MemberType the Member should be based on</param>
/// <returns><see cref="IMember"/></returns>
IMember CreateMember(string username, string email, string name, IMemberType memberType);
/// <summary>
/// Creates and persists a Member
/// </summary>
/// <remarks>Using this method will persist the Member object before its returned
/// meaning that it will have an Id available (unlike the CreateMember method)</remarks>
/// <param name="username">Username of the Member to create</param>
/// <param name="email">Email of the Member to create</param>
/// <param name="name">Name of the Member to create</param>
/// <param name="memberTypeAlias">Alias of the MemberType the Member should be based on</param>
/// <returns><see cref="IMember"/></returns>
IMember CreateMemberWithIdentity(string username, string email, string name, string memberTypeAlias);
/// <summary>
/// Creates and persists a Member
/// </summary>
/// <remarks>Using this method will persist the Member object before its returned
/// meaning that it will have an Id available (unlike the CreateMember method)</remarks>
/// <param name="username">Username of the Member to create</param>
/// <param name="email">Email of the Member to create</param>
/// <param name="name">Name of the Member to create</param>
/// <param name="memberType">MemberType the Member should be based on</param>
/// <returns><see cref="IMember"/></returns>
IMember CreateMemberWithIdentity(string username, string email, string name, IMemberType memberType);
/// <summary>
/// This is simply a helper method which essentially just wraps the MembershipProvider's ChangePassword method
/// </summary>
/// <remarks>This method exists so that Umbraco developers can use one entry point to create/update
/// Members if they choose to. </remarks>
/// <param name="member">The Member to save the password for</param>
/// <param name="password">The password to encrypt and save</param>
void SavePassword(IMember member, string password);
/// <summary>
/// Gets the count of Members by an optional MemberType alias
/// </summary>
/// <remarks>If no alias is supplied then the count for all Member will be returned</remarks>
/// <param name="memberTypeAlias">Optional alias for the MemberType when counting number of Members</param>
/// <returns><see cref="System.int"/> with number of Members</returns>
int Count(string memberTypeAlias = null);
/// <summary>
/// Checks if a Member with the id exists
/// </summary>
/// <param name="id">Id of the Member</param>
/// <returns><c>True</c> if the Member exists otherwise <c>False</c></returns>
bool Exists(int id);
/// <summary>
/// Gets a Member by the unique key
/// </summary>
/// <remarks>The guid key corresponds to the unique id in the database
/// and the user id in the membership provider.</remarks>
/// <param name="id"><see cref="Guid"/> Id</param>
/// <returns><see cref="IMember"/></returns>
IMember GetByKey(Guid id);
/// <summary>
/// Gets a Member by its integer id
/// </summary>
/// <param name="id"><see cref="System.int"/> Id</param>
/// <returns><see cref="IMember"/></returns>
IMember GetById(int id);
/// <summary>
/// Gets all Members for the specified MemberType alias
/// </summary>
/// <param name="memberTypeAlias">Alias of the MemberType</param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetMembersByMemberType(string memberTypeAlias);
/// <summary>
/// Gets all Members for the MemberType id
/// </summary>
/// <param name="memberTypeId">Id of the MemberType</param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetMembersByMemberType(int memberTypeId);
/// <summary>
/// Gets all Members within the specified MemberGroup name
/// </summary>
/// <param name="memberGroupName">Name of the MemberGroup</param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetMembersByGroup(string memberGroupName);
/// <summary>
/// Gets all Members with the ids specified
/// </summary>
/// <remarks>If no Ids are specified all Members will be retrieved</remarks>
/// <param name="ids">Optional list of Member Ids</param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetAllMembers(params int[] ids);
/// <summary>
/// Delete Members of the specified MemberType id
/// </summary>
/// <param name="memberTypeId">Id of the MemberType</param>
void DeleteMembersOfType(int memberTypeId);
/// <summary>
/// Finds Members based on their display name
/// </summary>
/// <param name="displayNameToMatch">Display name to match</param>
/// <param name="pageIndex">Current page index</param>
/// <param name="pageSize">Size of the page</param>
/// <param name="totalRecords">Total number of records found (out)</param>
/// <param name="matchType">The type of match to make as <see cref="StringPropertyMatchType"/>. Default is <see cref="StringPropertyMatchType.StartsWith"/></param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> FindMembersByDisplayName(string displayNameToMatch, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith);
/// <summary>
/// Gets a list of Members based on a property search
/// </summary>
/// <param name="propertyTypeAlias">Alias of the PropertyType to search for</param>
/// <param name="value"><see cref="System.string"/> Value to match</param>
/// <param name="matchType">The type of match to make as <see cref="StringPropertyMatchType"/>. Default is <see cref="StringPropertyMatchType.Exact"/></param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, string value, StringPropertyMatchType matchType = StringPropertyMatchType.Exact);
/// <summary>
/// Gets a list of Members based on a property search
/// </summary>
/// <param name="propertyTypeAlias">Alias of the PropertyType to search for</param>
/// <param name="value"><see cref="System.int"/> Value to match</param>
/// <param name="matchType">The type of match to make as <see cref="StringPropertyMatchType"/>. Default is <see cref="StringPropertyMatchType.Exact"/></param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, int value, ValuePropertyMatchType matchType = ValuePropertyMatchType.Exact);
/// <summary>
/// Gets a list of Members based on a property search
/// </summary>
/// <param name="propertyTypeAlias">Alias of the PropertyType to search for</param>
/// <param name="value"><see cref="System.bool"/> Value to match</param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, bool value);
/// <summary>
/// Gets a list of Members based on a property search
/// </summary>
/// <param name="propertyTypeAlias">Alias of the PropertyType to search for</param>
/// <param name="value"><see cref="System.DateTime"/> Value to match</param>
/// <param name="matchType">The type of match to make as <see cref="StringPropertyMatchType"/>. Default is <see cref="StringPropertyMatchType.Exact"/></param>
/// <returns><see cref="IEnumerable{IMember}"/></returns>
IEnumerable<IMember> GetMembersByPropertyValue(string propertyTypeAlias, DateTime value, ValuePropertyMatchType matchType = ValuePropertyMatchType.Exact);
}
} | 57.298507 | 205 | 0.630199 | [
"MIT"
] | filipw/Umbraco-CMS | src/Umbraco.Core/Services/IMemberService.cs | 11,519 | C# |
using EasyAbp.WeChatManagement.MiniPrograms;
using WeChatManagementSample.Localization;
using Volo.Abp.AuditLogging;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.FeatureManagement;
using Volo.Abp.Identity;
using Volo.Abp.IdentityServer;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.PermissionManagement;
using Volo.Abp.SettingManagement;
using Volo.Abp.TenantManagement;
using Volo.Abp.Validation.Localization;
using Volo.Abp.VirtualFileSystem;
namespace WeChatManagementSample
{
[DependsOn(
typeof(AbpAuditLoggingDomainSharedModule),
typeof(AbpBackgroundJobsDomainSharedModule),
typeof(AbpFeatureManagementDomainSharedModule),
typeof(AbpIdentityDomainSharedModule),
typeof(AbpIdentityServerDomainSharedModule),
typeof(AbpPermissionManagementDomainSharedModule),
typeof(AbpSettingManagementDomainSharedModule),
typeof(AbpTenantManagementDomainSharedModule),
typeof(WeChatManagementMiniProgramsDomainSharedModule)
)]
public class WeChatManagementSampleDomainSharedModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
options.FileSets.AddEmbedded<WeChatManagementSampleDomainSharedModule>();
});
Configure<AbpLocalizationOptions>(options =>
{
options.Resources
.Add<WeChatManagementSampleResource>("en")
.AddBaseTypes(typeof(AbpValidationResource))
.AddVirtualJson("/Localization/WeChatManagementSample");
options.DefaultResourceType = typeof(WeChatManagementSampleResource);
});
}
}
}
| 36.5 | 89 | 0.714521 | [
"MIT"
] | EasyAbp/WeChatManagement | samples/WeChatManagementSample/aspnet-core/src/WeChatManagementSample.Domain.Shared/WeChatManagementSampleDomainSharedModule.cs | 1,827 | C# |
namespace Naspinski.FoodTruck.Admin.Models
{
public class IndexHeaderModel
{
public string Controller;
public string Text;
public IndexHeaderModel(string controller, string text) => (Controller, Text) = (controller, text);
}
}
| 24.090909 | 107 | 0.675472 | [
"MIT"
] | naspinski/FoodTruck.Admin | Naspinski.FoodTruck.Admin/Models/IndexHeaderModel.cs | 267 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PearlCalculatorBlazor.Managers
{
public class EventManager
{
private static EventManager _instance;
public static EventManager Instance => _instance ??= new EventManager();
interface IEventHandlerWrapper
{
public void Invoke(object sender, EventArgs e);
}
class EventHanderWrapper<T> : IEventHandlerWrapper where T : EventArgs
{
public event CEventHandler<T> Handler;
public void Invoke(object sender, EventArgs e) => Handler?.Invoke(sender, (T)e);
}
Dictionary<string, Dictionary<Type, IEventHandlerWrapper>> _eventCon;
private EventManager()
{
_eventCon = new();
}
public void AddListener<T>(string eventKey, CEventHandler<T> eventHandler) where T : EventArgs
{
if (string.IsNullOrEmpty(eventKey) || string.IsNullOrWhiteSpace(eventKey))
throw new ArgumentNullException(nameof(eventKey));
if (eventHandler is null)
throw new ArgumentNullException(nameof(eventHandler));
if (!_eventCon.TryGetValue(eventKey, out var handlerDict))
{
handlerDict = new();
_eventCon.Add(eventKey, handlerDict);
}
EventHanderWrapper<T> wrapper;
if (!handlerDict.TryGetValue(typeof(T), out var w))
handlerDict.Add(typeof(T), wrapper = new());
else
wrapper = (EventHanderWrapper<T>)w;
wrapper.Handler += eventHandler;
}
public void RemoveListener<T>(string eventKey, CEventHandler<T> eventHandler) where T : EventArgs
{
if (string.IsNullOrEmpty(eventKey) || string.IsNullOrWhiteSpace(eventKey))
throw new ArgumentNullException(nameof(eventKey));
if (eventHandler is null)
throw new ArgumentNullException(nameof(eventHandler));
if (!_eventCon.TryGetValue(eventKey, out var handlerDict)) return;
if (handlerDict.TryGetValue(typeof(T), out var w))
{
var wrapper = (EventHanderWrapper<T>)w;
wrapper.Handler -= eventHandler;
}
}
public void PublishEvent<T>(object sender, string eventKey, T args) where T : EventArgs
{
if (string.IsNullOrEmpty(eventKey) || string.IsNullOrWhiteSpace(eventKey))
throw new ArgumentNullException(nameof(eventKey));
if (args is null)
throw new ArgumentNullException(nameof(args));
if (_eventCon.TryGetValue(eventKey, out var dict) &&
dict.TryGetValue(typeof(T), out var wrapper))
{
wrapper?.Invoke(sender, args);
}
}
}
public delegate void CEventHandler<in T>(object sender, T e);
}
| 33.354839 | 106 | 0.579626 | [
"MIT"
] | memorydream/PearlCalculatorBlazor | Managers/EventManager.cs | 3,104 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PhotosOfUs.Model.Repositories;
using PhotosOfUs.Model.ViewModels;
using PhotosOfUs.Model.Models;
namespace PhotosOfUs.Web.Controllers.API
{
[Route("api/Print")]
public class PrintApiController : Controller
{
//pwinty sandbox
//https://sandbox.pwinty.com/v2.6
//[HttpPost]
//[Route("OrderPhotos")]
//public OrderViewModel CreateOrder(Order order)
//{
// string url = "https://sandbox.pwinty.com/v2.5";
// var newOrder = new OrderViewModel();
// return newOrder;
//}
}
}
| 24.096774 | 61 | 0.65328 | [
"MIT"
] | sparc-coop/photos-of-us | PhotosOfUs.Web/Controllers/API/PrintApiController.cs | 749 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace YourAmongusSpecialSpy.Mission
{
public class AcceptDivertedPowerMission : IMission
{
public string GetName()
{
return "전환된 에너지 받기";
}
public bool IsMyMission(Bitmap image)
{
var mapping = new List<(Point Point, List<Color> Color)>
{
(new Point(360, 405), new List<Color> { Color.FromArgb(221, 180, 64) }),
(new Point(368, 394), new List<Color> { Color.FromArgb(209, 201, 180) }),
(new Point(370, 445), new List<Color> { Color.FromArgb(153, 121, 26) }),
(new Point(371, 409), new List<Color> { Color.FromArgb(151, 118, 17) }),
(new Point(376, 436), new List<Color> { Color.FromArgb(129, 92, 1) }),
(new Point(378, 395), new List<Color> { Color.FromArgb(175, 148, 59) }),
(new Point(379, 424), new List<Color> { Color.FromArgb(185, 142, 12) }),
(new Point(387, 378), new List<Color> { Color.FromArgb(161, 158, 147) }),
(new Point(387, 424), new List<Color> { Color.FromArgb(148, 107, 0) }),
(new Point(657, 561), new List<Color> { Color.FromArgb(105, 105, 105) }),
(new Point(704, 395), new List<Color> { Color.FromArgb(105, 105, 105) }),
(new Point(765, 521), new List<Color> { Color.FromArgb(234, 234, 234) }),
(new Point(774, 287), new List<Color> { Color.FromArgb(105, 105, 105) }),
(new Point(791, 441), new List<Color> { Color.FromArgb(224, 224, 224) }),
(new Point(805, 359), new List<Color> { Color.FromArgb(255, 255, 255) }),
(new Point(884, 351), new List<Color> { Color.FromArgb(168, 168, 168) }),
(new Point(917, 548), new List<Color> { Color.FromArgb(105, 105, 105) }),
(new Point(921, 329), new List<Color> { Color.FromArgb(105, 105, 105) }),
(new Point(968, 288), new List<Color> { Color.FromArgb(105, 105, 105) }),
(new Point(1010, 470), new List<Color> { Color.FromArgb(105, 105, 105) }),
(new Point(1013, 344), new List<Color> { Color.FromArgb(105, 105, 105) }),
};
return mapping.All(x => x.Color.Contains(image.GetPixel(x.Point.X, x.Point.Y)));
}
public void StartMission(Bitmap image)
{
Thread.Sleep(100);
MouseController.Click(688, 415, 50);
}
}
}
| 48.163636 | 92 | 0.548886 | [
"MIT"
] | jkwchunjae/YourAmongusSpecialSpy | YourAmongusSpecialSpy/Mission/AcceptDivertedPowerMission.cs | 2,667 | 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 apigateway-2015-07-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.APIGateway.Model
{
/// <summary>
/// Represents a usage plan than can specify who can assess associated API stages with
/// specified request limits and quotas.
///
/// <div class="remarks">
/// <para>
/// In a usage plan, you associate an API by specifying the API's Id and a stage name
/// of the specified API. You add plan customers by adding API keys to the plan.
/// </para>
/// </div> <div class="seeAlso"> <a href="http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html">Create
/// and Use Usage Plans</a> </div>
/// </summary>
public partial class UpdateUsagePlanResponse : AmazonWebServiceResponse
{
private List<ApiStage> _apiStages = new List<ApiStage>();
private string _description;
private string _id;
private string _name;
private string _productCode;
private QuotaSettings _quota;
private ThrottleSettings _throttle;
/// <summary>
/// Gets and sets the property ApiStages.
/// <para>
/// The associated API stages of a usage plan.
/// </para>
/// </summary>
public List<ApiStage> ApiStages
{
get { return this._apiStages; }
set { this._apiStages = value; }
}
// Check to see if ApiStages property is set
internal bool IsSetApiStages()
{
return this._apiStages != null && this._apiStages.Count > 0;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of a usage plan.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// The identifier of a <a>UsagePlan</a> resource.
/// </para>
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of a usage plan.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property ProductCode.
/// <para>
/// The AWS Markeplace product identifier to associate with the usage plan as a SaaS product
/// on AWS Marketplace.
/// </para>
/// </summary>
public string ProductCode
{
get { return this._productCode; }
set { this._productCode = value; }
}
// Check to see if ProductCode property is set
internal bool IsSetProductCode()
{
return this._productCode != null;
}
/// <summary>
/// Gets and sets the property Quota.
/// <para>
/// The maximum number of permitted requests per a given unit time interval.
/// </para>
/// </summary>
public QuotaSettings Quota
{
get { return this._quota; }
set { this._quota = value; }
}
// Check to see if Quota property is set
internal bool IsSetQuota()
{
return this._quota != null;
}
/// <summary>
/// Gets and sets the property Throttle.
/// <para>
/// The request throttle limits of a usage plan.
/// </para>
/// </summary>
public ThrottleSettings Throttle
{
get { return this._throttle; }
set { this._throttle = value; }
}
// Check to see if Throttle property is set
internal bool IsSetThrottle()
{
return this._throttle != null;
}
}
} | 29.8 | 147 | 0.557979 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/APIGateway/Generated/Model/UpdateUsagePlanResponse.cs | 5,364 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Foundation;
using ObjCRuntime;
using UIKit;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
using RectangleF = CoreGraphics.CGRect;
namespace Xamarin.Forms.Platform.iOS
{
internal class ReadOnlyField : NoCaretField
{
readonly HashSet<string> enableActions;
public ReadOnlyField() {
string[] actions = { "copy:", "select:", "selectAll:" };
enableActions = new HashSet<string> (actions);
}
public override bool CanPerform (Selector action, NSObject withSender)
=> enableActions.Contains(action.Name);
}
public class PickerRenderer : PickerRendererBase<UITextField>
{
protected override UITextField CreateNativeControl()
{
return new ReadOnlyField { BorderStyle = UITextBorderStyle.RoundedRect };
}
}
public abstract class PickerRendererBase<TControl> : ViewRenderer<Picker, TControl>
where TControl : UITextField
{
UIPickerView _picker;
UIColor _defaultTextColor;
bool _disposed;
bool _useLegacyColorManagement;
IElementController ElementController => Element as IElementController;
protected abstract override TControl CreateNativeControl();
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
if (e.OldElement != null)
((INotifyCollectionChanged)e.OldElement.Items).CollectionChanged -= RowsCollectionChanged;
if (e.NewElement != null)
{
if (Control == null)
{
// disabled cut, delete, and toggle actions because they can throw an unhandled native exception
var entry = CreateNativeControl();
entry.EditingDidBegin += OnStarted;
entry.EditingDidEnd += OnEnded;
entry.EditingChanged += OnEditing;
_picker = new UIPickerView();
var width = UIScreen.MainScreen.Bounds.Width;
var toolbar = new UIToolbar(new RectangleF(0, 0, width, 44)) { BarStyle = UIBarStyle.Default, Translucent = true };
var spacer = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);
var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (o, a) =>
{
var s = (PickerSource)_picker.Model;
if (s.SelectedIndex == -1 && Element.Items != null && Element.Items.Count > 0)
UpdatePickerSelectedIndex(0);
UpdatePickerFromModel(s);
entry.ResignFirstResponder();
});
toolbar.SetItems(new[] { spacer, doneButton }, false);
entry.InputView = _picker;
entry.InputAccessoryView = toolbar;
entry.InputView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight;
entry.InputAccessoryView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight;
entry.InputAssistantItem.LeadingBarButtonGroups = null;
entry.InputAssistantItem.TrailingBarButtonGroups = null;
_defaultTextColor = entry.TextColor;
_useLegacyColorManagement = e.NewElement.UseLegacyColorManagement();
SetNativeControl(entry);
}
_picker.Model = new PickerSource(this);
UpdateFont();
UpdatePicker();
UpdateTextColor();
((INotifyCollectionChanged)e.NewElement.Items).CollectionChanged += RowsCollectionChanged;
}
base.OnElementChanged(e);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Picker.TitleProperty.PropertyName || e.PropertyName == Picker.TitleColorProperty.PropertyName)
UpdatePicker();
else if (e.PropertyName == Picker.SelectedIndexProperty.PropertyName)
UpdatePicker();
else if (e.PropertyName == Picker.TextColorProperty.PropertyName || e.PropertyName == VisualElement.IsEnabledProperty.PropertyName)
UpdateTextColor();
else if (e.PropertyName == Picker.FontAttributesProperty.PropertyName || e.PropertyName == Picker.FontFamilyProperty.PropertyName || e.PropertyName == Picker.FontSizeProperty.PropertyName)
UpdateFont();
}
void OnEditing(object sender, EventArgs eventArgs)
{
// Reset the TextField's Text so it appears as if typing with a keyboard does not work.
var selectedIndex = Element.SelectedIndex;
var items = Element.Items;
Control.Text = selectedIndex == -1 || items == null ? "" : items[selectedIndex];
// Also clears the undo stack (undo/redo possible on iPads)
Control.UndoManager.RemoveAllActions();
}
void OnEnded(object sender, EventArgs eventArgs)
{
var s = (PickerSource)_picker.Model;
if (s.SelectedIndex != -1 && s.SelectedIndex != _picker.SelectedRowInComponent(0))
{
_picker.Select(s.SelectedIndex, 0, false);
}
ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
}
void OnStarted(object sender, EventArgs eventArgs)
{
ElementController.SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true);
}
void RowsCollectionChanged(object sender, EventArgs e)
{
UpdatePicker();
}
protected internal virtual void UpdateFont()
{
Control.Font = Element.ToUIFont();
}
readonly Color _defaultPlaceholderColor = ColorExtensions.SeventyPercentGrey.ToColor();
protected internal virtual void UpdatePlaceholder()
{
var formatted = (FormattedString)Element.Title;
if (formatted == null)
return;
var targetColor = Element.TitleColor;
if (_useLegacyColorManagement)
{
var color = targetColor.IsDefault || !Element.IsEnabled ? _defaultPlaceholderColor : targetColor;
Control.AttributedPlaceholder = formatted.ToAttributed(Element, color);
}
else
{
// Using VSM color management; take whatever is in Element.PlaceholderColor
var color = targetColor.IsDefault ? _defaultPlaceholderColor : targetColor;
Control.AttributedPlaceholder = formatted.ToAttributed(Element, color);
}
}
void UpdatePicker()
{
var selectedIndex = Element.SelectedIndex;
var items = Element.Items;
UpdatePlaceholder();
var oldText = Control.Text;
Control.Text = selectedIndex == -1 || items == null || selectedIndex >= items.Count ? "" : items[selectedIndex];
UpdatePickerNativeSize(oldText);
_picker.ReloadAllComponents();
if (items == null || items.Count == 0)
return;
UpdatePickerSelectedIndex(selectedIndex);
}
void UpdatePickerFromModel(PickerSource s)
{
if (Element != null)
{
var oldText = Control.Text;
Control.Text = s.SelectedItem;
UpdatePickerNativeSize(oldText);
ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, s.SelectedIndex);
}
}
void UpdatePickerNativeSize(string oldText)
{
if (oldText != Control.Text)
((IVisualElementController)Element).NativeSizeChanged();
}
void UpdatePickerSelectedIndex(int formsIndex)
{
var source = (PickerSource)_picker.Model;
source.SelectedIndex = formsIndex;
source.SelectedItem = formsIndex >= 0 ? Element.Items[formsIndex] : null;
_picker.Select(Math.Max(formsIndex, 0), 0, true);
}
protected internal virtual void UpdateTextColor()
{
var textColor = Element.TextColor;
if (textColor.IsDefault || (!Element.IsEnabled && _useLegacyColorManagement))
Control.TextColor = _defaultTextColor;
else
Control.TextColor = textColor.ToUIColor();
// HACK This forces the color to update; there's probably a more elegant way to make this happen
Control.Text = Control.Text;
}
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
_disposed = true;
if (disposing)
{
_defaultTextColor = null;
if (_picker != null)
{
if (_picker.Model != null)
{
_picker.Model.Dispose();
_picker.Model = null;
}
_picker.RemoveFromSuperview();
_picker.Dispose();
_picker = null;
}
if (Control != null)
{
Control.EditingDidBegin -= OnStarted;
Control.EditingDidEnd -= OnEnded;
Control.EditingChanged -= OnEditing;
}
if(Element != null)
((INotifyCollectionChanged)Element.Items).CollectionChanged -= RowsCollectionChanged;
}
base.Dispose(disposing);
}
class PickerSource : UIPickerViewModel
{
PickerRendererBase<TControl> _renderer;
bool _disposed;
public PickerSource(PickerRendererBase<TControl> renderer)
{
_renderer = renderer;
}
public int SelectedIndex { get; internal set; }
public string SelectedItem { get; internal set; }
public override nint GetComponentCount(UIPickerView picker)
{
return 1;
}
public override nint GetRowsInComponent(UIPickerView pickerView, nint component)
{
return _renderer.Element.Items != null ? _renderer.Element.Items.Count : 0;
}
public override string GetTitle(UIPickerView picker, nint row, nint component)
{
return _renderer.Element.Items[(int)row];
}
public override void Selected(UIPickerView picker, nint row, nint component)
{
if (_renderer.Element.Items.Count == 0)
{
SelectedItem = null;
SelectedIndex = -1;
}
else
{
SelectedItem = _renderer.Element.Items[(int)row];
SelectedIndex = (int)row;
}
if(_renderer.Element.On<PlatformConfiguration.iOS>().UpdateMode() == UpdateMode.Immediately)
_renderer.UpdatePickerFromModel(this);
}
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
_disposed = true;
if (disposing)
_renderer = null;
base.Dispose(disposing);
}
}
}
} | 28.429003 | 191 | 0.716472 | [
"MIT"
] | Arobono/Xamarin.Forms | Xamarin.Forms.Platform.iOS/Renderers/PickerRenderer.cs | 9,410 | C# |
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Logi3plJMS.API
{
public class QuartzHostedService : IHostedService
{
private readonly ISchedulerFactory _schedulerFactory;
private readonly IJobFactory _jobFactory;
public QuartzHostedService(
ISchedulerFactory schedulerFactory,
IJobFactory jobFactory)
{
_schedulerFactory = schedulerFactory;
_jobFactory = jobFactory;
}
public IScheduler Scheduler { get; set; }
public async Task StartAsync(CancellationToken cancellationToken)
{
Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
Scheduler.JobFactory = _jobFactory;
await Scheduler.Start(cancellationToken);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
await Scheduler?.Shutdown(cancellationToken);
}
}
}
| 27.04878 | 80 | 0.679892 | [
"MIT"
] | Logi3PL/Quartzmin | Source/Services/SelfHosting.API/QuartzHostedService.cs | 1,111 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TD5
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
| 26.75 | 143 | 0.594626 | [
"MIT"
] | Misaux/eiin839 | TD5/TD5/TD5/Service1.cs | 858 | C# |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
namespace Wintellog2.DataModel
{
[DataContract]
public class BlogItem : BaseItem
{
private static Random _random = new Random();
private static Random RandomNumber
{
get
{
_random = _random ?? new Random();
return _random;
}
}
public BlogItem()
{
Initialize();
}
[OnDeserialized]
public void Init(StreamingContext c)
{
Initialize();
}
private void Initialize()
{
if (ImageUriList == null)
{
ImageUriList = new ObservableCollection<Uri>();
}
// ReSharper disable ExplicitCallerInfoArgument
ImageUriList.CollectionChanged += (o, e) => OnPropertyChanged("DefaultImageUri");
// ReSharper restore ExplicitCallerInfoArgument
}
public BlogGroup Group { get; set; }
[DataMember]
public string Description { get; set; }
private ObservableCollection<Uri> _imageUriList;
[DataMember]
public ObservableCollection<Uri> ImageUriList
{
get
{
return _imageUriList;
}
set
{
_imageUriList = value;
if (_imageUriList != null)
{
_imageUriList.CollectionChanged += (o, e) =>
{
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged("DefaultImageUri");
OnPropertyChanged("FilteredList");
// ReSharper restore ExplicitCallerInfoArgument
};
}
OnPropertyChanged();
}
}
public ObservableCollection<Uri> FilteredList
{
get
{
var filteredList = ImageUriManager.FilteredImageSet(Id, ImageUriList).ToArray();
return new ObservableCollection<Uri>(filteredList.Length > 0 ?
filteredList : ImageUriList.ToArray());
}
}
public Uri DefaultImageUri
{
get
{
var filteredList = ImageUriManager.FilteredImageSet(Id, ImageUriList).ToArray();
if (filteredList == null || filteredList.Length < 1)
{
return new Uri("http://www.wintellect.com/images/WintellectLogo.png", UriKind.Absolute);
}
var x = RandomNumber.Next(1, filteredList.Length) - 1;
return filteredList[x];
}
}
[DataMember]
public DateTime PostDate { get; set; }
}
}
| 27.813084 | 109 | 0.494288 | [
"MIT"
] | JeremyLikness/BuildWin8Apps | Chapter7/Wintellog2/Wintellog2/DataModel/BlogItem.cs | 2,978 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ex7_Problem_7.Cake_Ingredients
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 0; i <= 20; i++)
{
string ingredients = Console.ReadLine();
sum++;
if (ingredients == "Bake!")
{
Console.WriteLine("Preparing cake with {0} ingredients.",sum-1);
return;
}
else
{
Console.WriteLine("Adding ingredient {0}.",ingredients);
}
}
}
}
}
| 16.5 | 69 | 0.611408 | [
"MIT"
] | MichelleMihova/SoftUni | C# Conditionals Statements and Loops - Exercises/Problem 7. Cake Ingredients/Program.cs | 563 | C# |
/*!
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT https://github.com/electricessence/Genetic-Algorithm-Platform/blob/master/LICENSE.md
*/
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
namespace Open.RandomizationExtensions;
public static class Randomizer
{
static readonly Lazy<Random> R = new(() => new Random());
/// <summary>
/// The Random object used by the extensions.
/// </summary>
public static Random Random => R.Value;
/// <summary>
/// Attempts to select a LinkedListNode at random and remove it.
/// </summary>
/// <typeparam name="T">The generic type of the linked list.</typeparam>
/// <param name="source">The source linked list.</param>
/// <param name="value">The value retrieved.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <returns>True if successfully retrieved and item and removed the node.</returns>
public static bool TryRandomPluck<T>(this LinkedList<T> source, out T value, Random? random = null)
{
if (source.Count == 0)
{
value = default!;
return false;
}
var r = (random ?? R.Value).Next(source.Count);
var node = source.First;
for (var i = 0; i <= r; i++)
node = node.Next;
value = node.Value;
source.Remove(node);
return true;
}
/// <summary>
/// Selects a LinkedListNode at random, removes it, and returns its value.
/// </summary>
/// <typeparam name="T">The generic type of the linked list.</typeparam>
/// <param name="source">The source linked list.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <returns>The value retrieved.</returns>
public static T RandomPluck<T>(this LinkedList<T> source, Random? random = null)
=> source.TryRandomPluck(out var value, random) ? value
: throw new InvalidOperationException("Source collection is empty.");
/// <summary>
/// Attempts to select an index at random and remove it.
/// </summary>
/// <typeparam name="T">The generic type of the list.</typeparam>
/// <param name="source">The source list.</param>
/// <param name="value">The value removed.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <returns>True if successfully removed.</returns>
public static bool TryRandomPluck<T>(this List<T> source, out T value, Random? random = null)
{
if (source.Count == 0)
{
value = default!;
return false;
}
var r = (random ?? R.Value).Next(source.Count);
value = source[r];
source.RemoveAt(r);
return true;
}
/// <summary>
/// Selects an index at random, removes it, and returns its value.
/// </summary>
/// <typeparam name="T">The generic type of the list.</typeparam>
/// <param name="source">The source list.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <returns>The value retrieved.</returns>
public static T RandomPluck<T>(this List<T> source, Random? random = null)
=> source.TryRandomPluck(out var value, random) ? value
: throw new InvalidOperationException("Source collection is empty.");
/// <summary>
/// Randomly selects a reference from the source.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <returns>The reference selected.</returns>
public static ref readonly T RandomSelectOne<T>(
this in ReadOnlySpan<T> source, Random? random = null)
{
if (source.Length == 0)
throw new InvalidOperationException("Source collection is empty.");
return ref source[(random ?? R.Value).Next(source.Length)];
}
/// <summary>
/// Randomly selects a reference from the source.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <returns>The reference selected.</returns>
public static ref T RandomSelectOne<T>(
this in Span<T> source, Random? random = null)
{
if (source.Length == 0)
throw new InvalidOperationException("Source collection is empty.");
return ref source[(random ?? R.Value).Next(source.Length)];
}
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">The optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndex<T>(this in ReadOnlySpan<T> source, Random? random = null, IEnumerable<T>? exclusion = null)
{
if (source.Length == 0)
return -1;
DeferredHashSet<T>? setCreated = null;
try
{
var exclusionSet = exclusion == null || exclusion is ICollection<T> c && c.Count == 0 ? default
: exclusion as ISet<T> ?? (setCreated = new DeferredHashSet<T>(exclusion));
if (exclusionSet == null || exclusionSet.Count == 0)
return (random ?? R.Value).Next(source.Length);
if (exclusionSet.Count == 1)
return RandomSelectIndexExcept(in source, random, exclusionSet.Single());
var count = source.Length;
var pool = ArrayPool<int>.Shared;
var indexes = pool.Rent(count);
try
{
var indexCount = 0;
for (var i = 0; i < count; ++i)
{
if (!exclusionSet.Contains(source[i]))
indexes[indexCount++] = i;
}
return indexCount == 0 ? -1
: indexes[(random ?? R.Value).Next(indexCount)];
}
finally
{
pool.Return(indexes);
}
}
finally
{
setCreated?.Dispose();
}
}
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="exclusion">The values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndex<T>(this in ReadOnlySpan<T> source, IEnumerable<T> exclusion)
=> RandomSelectIndex(in source, default, exclusion);
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndexExcept<T>(this in ReadOnlySpan<T> source, Random? random, T excluding, params T[] others)
{
if (source.Length == 0)
return -1;
if (others.Length != 0)
return RandomSelectIndex(in source, random, others.Prepend(excluding));
var pool = ArrayPool<int>.Shared;
var indexes = pool.Rent(others.Length);
try
{
var i = -1;
var indexCount = 0;
foreach (var value in source)
{
++i;
bool equals = excluding is null ? value is null : excluding.Equals(value);
if (!equals)
indexes[indexCount++] = i;
}
return indexCount == 0 ? -1 : indexes[R.Value.Next(indexCount)];
}
finally
{
pool.Return(indexes);
}
}
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="exclusion">A value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndexExcept<T>(this in ReadOnlySpan<T> source, T excluding, params T[] others)
=> RandomSelectIndexExcept(in source, default, excluding, others);
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">The optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndex<T>(this in Span<T> source, Random? random = null, IEnumerable<T>? exclusion = null)
=> RandomSelectIndex((ReadOnlySpan<T>)source, random, exclusion);
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="exclusion">The values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndex<T>(this in Span<T> source, IEnumerable<T> exclusion)
=> RandomSelectIndex((ReadOnlySpan<T>)source, default, exclusion);
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="excluding">A value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndexExcept<T>(this in Span<T> source, Random random, T excluding, params T[] others)
=> RandomSelectIndexExcept((ReadOnlySpan<T>)source, random, excluding, others);
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="excluding">A value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndexExcept<T>(this in Span<T> source, T excluding, params T[] others)
=> RandomSelectIndexExcept((ReadOnlySpan<T>)source, default, excluding, others);
static int RandomSelectIndex<T>(Random? random, int count, IEnumerable<T> source, IEnumerable<T>? exclusion)
{
if (count == 0)
return -1;
DeferredHashSet<T>? setCreated = null;
try
{
var exclusionSet = exclusion == null ? default
: exclusion as ISet<T> ?? (setCreated = new DeferredHashSet<T>(exclusion));
if (exclusionSet == null || exclusionSet.Count == 0)
return (random ?? R.Value).Next(count);
if (exclusionSet.Count == 1)
return RandomSelectIndexExcept(random, count, source, exclusionSet.Single());
var pool = ArrayPool<int>.Shared;
var indexes = pool.Rent(count);
try
{
var i = -1;
var indexCount = 0;
foreach (var value in source)
{
++i;
if (!exclusionSet.Contains(value))
indexes[indexCount++] = i;
}
return indexCount == 0 ? -1 : indexes[(random ?? R.Value).Next(indexCount)];
}
finally
{
pool.Return(indexes);
}
}
finally
{
setCreated?.Dispose();
}
}
static int RandomSelectIndexExcept<T>(Random? random, int count, IEnumerable<T> source, T excluding, params T[] others)
{
if (count == 0)
return -1;
if (others.Length != 0)
return RandomSelectIndex(random, count, source, others.Prepend(excluding));
var pool = ArrayPool<int>.Shared;
var indexes = pool.Rent(count);
try
{
var i = -1;
var indexCount = 0;
foreach (var value in source)
{
++i;
bool equals = excluding is null ? value is null : excluding.Equals(value);
if (!equals)
indexes[indexCount++] = i;
}
return indexCount == 0 ? -1 : indexes[R.Value.Next(indexCount)];
}
finally
{
pool.Return(indexes);
}
}
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">The optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndex<T>(this IReadOnlyCollection<T> source, Random? random = null, IEnumerable<T>? exclusion = null)
=> RandomSelectIndex(random, source.Count, source, exclusion);
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">A value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndexExcept<T>(this IReadOnlyCollection<T> source, Random random, T exclusion, params T[] others)
=> RandomSelectIndexExcept(random, source.Count, source, exclusion, others);
/// <summary>
/// Randomly selects an index from the source.
/// Will not return indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="exclusion">A value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The index selected.</returns>
public static int RandomSelectIndexExcept<T>(this IReadOnlyCollection<T> source, T exclusion, params T[] others)
=> RandomSelectIndexExcept(default, source.Count, source, exclusion, others);
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="value">The value selected.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">The values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOne<T>(
this in ReadOnlySpan<T> source,
out T value,
Random? random = null,
IEnumerable<T>? exclusion = null)
{
var index = RandomSelectIndex(in source, random, exclusion);
if (index == -1)
{
value = default!;
return false;
}
value = source[index];
return true;
}
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="value">The value selected.</param>
/// <param name="exclusion">The values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOne<T>(
this in ReadOnlySpan<T> source,
out T value,
IEnumerable<T> exclusion)
=> TryRandomSelectOne(in source, out value, null, exclusion);
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="value">The value selected.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">The optional values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOne<T>(
this in Span<T> source,
out T value,
Random? random = null,
IEnumerable<T>? exclusion = null)
=> TryRandomSelectOne((ReadOnlySpan<T>)source, out value, random, exclusion);
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="value">The value selected.</param>
/// <param name="exclusion">The values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOne<T>(
this in Span<T> source,
out T value,
IEnumerable<T> exclusion)
=> TryRandomSelectOne((ReadOnlySpan<T>)source, out value, null, exclusion);
static T GetElementAt<T>(IEnumerable<T> source, int index)
=> source switch
{
IReadOnlyList<T> readOnlyList => readOnlyList[index],
IList<T> list => list[index],
_ => source.ElementAt(index)
};
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">The optional values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOne<T>(
this IReadOnlyCollection<T> source,
Random? random = null,
IEnumerable<T>? exclusion = null)
{
if (source.Count == 0)
throw new InvalidOperationException("Source collection is empty.");
var index = RandomSelectIndex(random, source.Count, source, exclusion);
return index == -1
? throw new InvalidOperationException("Exclusion set invalidates the source. No possible value can be selected.")
: GetElementAt(source, index);
}
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="exclusion">The values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOne<T>(
this IReadOnlyCollection<T> source,
IEnumerable<T> exclusion)
=> RandomSelectOne(source, default, exclusion);
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="value">The value selected.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="exclusion">The optional values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOne<T>(
this IReadOnlyCollection<T> source,
out T value,
Random? random = null,
IEnumerable<T>? exclusion = null)
{
var index = RandomSelectIndex(random, source.Count, source, exclusion);
if (index == -1)
{
value = default!;
return false;
}
value = GetElementAt(source, index);
return true;
}
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="value">The value selected.</param>
/// <param name="exclusion">The values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOne<T>(
this IReadOnlyCollection<T> source,
out T value,
IEnumerable<T> exclusion)
=> TryRandomSelectOne(source, out value, default, exclusion);
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="value">The value selected.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOneExcept<T>(
this in ReadOnlySpan<T> source,
out T value,
Random? random,
T excluding, params T[] others)
{
var index = RandomSelectIndexExcept(in source, random, excluding, others);
if (index == -1)
{
value = default!;
return false;
}
value = source[index];
return true;
}
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="value">The value selected.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOneExcept<T>(
this in ReadOnlySpan<T> source,
out T value,
T excluding, params T[] others)
=> TryRandomSelectOneExcept(in source, out value, default, excluding, others);
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="value">The value selected.</param>
/// <param name="excluding">The optional values to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOneExcept<T>(
this in Span<T> source,
out T value,
Random? random,
T excluding, params T[] others)
=> TryRandomSelectOneExcept((ReadOnlySpan<T>)source, out value, random, excluding, others);
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="value">The value selected.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOneExcept<T>(
this IReadOnlyCollection<T> source,
out T value,
Random? random,
T excluding, params T[] others)
{
var index = RandomSelectIndexExcept(random, source.Count, source, excluding, others);
if (index == -1)
{
value = default!;
return false;
}
value = GetElementAt(source, index);
return true;
}
/// <summary>
/// Attempts to select an index at random from the source and returns the value from it..
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="value">The value selected.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>True if a valid value was selected.</returns>
public static bool TryRandomSelectOneExcept<T>(
this IReadOnlyCollection<T> source,
out T value,
T excluding, params T[] others)
=> TryRandomSelectOneExcept(source, out value, default, excluding, others);
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOneExcept<T>(
this in ReadOnlySpan<T> source,
Random? random,
T excluding, params T[] others)
=> source.Length == 0
? throw new InvalidOperationException("Source collection is empty.")
: TryRandomSelectOneExcept(in source, out T value, random, excluding, others)
? value
: throw new InvalidOperationException("Exclusion set invalidates the source. No possible value can be selected.");
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOneExcept<T>(
this in ReadOnlySpan<T> source,
T excluding, params T[] others)
=> RandomSelectOneExcept(in source, default, excluding, others);
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOneExcept<T>(
this in Span<T> source,
Random? random,
T excluding, params T[] others)
=> RandomSelectOneExcept((ReadOnlySpan<T>)source, random, excluding, others);
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source span.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOneExcept<T>(
this in Span<T> source,
T excluding, params T[] others)
=> RandomSelectOneExcept((ReadOnlySpan<T>)source, default, excluding, others);
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="random">The optional source of random numbers.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOneExcept<T>(
this IReadOnlyCollection<T> source,
Random? random,
T excluding, params T[] others)
=> source.Count == 0
? throw new InvalidOperationException("Source collection is empty.")
: source.TryRandomSelectOneExcept(out T value, random, excluding, others)
? value
: throw new InvalidOperationException("Exclusion set invalidates the source. No possible value can be selected.");
/// <summary>
/// Selects an index at random from the source and returns the value from it.
/// Will not select indexes that are contained in the optional exclusion set.
/// </summary>
/// <typeparam name="T">The generic type of the source.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="excluding">The value to exclude from selection.</param>
/// <param name="others">The additional set of optional values to exclude from selection.</param>
/// <returns>The value selected.</returns>
public static T RandomSelectOneExcept<T>(
this IReadOnlyCollection<T> source,
T excluding, params T[] others)
=> RandomSelectOneExcept(source, default, excluding, others);
/// <summary>
/// Select a random number except the excluded ones.
/// </summary>
/// <param name="range">The range of values to select from.</param>
/// <param name="exclusion">The values to exclude.</param>
/// <returns>The value selected.</returns>
public static ushort NextExcluding(this Random source,
ushort range,
IEnumerable<ushort> exclusion)
{
if (range == 0)
throw new ArgumentOutOfRangeException(nameof(range), range, "Must be a number greater than zero.");
DeferredHashSet<ushort>? setCreated = null;
try
{
var exclusionSet = exclusion == null ? null
: exclusion as ISet<ushort> ?? (setCreated = new DeferredHashSet<ushort>(exclusion));
if (exclusionSet == null || exclusionSet.Count == 0)
return (ushort)source.Next(range);
var pool = ArrayPool<ushort>.Shared;
var indexes = pool.Rent(range);
try
{
var indexCount = 0;
for (ushort i = 0; i < range; ++i)
{
if (!exclusionSet.Contains(i))
indexes[indexCount++] = i;
}
return indexCount == 0
? throw new InvalidOperationException("Exclusion set invalidates the source. No possible value can be selected.")
: indexes[source.Next(indexCount)];
}
finally
{
pool.Return(indexes);
}
}
finally
{
setCreated?.Dispose();
}
}
/// <summary>
/// Select a random number except the excluded ones.
/// </summary>
/// <param name="range">The range of values to select from.</param>
/// <param name="exclusion">The values to exclude.</param>
/// <returns>The value selected.</returns>
public static int NextExcluding(this Random source,
int range,
IEnumerable<int> exclusion)
{
if (range <= 0)
throw new ArgumentOutOfRangeException(nameof(range), range, "Must be a number greater than zero.");
DeferredHashSet<int>? setCreated = null;
try
{
var exclusionSet = exclusion == null ? null
: exclusion as ISet<int> ?? (setCreated = new DeferredHashSet<int>(exclusion));
if (exclusionSet == null || exclusionSet.Count == 0)
return source.Next(range);
var pool = ArrayPool<int>.Shared;
var indexes = pool.Rent(range);
try
{
var indexCount = 0;
for (var i = 0; i < range; ++i)
{
if (!exclusionSet.Contains(i))
indexes[indexCount++] = i;
}
return indexCount == 0
? throw new InvalidOperationException("Exclusion set invalidates the source. No possible value can be selected.")
: indexes[source.Next(indexCount)];
}
finally
{
pool.Return(indexes);
}
}
finally
{
setCreated?.Dispose();
}
}
/// <summary>
/// Select a random number but skip the excluded one.
/// </summary>
/// <param name="range">The range of values to select from.</param>
/// <param name="excluding">The value to skip.</param>
/// <returns>The value selected.</returns>
public static int NextExcluding(this Random source,
int range,
int excluding, params int[] others)
{
if (range <= 0)
throw new ArgumentOutOfRangeException(nameof(range), range, "Must be a number greater than zero.");
if (others.Length != 0)
return source.NextExcluding(range, others.Prepend(excluding));
if (excluding >= range || excluding < 0)
return source.Next(range);
if (excluding == 0 && range == 1)
throw new ArgumentException("No value is available with a range of 1 and exclusion of 0.", nameof(range));
var i = source.Next(range - 1);
return i < excluding ? i : i + 1;
}
/// <summary>
/// Select a random number but skip the excluded one.
/// </summary>
/// <param name="range">The range of values to select from.</param>
/// <param name="excluding">The value to skip.</param>
/// <returns>The value selected.</returns>
public static int NextExcluding(this Random source,
int range,
uint excluding, params uint[] others)
{
var exInt = excluding > int.MaxValue ? -1 : (int)excluding;
return others.Length == 0
? NextExcluding(source, range, exInt)
: NextExcluding(source, range,
others.Where(v => v <= int.MaxValue).Cast<int>().Prepend(exInt));
}
}
| 38.922222 | 132 | 0.694919 | [
"MIT"
] | electricessence/Open.RandomizationExtensions | Randomizer.cs | 35,032 | C# |
namespace YourBrand.Customers.Application;
public record ItemsResult<T>(IEnumerable<T> Items, int TotalItems); | 37.666667 | 67 | 0.814159 | [
"MIT"
] | marinasundstrom/YourCompany | Customers/Customers/Application/ItemsResult.cs | 113 | C# |
using System.Threading;
using Cysharp.Threading.Tasks;
namespace Runtime.Executor
{
public interface IStateWorker
{
public GameState GameState { get; }
public UniTask Work(CancellationToken token);
}
}
| 17.846154 | 53 | 0.702586 | [
"MIT"
] | nekomimi-daimao/BotTestBed | Assets/BotTestBed/Scripts/Runtime/Executor/IStateWorker.cs | 232 | C# |
using System.Net.NetworkInformation;
using Thinktecture.Collections.Generic;
namespace Thinktecture.Net.NetworkInformation
{
/// <summary>
/// Stores a set of IPAddressInformation types.
/// </summary>
// ReSharper disable once InconsistentNaming
public interface IIPAddressInformationCollection : INotNullCollectionAbstraction<IIPAddressInformation, IPAddressInformation, IPAddressInformationCollection>
{
/// <summary>
/// Gets the IPAddressInformation at the specified index in the collection.
/// </summary>
/// <param name="index">The zero-based index of the element.</param>
/// <returns>The IPAddressInformation at the specified location.</returns>
IIPAddressInformation? this[int index] { get; }
}
}
| 37.35 | 159 | 0.752343 | [
"BSD-3-Clause"
] | PawelGerr/Thinktecture.Abstractions | src/Thinktecture.Net.NetworkInformation.Abstractions/Net/NetworkInformation/IIPAddressInformationCollection.cs | 747 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Collections;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Select.Carousel
{
public class DrawableCarouselBeatmap : DrawableCarouselItem, IHasContextMenu
{
public const float CAROUSEL_BEATMAP_SPACING = 5;
/// <summary>
/// The height of a carousel beatmap, including vertical spacing.
/// </summary>
public const float HEIGHT = height + CAROUSEL_BEATMAP_SPACING;
private const float height = MAX_HEIGHT * 0.6f;
private readonly BeatmapInfo beatmap;
private Sprite background;
private Action<BeatmapInfo> startRequested;
private Action<BeatmapInfo> editRequested;
private Action<BeatmapInfo> hideRequested;
private Triangles triangles;
private StarCounter starCounter;
[Resolved(CanBeNull = true)]
private BeatmapSetOverlay beatmapOverlay { get; set; }
[Resolved]
private BeatmapDifficultyManager difficultyManager { get; set; }
[Resolved(CanBeNull = true)]
private CollectionManager collectionManager { get; set; }
[Resolved(CanBeNull = true)]
private ManageCollectionsDialog manageCollectionsDialog { get; set; }
private IBindable<StarDifficulty> starDifficultyBindable;
private CancellationTokenSource starDifficultyCancellationSource;
public DrawableCarouselBeatmap(CarouselBeatmap panel)
{
beatmap = panel.Beatmap;
Item = panel;
}
[BackgroundDependencyLoader(true)]
private void load(BeatmapManager manager, SongSelect songSelect)
{
Header.Height = height;
if (songSelect != null)
{
startRequested = b => songSelect.FinaliseSelection(b);
if (songSelect.AllowEditing)
editRequested = songSelect.Edit;
}
if (manager != null)
hideRequested = manager.Hide;
Header.Children = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
},
triangles = new Triangles
{
TriangleScale = 2,
RelativeSizeAxes = Axes.Both,
ColourLight = Color4Extensions.FromHex(@"3a7285"),
ColourDark = Color4Extensions.FromHex(@"123744")
},
new FillFlowContainer
{
Padding = new MarginPadding(5),
Direction = FillDirection.Horizontal,
AutoSizeAxes = Axes.Both,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Children = new Drawable[]
{
new DifficultyIcon(beatmap, shouldShowTooltip: false)
{
Scale = new Vector2(1.8f),
},
new FillFlowContainer
{
Padding = new MarginPadding { Left = 5 },
Direction = FillDirection.Vertical,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new FillFlowContainer
{
Direction = FillDirection.Horizontal,
Spacing = new Vector2(4, 0),
AutoSizeAxes = Axes.Both,
Children = new[]
{
new OsuSpriteText
{
Text = beatmap.Version,
Font = OsuFont.GetFont(size: 20),
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft
},
new OsuSpriteText
{
Text = "mapped by",
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft
},
new OsuSpriteText
{
Text = $"{(beatmap.Metadata ?? beatmap.BeatmapSet.Metadata).Author.Username}",
Font = OsuFont.GetFont(italics: true),
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft
},
}
},
new FillFlowContainer
{
Direction = FillDirection.Horizontal,
Spacing = new Vector2(4, 0),
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new TopLocalRank(beatmap)
{
Scale = new Vector2(0.8f),
Size = new Vector2(40, 20)
},
starCounter = new StarCounter
{
Scale = new Vector2(0.8f),
}
}
}
}
}
}
}
};
}
protected override void Selected()
{
base.Selected();
MovementContainer.MoveToX(-50, 500, Easing.OutExpo);
background.Colour = ColourInfo.GradientVertical(
new Color4(20, 43, 51, 255),
new Color4(40, 86, 102, 255));
triangles.Colour = Color4.White;
}
protected override void Deselected()
{
base.Deselected();
MovementContainer.MoveToX(0, 500, Easing.OutExpo);
background.Colour = new Color4(20, 43, 51, 255);
triangles.Colour = OsuColour.Gray(0.5f);
}
protected override bool OnClick(ClickEvent e)
{
if (Item.State.Value == CarouselItemState.Selected)
startRequested?.Invoke(beatmap);
return base.OnClick(e);
}
protected override void ApplyState()
{
if (Item.State.Value != CarouselItemState.Collapsed && Alpha == 0)
starCounter.ReplayAnimation();
starDifficultyCancellationSource?.Cancel();
// Only compute difficulty when the item is visible.
if (Item.State.Value != CarouselItemState.Collapsed)
{
// We've potentially cancelled the computation above so a new bindable is required.
starDifficultyBindable = difficultyManager.GetBindableDifficulty(beatmap, (starDifficultyCancellationSource = new CancellationTokenSource()).Token);
starDifficultyBindable.BindValueChanged(d => starCounter.Current = (float)d.NewValue.Stars, true);
}
base.ApplyState();
}
public MenuItem[] ContextMenuItems
{
get
{
List<MenuItem> items = new List<MenuItem>();
if (startRequested != null)
items.Add(new OsuMenuItem("Play", MenuItemType.Highlighted, () => startRequested(beatmap)));
if (editRequested != null)
items.Add(new OsuMenuItem("Edit", MenuItemType.Standard, () => editRequested(beatmap)));
if (beatmap.OnlineBeatmapID.HasValue && beatmapOverlay != null)
items.Add(new OsuMenuItem("Details...", MenuItemType.Standard, () => beatmapOverlay.FetchAndShowBeatmap(beatmap.OnlineBeatmapID.Value)));
if (collectionManager != null)
{
var collectionItems = collectionManager.Collections.Select(createCollectionMenuItem).ToList();
if (manageCollectionsDialog != null)
collectionItems.Add(new OsuMenuItem("Manage...", MenuItemType.Standard, manageCollectionsDialog.Show));
items.Add(new OsuMenuItem("Collections") { Items = collectionItems });
}
if (hideRequested != null)
items.Add(new OsuMenuItem("Hide", MenuItemType.Destructive, () => hideRequested(beatmap)));
return items.ToArray();
}
}
private MenuItem createCollectionMenuItem(BeatmapCollection collection)
{
return new ToggleMenuItem(collection.Name.Value, MenuItemType.Standard, s =>
{
if (s)
collection.Beatmaps.Add(beatmap);
else
collection.Beatmaps.Remove(beatmap);
})
{
State = { Value = collection.Beatmaps.Contains(beatmap) }
};
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
starDifficultyCancellationSource?.Cancel();
}
}
}
| 39.92446 | 165 | 0.475628 | [
"MIT"
] | AaqibAhamed/osu | osu.Game/Screens/Select/Carousel/DrawableCarouselBeatmap.cs | 10,822 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Get a list of Route Points that are using the specified Route Point External System.
/// The response is either a SystemRoutePointExternalSystemGetRoutePointListResponse or an
/// ErrorResponse.
/// <see cref="SystemRoutePointExternalSystemGetRoutePointListResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:14060""}]")]
public class SystemRoutePointExternalSystemGetRoutePointListRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private string _routePointExternalSystem;
[XmlElement(ElementName = "routePointExternalSystem", IsNullable = false, Namespace = "")]
[Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14060")]
[MinLength(1)]
[MaxLength(40)]
public string RoutePointExternalSystem
{
get => _routePointExternalSystem;
set
{
RoutePointExternalSystemSpecified = true;
_routePointExternalSystem = value;
}
}
[XmlIgnore]
protected bool RoutePointExternalSystemSpecified { get; set; }
}
}
| 34.227273 | 131 | 0.683931 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemRoutePointExternalSystemGetRoutePointListRequest.cs | 1,506 | C# |
namespace Rocks.Helpers
{
public class TimeSpanFormatStrings
{
#region Static fields
private static TimeSpanFormatStrings _default =
new TimeSpanFormatStrings
{
Milliseconds = " ms",
Seconds = " sec",
Minutes = " min",
Hours = " h",
Days = " d",
};
#endregion
#region Public properties
public static TimeSpanFormatStrings Default
{
get { return _default; }
set { _default = value; }
}
public string Milliseconds { get; set; }
public string Seconds { get; set; }
public string Minutes { get; set; }
public string Hours { get; set; }
public string Days { get; set; }
#endregion
}
} | 24.057143 | 55 | 0.498812 | [
"MIT"
] | MichaelLogutov/Rocks.Helpers | src/Rocks.Helpers/TimeSpanFormatStrings.cs | 844 | 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 xray-2016-04-12.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.XRay.Model
{
/// <summary>
/// The root cause information for a trace summary fault.
/// </summary>
public partial class FaultRootCause
{
private bool? _clientImpacting;
private List<FaultRootCauseService> _services = new List<FaultRootCauseService>();
/// <summary>
/// Gets and sets the property ClientImpacting.
/// <para>
/// A flag that denotes that the root cause impacts the trace client.
/// </para>
/// </summary>
public bool ClientImpacting
{
get { return this._clientImpacting.GetValueOrDefault(); }
set { this._clientImpacting = value; }
}
// Check to see if ClientImpacting property is set
internal bool IsSetClientImpacting()
{
return this._clientImpacting.HasValue;
}
/// <summary>
/// Gets and sets the property Services.
/// <para>
/// A list of corresponding services. A service identifies a segment and it contains a
/// name, account ID, type, and inferred flag.
/// </para>
/// </summary>
public List<FaultRootCauseService> Services
{
get { return this._services; }
set { this._services = value; }
}
// Check to see if Services property is set
internal bool IsSetServices()
{
return this._services != null && this._services.Count > 0;
}
}
} | 31.207792 | 102 | 0.633375 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/XRay/Generated/Model/FaultRootCause.cs | 2,403 | C# |
using System;
namespace Raygun.Druid4Net
{
public class DruidClientException : Exception
{
public DruidClientException()
{
}
public DruidClientException(string message) : base(message)
{
}
public DruidClientException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
| 17.25 | 105 | 0.689855 | [
"MIT"
] | Derivitec/druid4net | Raygun.Druid4Net/DruidClientException.cs | 347 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Mondo.Messages
{
internal sealed class ListAccountsResponse
{
[JsonProperty("accounts")]
public IList<Account> Accounts { get; set; }
}
} | 21.272727 | 52 | 0.688034 | [
"MIT"
] | KonradNN/Monzo.Api | Mondo/Messages/ListAccountsResponse.cs | 236 | C# |
namespace MongoCms.Entity
{
public class PriceAdjustment
{
public decimal OldPrice { get; set; }
public decimal NewPrice { get; set; }
public string Reason { get; set; }
public PriceAdjustment(AdjustPrice adjustPrice, decimal oldPrice)
{
OldPrice = oldPrice;
NewPrice = adjustPrice.NewPrice;
Reason = adjustPrice.Reason;
}
public string Describe()
{
return string.Format("{0} -> {1}: {2}", OldPrice, NewPrice, Reason);
}
}
} | 20.086957 | 71 | 0.679654 | [
"MIT"
] | nrock/MongoCms | Source/MongoCms.Entity/PriceAdjustment.cs | 464 | C# |
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("GrenMajuThunderBoarder", "AI_GrenMajuThunderBoarder")]
public class GrenMajuThunderBoarderExecutor : DefaultExecutor
{
public class CardId
{
public const int MetalSnake = 71197066;
public const int InspectBoarder = 15397015;
public const int ThunderKingRaiOh = 71564252;
public const int AshBlossomAndJoyousSpring =14558127;
public const int GhostReaperAndWinterCherries = 62015408;
public const int GrenMajuDaEizo = 36584821;
public const int MaxxC = 23434538;
public const int EaterOfMillions = 63845230;
public const int HarpieFeatherDuster = 18144506;
public const int PotOfDesires = 35261759;
public const int CardOfDemise = 59750328;
public const int UpstartGoblin = 70368879;
public const int PotOfDuality = 98645731;
public const int Scapegoat = 73915051;
public const int MoonMirrorShield = 19508728;
public const int InfiniteImpermanence = 10045474;
public const int WakingTheDragon = 10813327;
public const int EvenlyMatched = 15693423;
public const int HeavyStormDuster = 23924608;
public const int DrowningMirrorForce = 47475363;
public const int MacroCosmos = 30241314;
public const int Crackdown = 36975314;
public const int AntiSpellFragrance = 58921041;
public const int ImperialOrder = 61740673;
public const int PhatomKnightsSword = 61936647;
public const int UnendingNightmare= 69452756;
public const int SolemnWarning = 84749824;
public const int SolemStrike= 40605147;
public const int SolemnJudgment = 41420027;
public const int DarkBribe = 77538567;
public const int RaidraptorUltimateFalcon = 86221741;
public const int BorreloadDragon = 31833038;
public const int BirrelswordDragon = 85289965;
public const int FirewallDragon = 5043010;
public const int NingirsuTheWorldChaliceWarrior = 30194529;
public const int TopologicTrisbaena = 72529749;
public const int KnightmareUnicorn = 38342335;
public const int KnightmarePhoenix = 2857636;
public const int HeavymetalfoesElectrumite= 24094258;
public const int KnightmareCerberus = 75452921;
public const int CrystronNeedlefiber = 50588353;
public const int MissusRadiant= 3987233;
public const int BrandishMaidenKagari= 63288573;
public const int LinkSpider = 98978921;
public const int Linkuriboh = 41999284;
public const int KnightmareGryphon = 65330383;
}
public GrenMajuThunderBoarderExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.GoToBattlePhase, GoToBattlePhase);
AddExecutor(ExecutorType.Activate, CardId.EvenlyMatched, EvenlyMatchedeff);
//Sticker
AddExecutor(ExecutorType.Activate, CardId.MacroCosmos, MacroCosmoseff);
AddExecutor(ExecutorType.Activate, CardId.AntiSpellFragrance, AntiSpellFragranceeff);
//counter
AddExecutor(ExecutorType.Activate, CardId.AshBlossomAndJoyousSpring, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC);
AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, DefaultInfiniteImpermanence);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.ImperialOrder, ImperialOrderfirst);
AddExecutor(ExecutorType.Activate, CardId.HeavyStormDuster, HeavyStormDustereff);
AddExecutor(ExecutorType.Activate, CardId.UnendingNightmare, UnendingNightmareeff);
AddExecutor(ExecutorType.Activate, CardId.DarkBribe, DarkBribeeff);
AddExecutor(ExecutorType.Activate, CardId.ImperialOrder, ImperialOrdereff);
AddExecutor(ExecutorType.Activate, CardId.ThunderKingRaiOh, ThunderKingRaiOheff);
AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, CardId.DrowningMirrorForce, DrowningMirrorForceeff);
//first do
AddExecutor(ExecutorType.Activate, CardId.UpstartGoblin, UpstartGoblineff);
AddExecutor(ExecutorType.Activate, CardId.HarpieFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.PotOfDuality, PotOfDualityeff);
AddExecutor(ExecutorType.Activate, CardId.PotOfDesires, PotOfDesireseff);
AddExecutor(ExecutorType.Activate, CardId.CardOfDemise, CardOfDemiseeff);
//sp
AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboheff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
AddExecutor(ExecutorType.SpSummon, CardId.KnightmareCerberus,Knightmaresp);
AddExecutor(ExecutorType.SpSummon, CardId.KnightmarePhoenix, Knightmaresp);
AddExecutor(ExecutorType.SpSummon, CardId.MissusRadiant, MissusRadiantsp);
AddExecutor(ExecutorType.Activate, CardId.MissusRadiant, MissusRadianteff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider);
AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragonsp);
AddExecutor(ExecutorType.Activate, CardId.BorreloadDragon, BorreloadDragoneff);
AddExecutor(ExecutorType.Activate, CardId.EaterOfMillions, EaterOfMillionseff);
AddExecutor(ExecutorType.Activate, CardId.WakingTheDragon, WakingTheDragoneff);
// normal summon
AddExecutor(ExecutorType.Summon, CardId.InspectBoarder, InspectBoardersummon);
AddExecutor(ExecutorType.Summon, CardId.GrenMajuDaEizo, GrenMajuDaEizosummon);
AddExecutor(ExecutorType.Summon, CardId.ThunderKingRaiOh, ThunderKingRaiOhsummon);
AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragonspsecond);
AddExecutor(ExecutorType.SpSummon, CardId.EaterOfMillions, EaterOfMillionssp);
AddExecutor(ExecutorType.Activate, CardId.MetalSnake, MetalSnakesp);
AddExecutor(ExecutorType.Activate, CardId.MetalSnake, MetalSnakeeff);
//spell
AddExecutor(ExecutorType.Activate, CardId.Crackdown, Crackdowneff);
AddExecutor(ExecutorType.Activate, CardId.MoonMirrorShield, MoonMirrorShieldeff);
AddExecutor(ExecutorType.Activate, CardId.Scapegoat, DefaultScapegoat);
AddExecutor(ExecutorType.Activate, CardId.PhatomKnightsSword, PhatomKnightsSwordeff);
AddExecutor(ExecutorType.Repos, MonsterRepos);
//set
AddExecutor(ExecutorType.SpellSet, SpellSet);
}
bool CardOfDemiseeff_used = false;
bool eater_eff = false;
public override void OnNewTurn()
{
eater_eff = false;
CardOfDemiseeff_used = false;
}
public override void OnNewPhase()
{
foreach (ClientCard check in Bot.GetMonsters())
{
if (check.HasType(CardType.Fusion) || check.HasType(CardType.Xyz) ||
check.HasType(CardType.Synchro) || check.HasType(CardType.Link) ||
check.HasType(CardType.Ritual))
{
eater_eff = true;
break;
}
}
foreach (ClientCard check in Enemy.GetMonsters())
{
if (check.HasType(CardType.Fusion) || check.HasType(CardType.Xyz) ||
check.HasType(CardType.Synchro) || check.HasType(CardType.Link) ||
check.HasType(CardType.Ritual))
{
eater_eff = true;
break;
}
}
base.OnNewPhase();
}
private bool GoToBattlePhase()
{
return Bot.HasInHand(CardId.EvenlyMatched) && Duel.Turn >= 2 && Enemy.GetFieldCount() >= 2 && Bot.GetFieldCount() == 0;
}
private bool MacroCosmoseff()
{
return (Duel.LastChainPlayer == 1 || Duel.LastSummonPlayer == 1 || Duel.Player == 0) && UniqueFaceupSpell();
}
private bool AntiSpellFragranceeff()
{
int spell_count = 0;
foreach(ClientCard check in Bot.Hand)
{
if (check.HasType(CardType.Spell))
spell_count++;
}
if (spell_count >= 2) return false;
return Duel.Player == 1 && UniqueFaceupSpell();
}
private bool EvenlyMatchedeff()
{
return Enemy.GetFieldCount()-Bot.GetFieldCount() > 1;
}
private bool HeavyStormDustereff()
{
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard check in Enemy.GetSpells())
{
if (check.HasType(CardType.Continuous) || check.HasType(CardType.Field))
targets.Add(check);
}
if (Util.GetPZone(1, 0) != null && Util.GetPZone(1, 0).Type == 16777218)
{
targets.Add(Util.GetPZone(1, 0));
}
if (Util.GetPZone(1, 1) != null && Util.GetPZone(1, 1).Type == 16777218)
{
targets.Add(Util.GetPZone(1, 1));
}
foreach (ClientCard check in Enemy.GetSpells())
{
if (!check.HasType(CardType.Continuous) && !check.HasType(CardType.Field))
targets.Add(check);
}
if(DefaultOnBecomeTarget())
{
AI.SelectCard(targets);
return true;
}
int count = 0;
foreach(ClientCard check in Enemy.GetSpells())
{
if (check.Type == 16777218)
count++;
}
if(Util.GetLastChainCard()!=null &&
(Util.GetLastChainCard().HasType(CardType.Continuous)||
Util.GetLastChainCard().HasType(CardType.Field) || count==2) &&
Duel.LastChainPlayer==1)
{
AI.SelectCard(targets);
return true;
}
return false;
}
private bool UnendingNightmareeff()
{
ClientCard card = null;
foreach(ClientCard check in Enemy.GetSpells())
{
if (check.HasType(CardType.Continuous) || check.HasType(CardType.Field))
card = check;
break;
}
int count = 0;
foreach (ClientCard check in Enemy.GetSpells())
{
if (check.Type == 16777218)
count++;
}
if(count==2)
{
if (Util.GetPZone(1, 1) != null && Util.GetPZone(1, 1).Type == 16777218)
{
card=Util.GetPZone(1, 1);
}
}
if (card!=null && Bot.LifePoints>1000)
{
AI.SelectCard(card);
return true;
}
return false;
}
private bool DarkBribeeff()
{
if (Util.GetLastChainCard()!=null && Util.GetLastChainCard().IsCode(CardId.UpstartGoblin))
return false;
return true;
}
private bool ImperialOrderfirst()
{
if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.UpstartGoblin))
return false;
return DefaultOnBecomeTarget() && Util.GetLastChainCard().HasType(CardType.Spell);
}
private bool ImperialOrdereff()
{
if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.UpstartGoblin))
return false;
if (Duel.LastChainPlayer == 1)
{
foreach(ClientCard check in Enemy.GetSpells())
{
if (Util.GetLastChainCard() == check)
return true;
}
}
return false;
}
private bool DrowningMirrorForceeff()
{
if(Enemy.GetMonsterCount() ==1)
{
if(Enemy.BattlingMonster.Attack-Bot.LifePoints>=1000)
return DefaultUniqueTrap();
}
if (Util.GetTotalAttackingMonsterAttack(1) >= Bot.LifePoints)
return DefaultUniqueTrap();
if (Enemy.GetMonsterCount() >= 2)
return DefaultUniqueTrap();
return false;
}
private bool UpstartGoblineff()
{
return !DefaultSpellWillBeNegated();
}
private bool PotOfDualityeff()
{
if (DefaultSpellWillBeNegated())
return false;
int count = 0;
if (Bot.GetMonsterCount() > 0)
count = 1;
foreach(ClientCard card in Bot.Hand)
{
if (card.HasType(CardType.Monster))
count++;
}
if(Util.GetBestEnemyMonster()!=null && Util.GetBestEnemyMonster().Attack>=1900)
AI.SelectCard(
CardId.EaterOfMillions,
CardId.PotOfDesires,
CardId.GrenMajuDaEizo,
CardId.InspectBoarder,
CardId.ThunderKingRaiOh,
CardId.Scapegoat,
CardId.SolemnJudgment,
CardId.SolemnWarning,
CardId.SolemStrike,
CardId.InfiniteImpermanence
);
if (count == 0)
AI.SelectCard(
CardId.PotOfDesires,
CardId.InspectBoarder,
CardId.ThunderKingRaiOh,
CardId.EaterOfMillions,
CardId.GrenMajuDaEizo,
CardId.Scapegoat
);
else
{
AI.SelectCard(
CardId.PotOfDesires,
CardId.CardOfDemise,
CardId.SolemnJudgment,
CardId.SolemnWarning,
CardId.SolemStrike,
CardId.InfiniteImpermanence,
CardId.Scapegoat
);
}
return true;
}
private bool PotOfDesireseff()
{
if (CardOfDemiseeff_used) return false;
return Bot.Deck.Count > 14 && !DefaultSpellWillBeNegated();
}
private bool CardOfDemiseeff()
{
if (Bot.Hand.Count == 1 && Bot.GetSpellCountWithoutField() <= 3 && !DefaultSpellWillBeNegated())
{
CardOfDemiseeff_used = true;
return true;
}
return false;
}
private bool Crackdowneff()
{
if (Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack)
AI.SelectCard(Util.GetOneEnemyBetterThanMyBest(true, true));
return Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack;
}
private bool MoonMirrorShieldeff()
{
if(Card.Location==CardLocation.Hand)
{
if (Bot.GetMonsterCount() == 0) return false;
return !DefaultSpellWillBeNegated();
}
if(Card.Location==CardLocation.Grave)
{
return true;
}
return false;
}
private bool PhatomKnightsSwordeff()
{
if (Card.IsFaceup())
return true;
if(Duel.Phase==DuelPhase.BattleStart && Bot.BattlingMonster!=null && Enemy.BattlingMonster!=null)
{
if (Bot.BattlingMonster.Attack + 800 >= Enemy.BattlingMonster.GetDefensePower())
{
AI.SelectCard(Bot.BattlingMonster);
return DefaultUniqueTrap();
}
}
return false;
}
private bool InspectBoardersummon()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return true;
}
private bool GrenMajuDaEizosummon()
{
if (Duel.Turn == 1) return false;
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return Bot.Banished.Count >= 6;
}
private bool ThunderKingRaiOhsummon()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return true;
}
private bool ThunderKingRaiOheff()
{
if(Duel.SummoningCards.Count > 0)
{
foreach(ClientCard m in Duel.SummoningCards)
{
if (m.Attack >= 1900)
return true;
}
}
return false;
}
private bool BorreloadDragonsp()
{
if (!(Bot.HasInMonstersZone(CardId.MissusRadiant) || Bot.HasInMonstersZone(new[] { CardId.KnightmareCerberus, CardId.KnightmarePhoenix }))) return false;
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.IsCode(CardId.MissusRadiant, CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LinkSpider, CardId.Linkuriboh))
material_list.Add(monster);
if (material_list.Count == 3) break;
}
if (material_list.Count >= 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
private bool BorreloadDragonspsecond()
{
if (!(Bot.HasInMonstersZone(CardId.MissusRadiant) || Bot.HasInMonstersZone(new[] { CardId.KnightmareCerberus,CardId.KnightmarePhoenix }))) return false;
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.IsCode(CardId.MissusRadiant, CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LinkSpider, CardId.Linkuriboh))
material_list.Add(monster);
if (material_list.Count == 3) break;
}
if (material_list.Count >= 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
public bool BorreloadDragoneff()
{
if (ActivateDescription == -1 && (Duel.Phase==DuelPhase.BattleStart||Duel.Phase==DuelPhase.End))
{
ClientCard enemy_monster = Enemy.BattlingMonster;
if (enemy_monster != null && enemy_monster.HasPosition(CardPosition.Attack))
{
return (Card.Attack - enemy_monster.Attack < Enemy.LifePoints);
}
return true;
};
ClientCard BestEnemy = Util.GetBestEnemyMonster(true);
ClientCard WorstBot = Bot.GetMonsters().GetLowestAttackMonster();
if (BestEnemy == null || BestEnemy.HasPosition(CardPosition.FaceDown)) return false;
if (WorstBot == null || WorstBot.HasPosition(CardPosition.FaceDown)) return false;
if (BestEnemy.Attack >= WorstBot.RealPower)
{
AI.SelectCard(BestEnemy);
return true;
}
return false;
}
private bool EaterOfMillionssp()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
if (Enemy.HasInMonstersZone(CardId.KnightmareGryphon, true)) return false;
if (Bot.HasInMonstersZone(CardId.InspectBoarder) && !eater_eff) return false;
if (Util.GetProblematicEnemyMonster() == null && Bot.ExtraDeck.Count < 5) return false;
if (Bot.GetMonstersInMainZone().Count >= 5) return false;
if (Util.IsTurn1OrMain2()) return false;
AI.SelectPosition(CardPosition.FaceUpAttack);
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard e_c in Bot.ExtraDeck)
{
targets.Add(e_c);
if (targets.Count >= 5)
{
AI.SelectCard(targets);
/*AI.SelectCard(new[] {
CardId.BingirsuTheWorldChaliceWarrior,
CardId.TopologicTrisbaena,
CardId.KnightmareCerberus,
CardId.KnightmarePhoenix,
CardId.KnightmareUnicorn,
CardId.BrandishMaidenKagari,
CardId.HeavymetalfoesElectrumite,
CardId.CrystronNeedlefiber,
CardId.FirewallDragon,
CardId.BirrelswordDragon,
CardId.RaidraptorUltimateFalcon,
});*/
AI.SelectPlace(Zones.z4 | Zones.z0);
return true;
}
}
Logger.DebugWriteLine("*** Eater use up the extra deck.");
foreach (ClientCard s_c in Bot.GetSpells())
{
targets.Add(s_c);
if (targets.Count >= 5)
{
AI.SelectCard(targets);
return true;
}
}
return false;
}
private bool EaterOfMillionseff()
{
if (Enemy.BattlingMonster.HasPosition(CardPosition.Attack) && (Bot.BattlingMonster.Attack - Enemy.BattlingMonster.GetDefensePower() >= Enemy.LifePoints)) return false;
return true;
}
private bool WakingTheDragoneff()
{
AI.SelectCard(new[] { CardId.RaidraptorUltimateFalcon });
return true;
}
private bool MetalSnakesp()
{
if (ActivateDescription == Util.GetStringId(CardId.MetalSnake, 0) && !Bot.HasInMonstersZone(CardId.MetalSnake))
{
if(Duel.Player == 1 && Duel.Phase >= DuelPhase.BattleStart )
return Bot.Deck.Count >= 12;
if(Duel.Player == 0 && Duel.Phase >= DuelPhase.Main1)
return Bot.Deck.Count >= 12;
}
return false;
}
private bool MetalSnakeeff()
{
ClientCard target = Util.GetOneEnemyBetterThanMyBest(true, true);
if (ActivateDescription == Util.GetStringId(CardId.MetalSnake, 1) && target != null)
{
AI.SelectCard(new[]
{
CardId.HeavymetalfoesElectrumite,
CardId.BrandishMaidenKagari,
CardId.CrystronNeedlefiber,
CardId.RaidraptorUltimateFalcon,
CardId.NingirsuTheWorldChaliceWarrior
});
AI.SelectNextCard(target);
return true;
}
return false;
}
private bool MissusRadiantsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Earth) && monster.Level==1 && !monster.IsCode(CardId.EaterOfMillions))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.MissusRadiant)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool MissusRadianteff()
{
AI.SelectCard(CardId.MaxxC, CardId.MissusRadiant);
return true;
}
private bool Linkuribohsp()
{
foreach (ClientCard c in Bot.GetMonsters())
{
if (!c.IsCode(CardId.EaterOfMillions, CardId.Linkuriboh) && c.Level==1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Knightmaresp()
{
int[] firstMats = new[] {
CardId.KnightmareCerberus,
CardId.KnightmarePhoenix
};
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(firstMats)) >= 1)return false;
foreach (ClientCard c in Bot.GetMonsters())
{
if (!c.IsCode(CardId.EaterOfMillions) && c.Level == 1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Linkuriboheff()
{
if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Linkuriboh)) return false;
return true;
}
private bool MonsterRepos()
{
if (Card.IsCode(CardId.EaterOfMillions) && Card.IsAttack()) return false;
return DefaultMonsterRepos();
}
private bool SpellSet()
{
int count = 0;
foreach(ClientCard check in Bot.Hand)
{
if (check.IsCode(CardId.CardOfDemise))
count++;
}
if (count == 2 && Bot.Hand.Count == 2 && Bot.GetSpellCountWithoutField() <= 2)
return true;
if (Card.IsCode(CardId.MacroCosmos) && Bot.HasInSpellZone(CardId.MacroCosmos)) return false;
if (Card.IsCode(CardId.AntiSpellFragrance) && Bot.HasInSpellZone(CardId.AntiSpellFragrance)) return false;
if (CardOfDemiseeff_used)return true;
if (Card.IsCode(CardId.EvenlyMatched) && (Enemy.GetFieldCount() - Bot.GetFieldCount()) < 0) return false;
if (Card.IsCode(CardId.AntiSpellFragrance) && Bot.HasInSpellZone(CardId.AntiSpellFragrance)) return false;
if (Card.IsCode(CardId.MacroCosmos) && Bot.HasInSpellZone(CardId.MacroCosmos)) return false;
if (Duel.Turn > 1 && Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster())
return false;
if (Card.IsCode(CardId.InfiniteImpermanence))
return Bot.GetFieldCount() > 0 && Bot.GetSpellCountWithoutField() < 4;
if (Card.IsCode(CardId.Scapegoat))
return true;
if (Card.HasType(CardType.Trap))
return Bot.GetSpellCountWithoutField() < 4;
if(Bot.HasInSpellZone(CardId.AntiSpellFragrance,true))
{
if (Card.IsCode(CardId.UpstartGoblin, CardId.PotOfDesires, CardId.PotOfDuality)) return true;
if (Card.IsCode(CardId.CardOfDemise) && Bot.HasInSpellZone(CardId.CardOfDemise)) return false;
if (Card.HasType(CardType.Spell))
return Bot.GetSpellCountWithoutField() < 4;
}
return false;
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (attacker.IsCode(_CardId.EaterOfMillions) && (Bot.HasInMonstersZone(CardId.InspectBoarder) && eater_eff) && !attacker.IsDisabled())
{
attacker.RealPower = 9999;
return true;
}
if (attacker.IsCode(_CardId.EaterOfMillions) && !Bot.HasInMonstersZone(CardId.InspectBoarder) && !attacker.IsDisabled())
{
attacker.RealPower = 9999;
return true;
}
return base.OnPreBattleBetween(attacker, defender);
}
public override ClientCard OnSelectAttacker(IList<ClientCard> attackers, IList<ClientCard> defenders)
{
for (int i = 0; i < attackers.Count; ++i)
{
ClientCard attacker = attackers[i];
if (attacker.IsCode(CardId.BirrelswordDragon, CardId.EaterOfMillions)) return attacker;
}
return null;
}
public override bool OnSelectHand()
{
return true;
}
}
} | 41.638239 | 179 | 0.544647 | [
"MIT"
] | Battle-City-Alpha/windbot | Game/AI/Decks/GrenMajuThunderBoarderExecutor.cs | 30,273 | C# |
// <copyright file="EfficientHttpClient.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2022 Datadog, Inc.
// </copyright>
#if NETCOREAPP || NETSTANDARD
// We will use System.Net.Http.HttpClient (see comments below for a discussion).
#define USE_HTTP_CLIENT
#if NET5_0
#define USE_HTTP_CLIENT_SEND_SYNC
#endif
#else
// We will use System.Net.WebRequest (see comments below for a discussion).
// We do not need to set up a "#define USE_WEB_REQUEST", because the respective code path is configured via #if-USE_HTTP_CLIENT-#else-#endif.
// #define USE_WEB_REQUEST
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using Datadog.Util;
#if USE_HTTP_CLIENT
using System.Net.Http;
#else
using System.Net;
#endif
namespace Datadog.Profiler
{
/// <summary>
/// We need an abstraction for HTTP client for several reasons:
/// - On .NET Framework:
/// we need to use WebRequest rather than HttpClient to avoid the dependency to System.Net.Http
/// - On .NET Core:
/// we need to use HttpClient rather than WebRequest because the dependency isn't an issue and WebRequest
/// on Net Core doesn't support TCP connection keep-alive until .NET 5.
/// (WebRequest on .NET Core is implemented on top of HttpClient. The way it works in older versions of Core
/// is that it creates a HttpClient under the hood, sends the request, and closes it. This closes the
/// underlying HTTP connection, so it means a new connection has to be established every time you send a request.
/// Since .NET 5 there is a pool of HttpClients (so the connection isn't closed).
/// It may sound like it isn't much, but it's made worse by the fact that (as of Jan 2021) the Datadog Agent only
/// binds the port to IPv4, and the client first tries to establish the connection with IPv6.
/// So, we need to wait for the IPv6 timeout before the connection is actually established.)
/// - We want a non-async send. This is because we operate from a non-thread-pooled dedicated background thread, and
/// we want to avoid interactions with the thread pool to avoid issues with thread starvation and other resource constraints.
/// HttpClient does not offer a sync API until .NET 5, so we perform a wait on the async API. But whereever available,
/// we use a sync API.
///
/// @ToDo: Once we have a .NET 5 build target, use Send(..) intead of SendAsync(..) on the HttpClient.
/// </summary>
internal sealed class EfficientHttpClient : IDisposable
{
#if USE_HTTP_CLIENT
private readonly Action<MemoryStream> _releaseContentBufferStreamForReuseDelegate;
private HttpClient _httpClient;
// We reuse the memory stream that is used to buffer the request payload.
// Our typical use case is non-async and non-concurrent. This re-use mechanism should be rubust in respect to being used concurrently,
// but we do not focus on that case. The last released buffer always wins.
private MemoryStream _reusableContentBufferStream = null;
public EfficientHttpClient()
{
_httpClient = new HttpClient();
_releaseContentBufferStreamForReuseDelegate = ReleaseContentBufferStreamForReuse;
}
public void Dispose()
{
HttpClient httpClient = Interlocked.Exchange(ref _httpClient, null);
if (httpClient != null)
{
httpClient.Dispose();
}
}
public EfficientHttpClient.MultipartFormPostRequest CreateNewMultipartFormPostRequest(string url)
{
HttpClient httpClient = _httpClient;
if (httpClient == null)
{
throw new ObjectDisposedException($"This {nameof(EfficientHttpClient)} has been disposed.");
}
MemoryStream reusableContentBufferStream = Interlocked.Exchange(ref _reusableContentBufferStream, null);
return new MultipartFormPostRequest(httpClient, url, reusableContentBufferStream, _releaseContentBufferStreamForReuseDelegate);
}
private void ReleaseContentBufferStreamForReuse(MemoryStream contentBufferStreamToReuse)
{
Interlocked.Exchange(ref _reusableContentBufferStream, contentBufferStreamToReuse);
}
#else
private static int _isGlobalInitPerformed = 0;
public EfficientHttpClient()
{
int wasGlobalInitPerformed = Interlocked.Exchange(ref _isGlobalInitPerformed, 1);
if (wasGlobalInitPerformed == 0)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
}
public void Dispose()
{
}
public EfficientHttpClient.MultipartFormPostRequest CreateNewMultipartFormPostRequest(string url)
{
return new MultipartFormPostRequest(WebRequest.CreateHttp(url));
}
#endif
public struct Response
{
public Response(int statusCode, string statusCodeString, string payload, Exception error)
{
this.StatusCode = statusCode;
this.StatusCodeString = statusCodeString;
this.Payload = payload;
this.Error = error;
}
public int StatusCode { get; }
public string StatusCodeString { get; }
public string Payload { get; }
public Exception Error { get; }
}
public class MultipartFormPostRequest
{
private const string DocumentTextEncodingName = "utf-8";
private static readonly Encoding BoundaryEncoding = Encoding.ASCII;
private static readonly Encoding DocumentTextEncoding = Encoding.UTF8;
private static readonly byte[] PlainTextContentTypeBytes = DocumentTextEncoding.GetBytes(
$"Content-Type: text/plain; charset={DocumentTextEncodingName}\r\n\r\n");
private static readonly byte[] PlainTextContentDispositionBytes1 = DocumentTextEncoding.GetBytes(
"Content-Disposition: form-data; name=\"");
private static readonly byte[] PlainTextContentDispositionBytes2 = DocumentTextEncoding.GetBytes(
"\"\r\n");
private static readonly byte[] OctetStreamContentTypeBytes = DocumentTextEncoding.GetBytes(
"Content-Type: application/octet-stream\r\n\r\n");
private static readonly byte[] OctetStreamContentDispositionBytes1 = DocumentTextEncoding.GetBytes(
"Content-Disposition: form-data; name=\"");
private static readonly byte[] OctetStreamContentDispositionBytes2 = DocumentTextEncoding.GetBytes(
"\"; filename=\"");
private static readonly byte[] OctetStreamContentDispositionBytes3 = DocumentTextEncoding.GetBytes(
"\"\r\n");
#if USE_HTTP_CLIENT
private readonly string _url;
private readonly Action<MemoryStream> _releaseContentBufferStreamForReuseDelegate;
private HttpClient _httpPoster;
#else
private HttpWebRequest _httpPoster;
#endif
private Stream _content;
private List<KeyValuePair<string, string>> _customHeaders;
private string _boundary;
private byte[] _boundaryBytes;
private byte[] _finalBoundaryBytes;
#if USE_HTTP_CLIENT
public MultipartFormPostRequest(HttpClient httpPoster, string url, MemoryStream reuseableContent, Action<MemoryStream> releaseReuseableContent)
{
Validate.NotNull(httpPoster, nameof(httpPoster));
Validate.NotNull(releaseReuseableContent, nameof(releaseReuseableContent));
_httpPoster = httpPoster;
_url = url;
_releaseContentBufferStreamForReuseDelegate = releaseReuseableContent;
if (reuseableContent != null)
{
reuseableContent.Position = 0;
_content = reuseableContent;
}
else if (reuseableContent == null)
{
_content = new MemoryStream();
}
InitHttpPosterAgnosticData();
}
#else
public MultipartFormPostRequest(HttpWebRequest httpPoster)
{
Validate.NotNull(httpPoster, nameof(httpPoster));
_httpPoster = httpPoster;
_httpPoster.Method = "POST";
_httpPoster.KeepAlive = true;
_content = _httpPoster.GetRequestStream();
InitHttpPosterAgnosticData();
}
#endif
public void AddHeader(string name, string value)
{
Validate.NotNullOrWhitespace(name, nameof(name));
Validate.NotNullOrWhitespace(value, nameof(value));
_customHeaders.Add(new KeyValuePair<string, string>(name, value));
}
public void AddPlainTextFormPart(string name, string content)
{
Validate.NotNullOrWhitespace(name, nameof(name));
Validate.NotNull(content, nameof(content));
Write(_boundaryBytes);
Write(PlainTextContentDispositionBytes1);
Write(DocumentTextEncoding.GetBytes(name));
Write(PlainTextContentDispositionBytes2);
Write(PlainTextContentTypeBytes);
Write(DocumentTextEncoding.GetBytes(content));
}
public Stream AddOctetStreamFormPart(string name, string filename)
{
Validate.NotNullOrWhitespace(name, nameof(name));
Validate.NotNull(filename, nameof(filename));
Write(_boundaryBytes);
Write(OctetStreamContentDispositionBytes1);
Write(DocumentTextEncoding.GetBytes(name));
Write(OctetStreamContentDispositionBytes2);
Write(DocumentTextEncoding.GetBytes(filename));
Write(OctetStreamContentDispositionBytes3);
Write(OctetStreamContentTypeBytes);
WriteOnlyStream octetStream = new WriteOnlyStream(_content, leaveUnderlyingStreamOpenWhenDisposed: true);
return octetStream;
}
#if USE_HTTP_CLIENT
public EfficientHttpClient.Response Send()
{
HttpClient httpClient = Interlocked.Exchange(ref _httpPoster, null);
if (httpClient == null)
{
throw new InvalidOperationException("This request has already been sent.");
}
Write(_finalBoundaryBytes);
_content.Position = 0;
int statusCode = 0;
string statusCodeString = null;
string payload = null;
Exception error = null;
MemoryStream contentBufferStream = null;
if (_content is MemoryStream memStream)
{
contentBufferStream = memStream;
}
HttpContent requestContent = (contentBufferStream != null && (contentBufferStream.Length < int.MaxValue - 1))
? (HttpContent)new ByteArrayContent(contentBufferStream.GetBuffer(), 0, (int)_content.Length)
: (HttpContent)new StreamContent(_content);
using (requestContent)
{
requestContent.Headers.Add("Content-Type", $"multipart/form-data; boundary=\"{_boundary}\"");
requestContent.Headers.ContentLength = _content.Length;
for (int i = 0; i < _customHeaders.Count; i++)
{
KeyValuePair<string, string> headerInfo = _customHeaders[i];
requestContent.Headers.Add(headerInfo.Key, headerInfo.Value);
}
using (var request = new HttpRequestMessage(HttpMethod.Post, _url))
{
request.Content = requestContent;
try
{
#if USE_HTTP_CLIENT_SEND_SYNC
HttpResponseMessage response = httpClient.Send(request);
#else
HttpResponseMessage response = httpClient.SendAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
#endif
using (response)
{
statusCode = (int)response.StatusCode;
statusCodeString = response.StatusCode.ToString();
#if USE_HTTP_CLIENT_SEND_SYNC
Stream payloadStream = response.Content.ReadAsStream();
#else
Stream payloadStream = response.Content.ReadAsStreamAsync().ConfigureAwait(false).GetAwaiter().GetResult();
#endif
using (payloadStream)
using (StreamReader payloadReader = new StreamReader(payloadStream))
{
payload = payloadReader.ReadToEnd();
}
}
}
catch (Exception ex)
{
error = ex;
}
}
}
// Return the allocated buffer for future reuse:
if (contentBufferStream != null && _releaseContentBufferStreamForReuseDelegate != null)
{
_content = null;
_releaseContentBufferStreamForReuseDelegate(contentBufferStream);
}
return new EfficientHttpClient.Response(statusCode, statusCodeString, payload, error);
}
#else
public EfficientHttpClient.Response Send()
{
HttpWebRequest httpPoster = Interlocked.Exchange(ref _httpPoster, null);
if (httpPoster == null)
{
throw new InvalidOperationException("This request has already been sent.");
}
Write(_finalBoundaryBytes);
httpPoster.ContentType = $"multipart/form-data; boundary=\"{_boundary}\"";
for (int i = 0; i < _customHeaders.Count; i++)
{
KeyValuePair<string, string> headerInfo = _customHeaders[i];
httpPoster.Headers.Add(headerInfo.Key, headerInfo.Value);
}
int statusCode = 0;
string statusCodeString = null;
string payload = null;
Exception error = null;
try
{
WebResponse response = httpPoster.GetResponse();
if (response != null && response is HttpWebResponse httpResponse)
{
statusCode = (int)httpResponse.StatusCode;
statusCodeString = httpResponse.StatusCode.ToString();
}
using (Stream payloadStream = response.GetResponseStream())
using (StreamReader payloadReader = new StreamReader(payloadStream))
{
payload = payloadReader.ReadToEnd();
}
}
catch (Exception ex)
{
error = ex;
}
return new EfficientHttpClient.Response(statusCode, statusCodeString, payload, error);
}
#endif
private void InitHttpPosterAgnosticData()
{
_customHeaders = new List<KeyValuePair<string, string>>(capacity: 5);
_boundary = Guid.NewGuid().ToString("N");
_boundaryBytes = BoundaryEncoding.GetBytes($"\r\n--{_boundary}\r\n");
_finalBoundaryBytes = BoundaryEncoding.GetBytes($"\r\n--{_boundary}--\r\n");
}
private void Write(byte[] bytes)
{
_content.Write(bytes, 0, bytes.Length);
}
} // class EfficientHttpClient.MultipartFormPostRequest
}
} | 42.428571 | 155 | 0.583732 | [
"Apache-2.0"
] | lucaspimentel/dd-trace-csharp | profiler/src/ProfilerEngine/Datadog.Profiler.Managed/Profiler/EfficientHttpClient.cs | 16,931 | C# |
using Microsoft.AspNetCore.DataProtection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Wobigtech.Companion.Shared
{
public class Encryptor
{
private readonly IDataProtector _protector;
public Encryptor(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector(GetType().FullName);
}
public string Encrypt<T>(T obj)
{
var json = JsonConvert.SerializeObject(obj);
return Encrypt(json);
}
public string Encrypt(string plaintext)
{
return _protector.Protect(plaintext);
}
public bool TryDecrypt<T>(string encryptedText, out T obj)
{
if (TryDecrypt(encryptedText, out var json))
{
obj = JsonConvert.DeserializeObject<T>(json);
return true;
}
obj = default;
return false;
}
public bool TryDecrypt(string encryptedText, out string decryptedText)
{
try
{
decryptedText = _protector.Unprotect(encryptedText);
return true;
}
catch (CryptographicException)
{
decryptedText = null;
return false;
}
}
}
}
| 23.048387 | 78 | 0.556333 | [
"MIT"
] | rwobig93/Wobigtech.Core | aspnet-core/src/Wobigtech.Core.Domain.Shared/Crypto/Encryptor.cs | 1,431 | 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/Audioclient.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
namespace TerraFX.Interop.Windows;
/// <include file='_AUDCLNT_BUFFERFLAGS.xml' path='doc/member[@name="_AUDCLNT_BUFFERFLAGS"]/*' />
[Flags]
public enum _AUDCLNT_BUFFERFLAGS
{
/// <include file='_AUDCLNT_BUFFERFLAGS.xml' path='doc/member[@name="_AUDCLNT_BUFFERFLAGS.AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY"]/*' />
AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY = 0x1,
/// <include file='_AUDCLNT_BUFFERFLAGS.xml' path='doc/member[@name="_AUDCLNT_BUFFERFLAGS.AUDCLNT_BUFFERFLAGS_SILENT"]/*' />
AUDCLNT_BUFFERFLAGS_SILENT = 0x2,
/// <include file='_AUDCLNT_BUFFERFLAGS.xml' path='doc/member[@name="_AUDCLNT_BUFFERFLAGS.AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR"]/*' />
AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR = 0x4,
}
| 44.73913 | 145 | 0.768707 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/Audioclient/_AUDCLNT_BUFFERFLAGS.cs | 1,031 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static Root;
using static core;
using api = memory;
/// <summary>
/// Captures and represents <see cref='ulong'/> pointer
/// </summary>
[ApiComplete]
public unsafe struct Ptr64 : IPtr<ulong>
{
public ulong* P;
public ref ulong this[ulong index]
{
[MethodImpl(Inline)]
get => ref seek(P,index);
}
public ref ulong this[long index]
{
[MethodImpl(Inline)]
get => ref seek(P,index);
}
[MethodImpl(Inline)]
public Ptr64(ulong* src)
=> P = src;
public uint Hash
{
[MethodImpl(Inline)]
get => (uint)P;
}
public readonly MemoryAddress Address
{
[MethodImpl(Inline)]
get => P;
}
[MethodImpl(Inline)]
public bool Equals(Ptr64 src)
=> P == src.P;
public override bool Equals(object src)
=> src is Ptr64 p && Equals(p);
public string Format()
=> Address.Format();
public override string ToString()
=> Format();
public override int GetHashCode()
=> (int)Hash;
[MethodImpl(Inline)]
public static ulong operator !(Ptr64 x)
=> *x.P;
[MethodImpl(Inline)]
public static Ptr64 operator ++(Ptr64 x)
=> api.next(x);
[MethodImpl(Inline)]
public static Ptr64 operator --(Ptr64 x)
=> api.prior(x);
[MethodImpl(Inline)]
public static implicit operator Ptr<ulong>(Ptr64 src)
=> new Ptr<ulong>(src);
[MethodImpl(Inline)]
public static implicit operator MemoryAddress(Ptr64 src)
=> src.Address;
[MethodImpl(Inline)]
public static implicit operator Ptr64(IntPtr src)
=> new Ptr64(src.ToPointer<ulong>());
[MethodImpl(Inline)]
public static explicit operator Ptr8(Ptr64 src)
=> new Ptr8((byte*)src.P);
[MethodImpl(Inline)]
public static explicit operator Ptr16(Ptr64 src)
=> new Ptr16((ushort*)src.P);
[MethodImpl(Inline)]
public static explicit operator Ptr32(Ptr64 src)
=> new Ptr32((uint*)src.P);
[MethodImpl(Inline)]
public static implicit operator Ptr64(ulong* src)
=> new Ptr64(src);
[MethodImpl(Inline)]
public static implicit operator ulong*(Ptr64 src)
=> src.P;
public ulong* Target
{
[MethodImpl(Inline)]
get => P;
}
}
} | 25.316239 | 79 | 0.494936 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/core/src/memory/models/Ptr64.cs | 2,962 | C# |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Glacier.Model
{
/// <summary>
/// Container for the parameters to the GetJobOutput operation.
/// <para>This operation downloads the output of the job you initiated using InitiateJob. Depending on the job type you specified when you
/// initiated the job, the output will be either the content of an archive or a vault inventory.</para> <para>A job ID will not expire for at
/// least 24 hours after Amazon Glacier completes the job. That is, you can download the job output within the 24 hours period after Amazon
/// Glacier completes the job.</para> <para>If the job output is large, then you can use the <c>Range</c> request header to retrieve a portion
/// of the output. This allows you to download the entire output in smaller chunks of bytes. For example, suppose you have 1 GB of job output
/// you want to download and you decide to download 128 MB chunks of data at a time, which is a total of eight Get Job Output requests. You use
/// the following process to download the job output:</para> <ol> <li> <para>Download a 128 MB chunk of output by specifying the appropriate
/// byte range using the <c>Range</c> header.</para> </li>
/// <li> <para>Along with the data, the response includes a checksum of the payload. You compute the checksum of the payload on the client and
/// compare it with the checksum you received in the response to ensure you received all the expected data.</para> </li>
/// <li> <para>Repeat steps 1 and 2 for all the eight 128 MB chunks of output data, each time specifying the appropriate byte range.</para>
/// </li>
/// <li> <para>After downloading all the parts of the job output, you have a list of eight checksum values. Compute the tree hash of these
/// values to find the checksum of the entire output. Using the Describe Job API, obtain job information of the job that provided you the
/// output. The response includes the checksum of the entire archive stored in Amazon Glacier. You compare this value with the checksum you
/// computed to ensure you have downloaded the entire archive content with no errors.</para> </li>
/// </ol> <para>An AWS account has full permission to perform all operations (actions). However, AWS Identity and Access Management (IAM) users
/// don't have any permissions by default. You must grant them explicit permission to perform specific actions. For more information, see <a
/// href="http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html" >Access Control Using AWS Identity and Access
/// Management (IAM)</a> .</para> <para>For conceptual information and the underlying REST API, go to <a
/// href="http://docs.aws.amazon.com/amazonglacier/latest/dev/vault-inventory.html" >Downloading a Vault Inventory</a> ,
///
/// <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/downloading-an-archive.html" >Downloading an Archive</a> ,
/// and <a href="http://docs.aws.amazon.com/amazonglacier/latest/dev/api-job-output-get.html" >Get Job Output </a> </para>
/// </summary>
public partial class GetJobOutputRequest : AmazonWebServiceRequest
{
private string accountId;
private string vaultName;
private string jobId;
private string range;
/// <summary>
/// The <c>AccountId</c> is the AWS Account ID. You can specify either the AWS Account ID or optionally a '-', in which case Amazon Glacier uses
/// the AWS Account ID associated with the credentials used to sign the request. If you specify your Account ID, do not include hyphens in it.
///
/// </summary>
public string AccountId
{
get { return this.accountId; }
set { this.accountId = value; }
}
// Check to see if AccountId property is set
internal bool IsSetAccountId()
{
return this.accountId != null;
}
/// <summary>
/// The name of the vault.
///
/// </summary>
public string VaultName
{
get { return this.vaultName; }
set { this.vaultName = value; }
}
// Check to see if VaultName property is set
internal bool IsSetVaultName()
{
return this.vaultName != null;
}
/// <summary>
/// The job ID whose data is downloaded.
///
/// </summary>
public string JobId
{
get { return this.jobId; }
set { this.jobId = value; }
}
// Check to see if JobId property is set
internal bool IsSetJobId()
{
return this.jobId != null;
}
/// <summary>
/// The range of bytes to retrieve from the output. For example, if you want to download the first 1,048,576 bytes, specify "Range:
/// bytes=0-1048575". By default, this operation downloads the entire output.
///
/// </summary>
public string Range
{
get { return this.range; }
set { this.range = value; }
}
// Check to see if Range property is set
internal bool IsSetRange()
{
return this.range != null;
}
}
}
| 47.170543 | 152 | 0.655711 | [
"Apache-2.0"
] | zz0733/aws-sdk-net | AWSSDK_DotNet35/Amazon.Glacier/Model/GetJobOutputRequest.cs | 6,085 | C# |
using System;
using System.Linq;
using NUnit.Framework;
namespace Reactol
{
[TestFixture]
public class ReactionTests
{
[Test]
public void HandlersCanNotBeNull()
{
Assert.Throws<ArgumentNullException>(() => new Reaction(null));
}
[Test]
public void HandlersReturnsExpectedResult()
{
var handler1 = new ReactionHandler(typeof (Int32), _ => Enumerable.Empty<object>());
var handler2 = new ReactionHandler(typeof (Int64), _ => Enumerable.Empty<object>());
var sut = new Reaction(new[]
{
handler1,
handler2
});
var result = sut.Handlers;
Assert.That(result, Is.EquivalentTo(new [] { handler1, handler2}));
}
[Test]
public void EmptyReturnsExpectedInstance()
{
var result = Reaction.Empty;
Assert.That(result, Is.InstanceOf<Reaction>());
Assert.That(result.Handlers, Is.Empty);
}
[Test]
public void EmptyReturnsSameInstance()
{
Assert.AreSame(Reaction.Empty, Reaction.Empty);
}
[Test]
public void ConcatReactionCanNotBeNull()
{
Assert.Throws<ArgumentNullException>(() => Reaction.Empty.Concat((Reaction)null));
}
[Test]
public void ConcatHandlerCanNotBeNull()
{
Assert.Throws<ArgumentNullException>(() => Reaction.Empty.Concat((ReactionHandler)null));
}
[Test]
public void ConcatHandlersCanNotBeNull()
{
Assert.Throws<ArgumentNullException>(() => Reaction.Empty.Concat((ReactionHandler[])null));
}
[Test]
public void ConcatReactionReturnsExpectedResult()
{
var handler1 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler2 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler3 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler4 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var projection = new Reaction(new[]
{
handler3,
handler4
});
var sut = new Reaction(new[]
{
handler1,
handler2
});
var result = sut.Concat(projection);
Assert.That(result.Handlers, Is.EquivalentTo(new[] { handler1, handler2, handler3, handler4 }));
}
[Test]
public void ConcatHandlerReturnsExpectedResult()
{
var handler1 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler2 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler3 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var sut = new Reaction(new[]
{
handler1,
handler2
});
var result = sut.Concat(handler3);
Assert.That(result.Handlers, Is.EquivalentTo(new[] { handler1, handler2, handler3 }));
}
[Test]
public void ConcatHandlersReturnsExpectedResult()
{
var handler1 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler2 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler3 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler4 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var sut = new Reaction(new[]
{
handler1,
handler2
});
var result = sut.Concat(new[]
{
handler3,
handler4
});
Assert.That(result.Handlers, Is.EquivalentTo(new[] { handler1, handler2, handler3, handler4 }));
}
//[Test]
//public void EmptyToBuilderReturnsExpectedResult()
//{
// var sut = Reaction.Empty;
// var result = sut.ToBuilder().Build().Handlers;
// Assert.That(result, Is.Empty);
//}
//[Test]
//public void ToBuilderReturnsExpectedResult()
//{
// var handler1 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
// var handler2 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
// var sut = new Reaction(new[]
// {
// handler1,
// handler2
// });
// var result = sut.ToBuilder().Build().Handlers;
// Assert.That(result, Is.EquivalentTo(new[]
// {
// handler1,
// handler2
// }));
//}
[Test]
public void ConversionOfNullToReactionHandlerArrayThrows()
{
Assert.Throws<ArgumentNullException>(() => { ReactionHandler[] _ = (Reaction)null; });
}
[Test]
public void ImplicitConversionToReactionHandlerArray()
{
var handler1 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler2 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handlers = new[]
{
handler1,
handler2
};
var sut = new Reaction(handlers);
ReactionHandler[] result = sut;
Assert.That(result, Is.EquivalentTo(handlers));
}
[Test]
public void ExplicitConversionToReactionHandlerArray()
{
var handler1 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handler2 = new ReactionHandler(typeof(object), _ => Enumerable.Empty<object>());
var handlers = new[]
{
handler1,
handler2
};
var sut = new Reaction(handlers);
var result = (ReactionHandler[])sut;
Assert.That(result, Is.EquivalentTo(handlers));
}
}
} | 31.929648 | 108 | 0.535883 | [
"BSD-3-Clause"
] | yreynhout/Reactol | src/Reactol.Tests/ReactionTests.cs | 6,356 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Security.Cryptography.X509Certificates;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the base class from which all signature commands
/// are derived.
/// </summary>
public abstract class SignatureCommandsBase : PSCmdlet
{
/// <summary>
/// Gets or sets the path to the file for which to get or set the
/// digital signature.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")]
public string[] FilePath
{
get
{
return _path;
}
set
{
_path = value;
}
}
private string[] _path;
/// <summary>
/// Gets or sets the literal path to the file for which to get or set the
/// digital signature.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _path;
}
set
{
_path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Gets or sets the digital signature to be written to
/// the output pipeline.
/// </summary>
protected Signature Signature
{
get { return _signature; }
set { _signature = value; }
}
private Signature _signature;
/// <summary>
/// Gets or sets the file type of the byte array containing the content with
/// digital signature.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] SourcePathOrExtension
{
get
{
return _sourcePathOrExtension;
}
set
{
_sourcePathOrExtension = value;
}
}
private string[] _sourcePathOrExtension;
/// <summary>
/// File contents as a byte array.
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public byte[] Content
{
get { return _content; }
set
{
_content = value;
}
}
private byte[] _content;
//
// name of this command
//
private readonly string _commandName;
/// <summary>
/// Initializes a new instance of the SignatureCommandsBase class,
/// using the given command name.
/// </summary>
/// <param name="name">
/// The name of the command.
/// </param>
protected SignatureCommandsBase(string name) : base()
{
_commandName = name;
}
//
// hide default ctor
//
private SignatureCommandsBase() : base() { }
/// <summary>
/// Processes records from the input pipeline.
/// For each input object, the command gets or
/// sets the digital signature on the object, and
/// and exports the object.
/// </summary>
protected override void ProcessRecord()
{
if (Content == null)
{
//
// this cannot happen as we have specified the Path
// property to be mandatory parameter
//
Dbg.Assert((FilePath != null) && (FilePath.Length > 0),
"GetSignatureCommand: Param binder did not bind path");
foreach (string p in FilePath)
{
Collection<string> paths = new Collection<string>();
// Expand wildcard characters
if (_isLiteralPath)
{
paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p));
}
else
{
try
{
foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p))
{
paths.Add(tempPath.ProviderPath);
}
}
catch (ItemNotFoundException)
{
WriteError(
SecurityUtils.CreateFileNotFoundErrorRecord(
SignatureCommands.FileNotFound,
"SignatureCommandsBaseFileNotFound", p));
}
}
if (paths.Count == 0)
continue;
bool foundFile = false;
foreach (string path in paths)
{
if (!System.IO.Directory.Exists(path))
{
foundFile = true;
string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path);
if (resolvedFilePath == null)
{
WriteError(SecurityUtils.CreateFileNotFoundErrorRecord(
SignatureCommands.FileNotFound,
"SignatureCommandsBaseFileNotFound",
path));
}
else
{
if ((Signature = PerformAction(resolvedFilePath)) != null)
{
WriteObject(Signature);
}
}
}
}
if (!foundFile)
{
WriteError(SecurityUtils.CreateFileNotFoundErrorRecord(
SignatureCommands.CannotRetrieveFromContainer,
"SignatureCommandsBaseCannotRetrieveFromContainer"));
}
}
}
else
{
foreach (string sourcePathOrExtension in SourcePathOrExtension)
{
if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null)
{
WriteObject(Signature);
}
}
}
}
/// <summary>
/// Performs the action (ie: get signature, or set signature)
/// on the specified file.
/// </summary>
/// <param name="filePath">
/// The name of the file on which to perform the action.
/// </param>
protected abstract Signature PerformAction(string filePath);
/// <summary>
/// Performs the action (ie: get signature, or set signature)
/// on the specified contents.
/// </summary>
/// <param name="fileName">
/// The filename used for type if content is specified.
/// </param>
/// <param name="content">
/// The file contents on which to perform the action.
/// </param>
protected abstract Signature PerformAction(string fileName, byte[] content);
}
/// <summary>
/// Defines the implementation of the 'get-AuthenticodeSignature' cmdlet.
/// This cmdlet extracts the digital signature from the given file.
/// </summary>
[Cmdlet(VerbsCommon.Get, "AuthenticodeSignature", DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096823")]
[OutputType(typeof(Signature))]
public sealed class GetAuthenticodeSignatureCommand : SignatureCommandsBase
{
/// <summary>
/// Initializes a new instance of the GetSignatureCommand class.
/// </summary>
public GetAuthenticodeSignatureCommand() : base("Get-AuthenticodeSignature") { }
/// <summary>
/// Gets the signature from the specified file.
/// </summary>
/// <param name="filePath">
/// The name of the file on which to perform the action.
/// </param>
/// <returns>
/// The signature on the specified file.
/// </returns>
protected override Signature PerformAction(string filePath)
{
return SignatureHelper.GetSignature(filePath, null);
}
/// <summary>
/// Gets the signature from the specified file contents.
/// </summary>
/// <param name="sourcePathOrExtension">The file type associated with the contents.</param>
/// <param name="content">
/// The contents of the file on which to perform the action.
/// </param>
/// <returns>
/// The signature on the specified file contents.
/// </returns>
protected override Signature PerformAction(string sourcePathOrExtension, byte[] content)
{
return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content));
}
}
/// <summary>
/// Defines the implementation of the 'set-AuthenticodeSignature' cmdlet.
/// This cmdlet sets the digital signature on a given file.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AuthenticodeSignature", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096919")]
[OutputType(typeof(Signature))]
public sealed class SetAuthenticodeSignatureCommand : SignatureCommandsBase
{
/// <summary>
/// Initializes a new instance of the SetAuthenticodeSignatureCommand class.
/// </summary>
public SetAuthenticodeSignatureCommand() : base("set-AuthenticodeSignature") { }
/// <summary>
/// Gets or sets the certificate with which to sign the
/// file.
/// </summary>
[Parameter(Position = 1, Mandatory = true)]
public X509Certificate2 Certificate
{
get
{
return _certificate;
}
set
{
_certificate = value;
}
}
private X509Certificate2 _certificate;
/// <summary>
/// Gets or sets the additional certificates to
/// include in the digital signature.
/// Use 'signer' to include only the signer's certificate.
/// Use 'notroot' to include all certificates in the certificate
/// chain, except for the root authority.
/// Use 'all' to include all certificates in the certificate chain.
///
/// Defaults to 'notroot'.
/// </summary>
[Parameter(Mandatory = false)]
[ValidateSet("signer", "notroot", "all")]
public string IncludeChain
{
get
{
return _includeChain;
}
set
{
_includeChain = value;
}
}
private string _includeChain = "notroot";
/// <summary>
/// Gets or sets the Url of the time stamping server.
/// The time stamping server certifies the exact time
/// that the certificate was added to the file.
/// </summary>
[Parameter(Mandatory = false)]
public string TimestampServer
{
get
{
return _timestampServer;
}
set
{
if (value == null)
{
value = string.Empty;
}
_timestampServer = value;
}
}
private string _timestampServer = string.Empty;
/// <summary>
/// Gets or sets the hash algorithm used for signing.
/// This string value must represent the name of a Cryptographic Algorithm
/// Identifier supported by Windows.
/// </summary>
[Parameter(Mandatory = false)]
public string HashAlgorithm
{
get
{
return _hashAlgorithm;
}
set
{
_hashAlgorithm = value;
}
}
private string _hashAlgorithm = null;
/// <summary>
/// Property that sets force parameter.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// Sets the digital signature on the specified file.
/// </summary>
/// <param name="filePath">
/// The name of the file on which to perform the action.
/// </param>
/// <returns>
/// The signature on the specified file.
/// </returns>
protected override Signature PerformAction(string filePath)
{
SigningOption option = GetSigningOption(IncludeChain);
if (Certificate == null)
{
throw PSTraceSource.NewArgumentNullException("certificate");
}
//
// if the cert is not good for signing, we cannot
// process any more files. Exit the command.
//
if (!SecuritySupport.CertIsGoodForSigning(Certificate))
{
Exception e = PSTraceSource.NewArgumentException(
"certificate",
SignatureCommands.CertNotGoodForSigning);
throw e;
}
if (!ShouldProcess(filePath))
return null;
FileInfo readOnlyFileInfo = null;
try
{
if (this.Force)
{
try
{
// remove readonly attributes on the file
FileInfo fInfo = new FileInfo(filePath);
if (fInfo != null)
{
// Save some disk write time by checking whether file is readonly..
if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// remember to reset the read-only attribute later
readOnlyFileInfo = fInfo;
// Make sure the file is not read only
fInfo.Attributes &= ~(FileAttributes.ReadOnly);
}
}
}
// These are the known exceptions for File.Load and StreamWriter.ctor
catch (ArgumentException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceArgumentException",
ErrorCategory.WriteError,
filePath
);
WriteError(er);
return null;
}
catch (IOException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceIOException",
ErrorCategory.WriteError,
filePath
);
WriteError(er);
return null;
}
catch (UnauthorizedAccessException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceUnauthorizedAccessException",
ErrorCategory.PermissionDenied,
filePath
);
WriteError(er);
return null;
}
catch (NotSupportedException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceNotSupportedException",
ErrorCategory.WriteError,
filePath
);
WriteError(er);
return null;
}
catch (System.Security.SecurityException e)
{
ErrorRecord er = new ErrorRecord(
e,
"ForceSecurityException",
ErrorCategory.PermissionDenied,
filePath
);
WriteError(er);
return null;
}
}
//
// ProcessRecord() code in base class has already
// ascertained that filePath really represents an existing
// file. Thus we can safely call GetFileSize() below.
//
if (SecurityUtils.GetFileSize(filePath) < 4)
{
// Note that the message param comes first
string message = string.Format(
System.Globalization.CultureInfo.CurrentCulture,
UtilsStrings.FileSmallerThan4Bytes, filePath);
PSArgumentException e = new PSArgumentException(message, nameof(filePath));
ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord(
e,
"SignatureCommandsBaseFileSmallerThan4Bytes"
);
WriteError(er);
return null;
}
return SignatureHelper.SignFile(option,
filePath,
Certificate,
TimestampServer,
_hashAlgorithm);
}
finally
{
// reset the read-only attribute
if (readOnlyFileInfo != null)
{
readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly;
}
}
}
/// <summary>
/// Not implemented.
/// </summary>
protected override Signature PerformAction(string sourcePathOrExtension, byte[] content)
{
throw new NotImplementedException();
}
private struct SigningOptionInfo
{
internal SigningOption option;
internal string optionName;
internal SigningOptionInfo(SigningOption o, string n)
{
option = o;
optionName = n;
}
}
/// <summary>
/// Association between SigningOption.* values and the
/// corresponding string names.
/// </summary>
private static readonly SigningOptionInfo[] s_sigOptionInfo =
{
new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"),
new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"),
new SigningOptionInfo(SigningOption.AddFullCertificateChain, "all")
};
/// <summary>
/// Get SigningOption value corresponding to a string name.
/// </summary>
/// <param name="optionName">Name of option.</param>
/// <returns>SigningOption.</returns>
private static SigningOption GetSigningOption(string optionName)
{
foreach (SigningOptionInfo si in s_sigOptionInfo)
{
if (string.Equals(optionName, si.optionName,
StringComparison.OrdinalIgnoreCase))
{
return si.option;
}
}
return SigningOption.AddFullCertificateChainExceptRoot;
}
}
}
| 34.249603 | 151 | 0.479181 | [
"MIT"
] | AML-MAR5-MDH-sudo/PowerShell | src/Microsoft.PowerShell.Security/security/SignatureCommands.cs | 21,543 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.