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("CurrencyConverterBook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CurrencyConverterBook")]
[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("86fd1a3f-4a88-43e5-b2db-3e70a96b6753")]
// 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.108108 | 84 | 0.751064 | [
"MIT"
] | Radostta/Programming-Basics-And-Fundamentals-SoftUni | CSharpBookExcercises/CurrencyConverterBook/Properties/AssemblyInfo.cs | 1,413 | C# |
namespace FluentValidation.WebApi
{
using System.Collections.Generic;
using System.Web.Http.Metadata;
using System.Web.Http.Validation;
using Internal;
using Validators;
internal class EmailFluentValidationPropertyValidator : FluentValidationPropertyValidator {
private IEmailValidator EmailValidator {
get { return (IEmailValidator)Validator; }
}
public EmailFluentValidationPropertyValidator(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, PropertyRule rule, IPropertyValidator validator) : base(metadata, validatorProviders, rule, validator) {
ShouldValidate=false;
}
}
} | 36 | 233 | 0.796296 | [
"Apache-2.0"
] | slgal/FluentValidation | src/FluentValidation.WebApi/PropertyValidatorAdapters/EmailFluentValidationPropertyValidator.cs | 650 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace ShelterClient
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 23.64 | 73 | 0.715736 | [
"MIT"
] | TJEverett/Shelter_Client | ShelterClient/Program.cs | 593 | 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 CPSC_481_Trailexplorers.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "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>
/// Returns the cached ResourceManager instance used by this class.
/// </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("CPSC_481_Trailexplorers.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.930556 | 189 | 0.606493 | [
"MIT"
] | agarc657/CPSC481 | CPSC_481_Trailexplorers/Properties/Resources.Designer.cs | 2,805 | C# |
using System.Collections.Generic;
using UnityEngine;
public class QuestController : Singleton<QuestController>
{
private List<Quest> activeQuests;
private List<Quest> completedQuests;
private QuestUI questUI;
private CharacterProps playerProps;
private LevelController levelController;
public GameObject NPCs;
public delegate void OnQuestChange();
public OnQuestChange onQuestChangeCallback;
public override void Awake()
{
base.Awake();
activeQuests = new List<Quest>();
completedQuests = new List<Quest>();
}
private void Start()
{
questUI = QuestUI.Instance;
playerProps = PlayerManager.Instance.player.GetComponent<CharacterProps>();
levelController = this.GetComponent<LevelController>();
if (SaveSystem.playerData == null)
{
ResetAllQuests();
}
}
public List<Quest> GetQuests()
{
return activeQuests;
}
public bool QuestAlreadyActive(Quest quest)
{
return activeQuests.Contains(quest);
}
public void SendProgressForQuest(string nameOfTarget)
{
foreach(Quest quest in activeQuests)
{
var goal = quest.goal.GetCurrentChoice();
if (goal.target.Equals(nameOfTarget))
{
goal.progress++;
if (goal.progress >= goal.quantity)
{
goal.progress = goal.quantity;
goal.done = true;
}
if (goal.options.Count == 1 && goal.done)
{
goal.choice = goal.options[0];
}
}
}
}
private QuestGiver FindGiver(string name)
{
foreach (Transform npc in NPCs.transform)
{
CharacterProps props = npc.gameObject.GetComponent<CharacterProps>();
if (props.name.Equals(name))
{
var questGiver = npc.gameObject.GetComponent<QuestGiver>();
return questGiver;
}
}
return null;
}
public void LoadToGiver(Quest quest)
{
if (quest.giver == null)
{
return;
}
var giver = FindGiver(quest.giver);
giver.LoadQuest(quest);
}
private void ClearGiver(Quest quest)
{
if (quest == null || quest.giver == null)
{
return;
}
var giver = FindGiver(quest.giver);
giver.LoadQuest(null);
}
public void AddQuest(Quest quest)
{
if (activeQuests.Contains(quest))
{
return;
}
activeQuests.Add(quest);
onQuestChangeCallback.Invoke();
}
public void AddQuests(Quest[] quests)
{
for(int i = 0; i < quests.Length; i++)
{
AddQuest(quests[i]);
}
}
public void CompleteQuest(Quest quest)
{
if(completedQuests.Contains(quest))
{
return;
}
levelController.AddExp(quest.reward.exp);
playerProps.coins += quest.reward.coins;
if (quest.reward.item != null)
{
PlayerManager.Instance.inventory.AddItem(quest.reward.item);
}
activeQuests.Remove(quest);
completedQuests.Add(quest);
var nextQuest = quest.GetNextQuest();
if (nextQuest != null)
{
if (nextQuest.done)
{
CompleteQuest(nextQuest);
return;
}
LoadToGiver(nextQuest);
}
else
{
ClearGiver(quest);
}
questUI.ClearPanel();
onQuestChangeCallback.Invoke();
}
public void AbortQuest(Quest quest)
{
activeQuests.Remove(quest);
quest.Reset();
onQuestChangeCallback.Invoke();
}
public void ResetAllQuests()
{
Quest[] quests = Resources.LoadAll<Quest>("Quests");
foreach(Quest quest in quests)
{
quest.Reset();
}
}
}
| 23.11828 | 84 | 0.51093 | [
"MIT"
] | gdemirev01/Avija | Assets/Scripts/Quests/QuestController.cs | 4,302 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Jarvis.TypeScriptGenerator.Builders;
using Newtonsoft.Json;
namespace Jarvis.TypeScriptGenerator
{
internal class Runner
{
private const string TsgeneratorJson = "tsgenerator.json";
private static IDictionary<string, Assembly> _assembliesCache = new Dictionary<string, Assembly>();
private TypeScriptGeneratorOptions _options;
public Runner()
{
var workingFolder = AppDomain.CurrentDomain.BaseDirectory;
var tsGeneratorJson = Path.Combine(workingFolder, TsgeneratorJson);
var text = File.ReadAllText(tsGeneratorJson);
_options = JsonConvert.DeserializeObject<TypeScriptGeneratorOptions>(text);
}
private Type[] LoadControllers(string pathToAssembly)
{
var assembly = LoadAssemblyFromPath(pathToAssembly);
var allClasses = assembly.GetTypes().Where(x => !x.IsAbstract && x.IsClass).ToArray();
// check fully qualified interface as a string to avoid webapi version mismatch
var controllers = allClasses.Where(x =>
x.GetInterfaces().Any(y => y.FullName != null && y.FullName.EndsWith("IHttpController"))
).ToArray();
return controllers;
}
private void DumpError(Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
public void Run()
{
var folder = Path.GetDirectoryName(_options.Assemblies.First());
var dlls = Directory.GetFiles(folder, "*.dll");
foreach (var dll in dlls)
{
LoadAssemblyFromPath(dll);
}
AppDomain currentDomain = AppDomain.CurrentDomain;
ResolveEventHandler handler = (sender, args) => LoadAssembly(
new AssemblyName(args.Name), _options.Assemblies.First()
);
currentDomain.AssemblyResolve += handler;
foreach (var pathToAssembly in _options.Assemblies)
{
ProcessAssembly(pathToAssembly, _options);
}
currentDomain.AssemblyResolve -= handler;
}
private Assembly LoadAssemblyFromName(AssemblyName assemblyName)
{
var fullName = assemblyName.FullName;
if (_assembliesCache.ContainsKey(fullName))
return _assembliesCache[fullName];
try
{
Console.Write("...loading {0}", Path.GetFileName(assemblyName.Name));
// var loaded = Assembly.ReflectionOnlyLoad(assemblyName.FullName);
var loaded = Assembly.Load(assemblyName.FullName);
_assembliesCache.Add(assemblyName.FullName, loaded);
Console.WriteLine("=> {0}", loaded.GetName());
return loaded;
}
catch (Exception ex)
{
Console.WriteLine("\nERROR: {0}\n", ex.Message);
}
return null;
}
private Assembly LoadAssemblyFromPath(string pathToDll)
{
if (_assembliesCache.ContainsKey(pathToDll))
return _assembliesCache[pathToDll];
if (!File.Exists(pathToDll))
{
return null;
}
try
{
Console.Write("...loading {0}", Path.GetFileName(pathToDll));
var raw = File.ReadAllBytes(pathToDll);
// var loaded = Assembly.ReflectionOnlyLoad(raw);
var loaded = Assembly.Load(raw);
_assembliesCache.Add(pathToDll, loaded);
Console.WriteLine("=> {0}", loaded.GetName());
return loaded;
}
catch (Exception ex)
{
Console.WriteLine("\nERROR: {0}\n", ex.Message);
}
return null;
}
private bool ProcessAssembly(string pathToAssembly, TypeScriptGeneratorOptions options)
{
if (!File.Exists(pathToAssembly))
{
Console.WriteLine("File {0} not found", pathToAssembly);
return false;
}
Console.WriteLine("Processing {0}", pathToAssembly);
try
{
var controllers = LoadControllers(pathToAssembly);
if (!controllers.Any())
{
Console.WriteLine("No controllers found");
return false;
}
foreach (var controller in controllers)
{
Console.WriteLine("...analyzing {0}", controller.FullName);
try
{
var builder = new TypeScriptBuilder(options.DestFolder, options.NgModule);
foreach (var reference in options.References)
{
builder.AddReference(reference);
}
var pathToTs = builder.GenerateClientApi(controller, options.Namespace, options.ApiRoot);
Console.WriteLine("...written {0}", pathToTs);
}
catch (Exception ex)
{
DumpError(ex);
}
}
}
catch (Exception ex)
{
if (ex is ReflectionTypeLoadException)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
foreach (var le in loaderExceptions)
{
DumpError(le);
}
}
else
{
DumpError(ex);
}
return false;
}
return true;
}
private Assembly LoadAssembly(AssemblyName assemblyName, string pathToAssembly)
{
var baseFolder = Path.GetDirectoryName(pathToAssembly);
var fname = Path.Combine(baseFolder, new AssemblyName(assemblyName.Name).Name + ".dll");
return LoadAssemblyFromPath(fname) ?? LoadAssemblyFromName(assemblyName);
}
}
} | 34.71123 | 113 | 0.526883 | [
"Apache-2.0"
] | ProximoSrl/Jarvis.TypeScriptGenerator | src/Jarvis.TypeScriptGenerator/Runner.cs | 6,491 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Core.Definitions;
using Microsoft.MixedReality.Toolkit.Core.Definitions.InputSystem;
using Microsoft.MixedReality.Toolkit.Core.Inspectors.Utilities;
using Microsoft.MixedReality.Toolkit.Core.Services;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Core.Inspectors.Profiles
{
[CustomEditor(typeof(MixedRealityInputActionsProfile))]
public class MixedRealityInputActionsProfileInspector : BaseMixedRealityProfileInspector
{
private static readonly GUIContent MinusButtonContent = new GUIContent("-", "Remove Action");
private static readonly GUIContent AddButtonContent = new GUIContent("+ Add a New Action", "Add New Action");
private static readonly GUIContent ActionContent = new GUIContent("Action", "The Name of the Action.");
private static readonly GUIContent AxisConstraintContent = new GUIContent("Axis Constraint", "Optional Axis Constraint for this input source.");
private static Vector2 scrollPosition = Vector2.zero;
private SerializedProperty inputActionList;
protected override void OnEnable()
{
base.OnEnable();
if (!MixedRealityInspectorUtility.CheckMixedRealityConfigured(false))
{
return;
}
inputActionList = serializedObject.FindProperty("inputActions");
}
public override void OnInspectorGUI()
{
MixedRealityInspectorUtility.RenderMixedRealityToolkitLogo();
if (!MixedRealityInspectorUtility.CheckMixedRealityConfigured())
{
return;
}
if (!MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled)
{
EditorGUILayout.HelpBox("No input system is enabled, or you need to specify the type in the main configuration profile.", MessageType.Error);
if (GUILayout.Button("Back to Configuration Profile"))
{
Selection.activeObject = MixedRealityToolkit.Instance.ActiveProfile;
}
return;
}
if (GUILayout.Button("Back to Input Profile"))
{
Selection.activeObject = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile;
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Input Actions", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("Input Actions are any/all actions your users will be able to make when interacting with your application.\n\n" +
"After defining all your actions, you can then wire up these actions to hardware sensors, controllers, and other input devices.", MessageType.Info);
(target as BaseMixedRealityProfile).CheckProfileLock();
serializedObject.Update();
RenderList(inputActionList);
serializedObject.ApplyModifiedProperties();
}
private static void RenderList(SerializedProperty list)
{
EditorGUILayout.Space();
GUILayout.BeginVertical();
if (GUILayout.Button(AddButtonContent, EditorStyles.miniButton))
{
list.arraySize += 1;
var inputAction = list.GetArrayElementAtIndex(list.arraySize - 1);
var inputActionId = inputAction.FindPropertyRelative("id");
var inputActionDescription = inputAction.FindPropertyRelative("description");
var inputActionConstraint = inputAction.FindPropertyRelative("axisConstraint");
inputActionConstraint.intValue = 0;
inputActionDescription.stringValue = $"New Action {inputActionId.intValue = list.arraySize}";
}
GUILayout.Space(12f);
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
var labelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 36f;
EditorGUILayout.LabelField(ActionContent, GUILayout.ExpandWidth(true));
EditorGUILayout.LabelField(AxisConstraintContent, GUILayout.Width(96f));
EditorGUILayout.LabelField(string.Empty, GUILayout.Width(24f));
EditorGUIUtility.labelWidth = labelWidth;
GUILayout.EndHorizontal();
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
for (int i = 0; i < list.arraySize; i++)
{
EditorGUILayout.BeginHorizontal();
var previousLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 64f;
SerializedProperty inputAction = list.GetArrayElementAtIndex(i);
SerializedProperty inputActionDescription = inputAction.FindPropertyRelative("description");
var inputActionConstraint = inputAction.FindPropertyRelative("axisConstraint");
EditorGUILayout.PropertyField(inputActionDescription, GUIContent.none);
EditorGUILayout.PropertyField(inputActionConstraint, GUIContent.none, GUILayout.Width(96f));
EditorGUIUtility.labelWidth = previousLabelWidth;
if (GUILayout.Button(MinusButtonContent, EditorStyles.miniButtonRight, GUILayout.Width(24f)))
{
list.DeleteArrayElementAtIndex(i);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
GUILayout.EndVertical();
GUILayout.EndVertical();
}
}
}
| 44.075758 | 184 | 0.654864 | [
"MIT"
] | StephenHodgson/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/_Core/Inspectors/Profiles/MixedRealityInputActionsProfileInspector.cs | 5,822 | 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("EMS.NIEM.Resource.NET")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ArdentMC")]
[assembly: AssemblyProduct("EMS.NIEM.Resource")]
[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("f4c85511-5255-4819-9a5c-4bb60aeb330e")]
// 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.351351 | 84 | 0.745595 | [
"Apache-2.0"
] | 1stResponder/em-serializers | NIEM/EMS.NIEM.Resource/Properties/AssemblyInfo.cs | 1,422 | C# |
////////////////////////////////////////////////////////////////////////////////
//EF Core Provider for LCPI OLE DB.
// IBProvider and Contributors. 26.03.2021.
using System;
using System.Diagnostics;
using System.Reflection;
namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D3.Expressions.Op2.Code{
////////////////////////////////////////////////////////////////////////////////
//using
using T_ARG1
=System.Nullable<System.Int64>;
using T_ARG2
=System.Nullable<System.Int32>;
using T_RESULT
=System.Nullable<System.Int64>;
////////////////////////////////////////////////////////////////////////////////
//class Op2_Code__Subtract___NullableInt64__NullableInt32
static class Op2_Code__Subtract___NullableInt64__NullableInt32
{
public static readonly System.Reflection.MethodInfo MethodInfo_V_V
=typeof(Op2_Code__Subtract___NullableInt64__NullableInt32)
.GetTypeInfo()
.GetDeclaredMethod(nameof(Exec_V_V));
//-----------------------------------------------------------------------
private static T_RESULT Exec_V_V(T_ARG1 a,T_ARG2 b)
{
if(!a.HasValue)
return null;
Debug.Assert(a.HasValue);
if(!b.HasValue)
return null;
Debug.Assert(b.HasValue);
return D0.Expressions.Op2.MasterCode.Op2_MasterCode__Subtract___Int64__Int64___checked.Exec
(a.Value,
b.Value);
}//Exec_V_V
};//class Op2_Code__Subtract___NullableInt64__NullableInt32
////////////////////////////////////////////////////////////////////////////////
}//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D3.Expressions.Op2.Code
| 32.75 | 130 | 0.591309 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Code/Provider/Source/Basement/EF/Dbms/Firebird/V03_0_0/Query/Local/D3/Expressions/Op2/Code/Subtract/NullableInt64/Op2_Code__Subtract___NullableInt64__NullableInt32.cs | 1,705 | 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 pinpoint-email-2018-07-26.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.PinpointEmail.Model
{
/// <summary>
/// An object that defines an Amazon Kinesis Data Firehose destination for email events.
/// You can use Amazon Kinesis Data Firehose to stream data to other services, such as
/// Amazon S3 and Amazon Redshift.
/// </summary>
public partial class KinesisFirehoseDestination
{
private string _deliveryStreamArn;
private string _iamRoleArn;
/// <summary>
/// Gets and sets the property DeliveryStreamArn.
/// <para>
/// The Amazon Resource Name (ARN) of the Amazon Kinesis Data Firehose stream that Amazon
/// Pinpoint sends email events to.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string DeliveryStreamArn
{
get { return this._deliveryStreamArn; }
set { this._deliveryStreamArn = value; }
}
// Check to see if DeliveryStreamArn property is set
internal bool IsSetDeliveryStreamArn()
{
return this._deliveryStreamArn != null;
}
/// <summary>
/// Gets and sets the property IamRoleArn.
/// <para>
/// The Amazon Resource Name (ARN) of the IAM role that Amazon Pinpoint uses when sending
/// email events to the Amazon Kinesis Data Firehose stream.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string IamRoleArn
{
get { return this._iamRoleArn; }
set { this._iamRoleArn = value; }
}
// Check to see if IamRoleArn property is set
internal bool IsSetIamRoleArn()
{
return this._iamRoleArn != null;
}
}
} | 32.567901 | 112 | 0.641395 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/PinpointEmail/Generated/Model/KinesisFirehoseDestination.cs | 2,638 | C# |
using System;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
using NUnit.Framework;
namespace NetTopologySuite.Tests.NUnit.Operation.Buffer
{
public class Test
{
[TestAttribute]
public void Buffer()
{
var geom =
new Polygon(
new LinearRing(new Coordinate[]
{
new Coordinate(0, 0), new Coordinate(0, 10), new Coordinate(10, 10),
new Coordinate(10, 0), new Coordinate(0, 0)
}));
Console.WriteLine(geom.AsText());
var geom2 = geom.Buffer(2d);
Console.WriteLine(geom2);
var geom3 = geom2.Buffer(-2);
geom3.Normalize();
Console.WriteLine(geom3);
}
}
} | 31.714286 | 111 | 0.472973 | [
"EPL-1.0"
] | ChaplinMarchais/NetTopologySuite | NetTopologySuite.Tests.NUnit/Operation/Buffer/Test.cs | 888 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
using Pulumi.Utilities;
namespace Pulumi.Yandex
{
public static class GetVpcSubnet
{
/// <summary>
/// Get information about a Yandex VPC subnet. For more information, see
/// [Yandex.Cloud VPC](https://cloud.yandex.com/docs/vpc/concepts/index).
///
/// ```csharp
/// using Pulumi;
/// using Yandex = Pulumi.Yandex;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var admin = Output.Create(Yandex.GetVpcSubnet.InvokeAsync(new Yandex.GetVpcSubnetArgs
/// {
/// SubnetId = "my-subnet-id",
/// }));
/// }
///
/// }
/// ```
///
/// This data source is used to define [VPC Subnets] that can be used by other resources.
/// </summary>
public static Task<GetVpcSubnetResult> InvokeAsync(GetVpcSubnetArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetVpcSubnetResult>("yandex:index/getVpcSubnet:getVpcSubnet", args ?? new GetVpcSubnetArgs(), options.WithVersion());
/// <summary>
/// Get information about a Yandex VPC subnet. For more information, see
/// [Yandex.Cloud VPC](https://cloud.yandex.com/docs/vpc/concepts/index).
///
/// ```csharp
/// using Pulumi;
/// using Yandex = Pulumi.Yandex;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var admin = Output.Create(Yandex.GetVpcSubnet.InvokeAsync(new Yandex.GetVpcSubnetArgs
/// {
/// SubnetId = "my-subnet-id",
/// }));
/// }
///
/// }
/// ```
///
/// This data source is used to define [VPC Subnets] that can be used by other resources.
/// </summary>
public static Output<GetVpcSubnetResult> Invoke(GetVpcSubnetInvokeArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetVpcSubnetResult>("yandex:index/getVpcSubnet:getVpcSubnet", args ?? new GetVpcSubnetInvokeArgs(), options.WithVersion());
}
public sealed class GetVpcSubnetArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Folder that the resource belongs to. If value is omitted, the default provider folder is used.
/// </summary>
[Input("folderId")]
public string? FolderId { get; set; }
/// <summary>
/// - Name of the subnet.
/// </summary>
[Input("name")]
public string? Name { get; set; }
/// <summary>
/// Subnet ID.
/// </summary>
[Input("subnetId")]
public string? SubnetId { get; set; }
public GetVpcSubnetArgs()
{
}
}
public sealed class GetVpcSubnetInvokeArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Folder that the resource belongs to. If value is omitted, the default provider folder is used.
/// </summary>
[Input("folderId")]
public Input<string>? FolderId { get; set; }
/// <summary>
/// - Name of the subnet.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Subnet ID.
/// </summary>
[Input("subnetId")]
public Input<string>? SubnetId { get; set; }
public GetVpcSubnetInvokeArgs()
{
}
}
[OutputType]
public sealed class GetVpcSubnetResult
{
/// <summary>
/// Creation timestamp of this subnet.
/// </summary>
public readonly string CreatedAt;
/// <summary>
/// Description of the subnet.
/// </summary>
public readonly string Description;
/// <summary>
/// Options for DHCP client. The structure is documented below.
/// </summary>
public readonly Outputs.GetVpcSubnetDhcpOptionsResult DhcpOptions;
public readonly string FolderId;
/// <summary>
/// The provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
/// <summary>
/// Labels to assign to this subnet.
/// </summary>
public readonly ImmutableDictionary<string, string> Labels;
public readonly string Name;
/// <summary>
/// ID of the network this subnet belongs to.
/// </summary>
public readonly string NetworkId;
/// <summary>
/// ID of the route table to assign to this subnet.
/// </summary>
public readonly string RouteTableId;
public readonly string SubnetId;
/// <summary>
/// The blocks of internal IPv4 addresses owned by this subnet.
/// </summary>
public readonly ImmutableArray<string> V4CidrBlocks;
/// <summary>
/// The blocks of internal IPv6 addresses owned by this subnet.
/// </summary>
public readonly ImmutableArray<string> V6CidrBlocks;
/// <summary>
/// Name of the availability zone for this subnet.
/// </summary>
public readonly string Zone;
[OutputConstructor]
private GetVpcSubnetResult(
string createdAt,
string description,
Outputs.GetVpcSubnetDhcpOptionsResult dhcpOptions,
string folderId,
string id,
ImmutableDictionary<string, string> labels,
string name,
string networkId,
string routeTableId,
string subnetId,
ImmutableArray<string> v4CidrBlocks,
ImmutableArray<string> v6CidrBlocks,
string zone)
{
CreatedAt = createdAt;
Description = description;
DhcpOptions = dhcpOptions;
FolderId = folderId;
Id = id;
Labels = labels;
Name = name;
NetworkId = networkId;
RouteTableId = routeTableId;
SubnetId = subnetId;
V4CidrBlocks = v4CidrBlocks;
V6CidrBlocks = v6CidrBlocks;
Zone = zone;
}
}
}
| 31.649289 | 172 | 0.549865 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-yandex | sdk/dotnet/GetVpcSubnet.cs | 6,678 | C# |
namespace NFugue.Patterns
{
public enum TokenType
{
Voice,
Layer,
Instrument,
Tempo,
KeySignature,
TimeSignature,
BarLine,
TrackTimeBookmark,
TrackTimeBookmarkRequested,
Lyric,
Marker,
Function,
Note,
Whitespace,
Atom,
UnknownToken
}
} | 17.045455 | 35 | 0.509333 | [
"Apache-2.0"
] | kurena-777/NFugue | src/NFugue/Patterns/TokenType.cs | 375 | C# |
using System;
using System.Drawing;
namespace TechEd.Demo.SolidPrinciples.Lsp.Principles.Entities
{
public class Car
{
private bool _hasFuel = true;
public Car(Color color)
{
Color = color;
}
public virtual void StartEngine()
{
if (!_hasFuel)
throw new OutOfFuelException("Can't start a car without gas in tank...");
IsEngineRunning = true;
}
public virtual void StopEngine()
{
IsEngineRunning = false;
}
public bool IsEngineRunning { get; private set; }
public Color Color { get; protected set; }
}
public class BrokenCar : Car
{
public BrokenCar(Color color) : base(color)
{
}
public override void StartEngine()
{
throw new NotImplementedException();
}
}
public class CrimeBossCar : Car
{
private readonly bool _boobyTrapped;
public CrimeBossCar(Color color, bool boobyTrap)
: base(color)
{
_boobyTrapped = boobyTrap;
}
public override void StartEngine()
{
if (_boobyTrapped)
throw new MetYourMakerException("Boom! You are dead!");
base.StartEngine();
}
}
public class Prius : Car
{
public Prius(Color color) : base(color)
{
}
public override void StartEngine()
{
}
public override void StopEngine()
{
}
}
public class StolenCar : Car
{
private bool _ignitionWiresStripped;
public StolenCar(Color color) : base(color)
{
}
public void StripIgnitionWires()
{
_ignitionWiresStripped = true;
}
public override void StartEngine()
{
if (!_ignitionWiresStripped) return;
base.StartEngine();
}
}
// http://www.dailymail.co.uk/sciencetech/article-2451931/Car-colour-heat-sensitive-paint-changes-depending-weather.html
public class PimpedCar : Car
{
private readonly Color _color;
public PimpedCar(Color color) : base(color)
{
_color = color;
}
public void SetTemperature(int temp)
{
if (temp > 20)
Color = _color;
else
Color = Color.Black;
}
}
public class OutOfFuelException : Exception
{
public OutOfFuelException(string message) : base(message)
{
}
}
public class MetYourMakerException : Exception
{
public MetYourMakerException(string message) : base(message)
{
}
}
}
| 21.389313 | 124 | 0.53212 | [
"MIT"
] | Inventum24/SOLID | TechEd.SolidPrinciples/TechEd.Demo.SolidPrinciples.Lsp.Principles/Entities/Car.cs | 2,804 | C# |
using System;
using CryptoApisLibrary.DataTypes;
using CryptoApisLibrary.ResponseTypes.Blockchains;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryptoApisLibrary.Tests.Blockchains.Transactions.SendAllAmountUsingPassword
{
[TestClass]
public abstract class BaseEthSimilarCoin : BaseTest
{
[Ignore] // todo: no funds for full testing
[TestMethod]
public void TestSimple()
{
var response = Manager.Blockchains.Transaction.SendAllAmountUsingPassword<CreateEthTransactionResponse>(
NetworkCoin, FromAddress, ToAddress, Password);
AssertNullErrorMessage(response);
Assert.IsFalse(string.IsNullOrEmpty(response.Payload.Hex), "'Hex' must not be null");
}
[TestMethod]
public void WrongFromAddress()
{
var fromAddress = "qw'e";
var response = Manager.Blockchains.Transaction.SendAllAmountUsingPassword<CreateEthTransactionResponse>(
NetworkCoin, fromAddress, ToAddress, Password);
AssertErrorMessage(response, $"{fromAddress} is not a valid Ethereum address");
}
[TestMethod]
public void WrongToAddress()
{
var toAddress = "qw'e";
var response = Manager.Blockchains.Transaction.SendAllAmountUsingPassword<CreateEthTransactionResponse>(
NetworkCoin, FromAddress, toAddress, Password);
AssertErrorMessage(response, $"There is no registry for address: {FromAddress}");
}
[TestMethod]
public void WrongPassword()
{
var password = "qw'e";
var response = Manager.Blockchains.Transaction.SendAllAmountUsingPassword<CreateEthTransactionResponse>(
NetworkCoin, FromAddress, ToAddress, password);
AssertErrorMessage(response, $"There is no registry for address: { FromAddress }");
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), "A FromAddress was inappropriately allowed.")]
public void NullFromAddress()
{
string fromAddress = null;
Manager.Blockchains.Transaction.SendAllAmountUsingPassword<CreateEthTransactionResponse>(
NetworkCoin, fromAddress, ToAddress, Password);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), "A ToAddress was inappropriately allowed.")]
public void NullToAddress()
{
string toAddress = null;
Manager.Blockchains.Transaction.SendAllAmountUsingPassword<CreateEthTransactionResponse>(
NetworkCoin, FromAddress, toAddress, Password);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), "A Password was inappropriately allowed.")]
public void NullPassword()
{
string password = null;
Manager.Blockchains.Transaction.SendAllAmountUsingPassword<CreateEthTransactionResponse>(
NetworkCoin, FromAddress, ToAddress, password);
}
protected abstract NetworkCoin NetworkCoin { get; }
protected abstract string FromAddress { get; }
protected abstract string ToAddress { get; }
private string Password { get; } = "123";
}
} | 39.164706 | 116 | 0.660859 | [
"MIT"
] | Crypto-APIs/.NET-Library | CryptoApisLibrary.Tests/Blockchains/Transactions/SendAllAmountUsingPassword/BaseEthSimilarCoin.cs | 3,331 | C# |
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
namespace uNvPipe
{
[RequireComponent(typeof(Renderer))]
public class uNvPipeDecodedTexture : MonoBehaviour
{
[SerializeField]
uNvPipeDecoder decoder = null;
Texture2D texture_;
CommandBuffer cb_;
void OnEnable()
{
Assert.IsNotNull(decoder, "Please set decoder.");
decoder.onDecoded.AddListener(OnDecoded);
texture_ = new Texture2D(decoder.width, decoder.height, TextureFormat.RGBA32, false, false);
var renderer = GetComponent<Renderer>();
renderer.material.mainTexture = texture_;
cb_ = new CommandBuffer();
cb_.name = "uNvPipeDecodedTexture" + decoder.id;
}
void OnDisable()
{
cb_.Dispose();
}
void OnDecoded(System.IntPtr ptr, int size)
{
var callback = Lib.GetTextureUpdateCallback();
if (callback == null) return;
cb_.IssuePluginCustomTextureUpdateV2(callback, texture_, (uint)decoder.id);
Graphics.ExecuteCommandBuffer(cb_);
cb_.Clear();
}
}
}
| 23.854167 | 101 | 0.638428 | [
"BSD-3-Clause"
] | Neos-Metaverse/uNvPipe | Assets/uNvPipe/Scripts/uNvPipeDecodedTexture.cs | 1,147 | C# |
using System;
using System.Collections.Generic;
namespace MobaFrame.SkillAction
{
public class SimpleSkillAction : BaseSkillAction
{
protected override bool doAction()
{
if (this.skillData == null)
{
return false;
}
string[] array = this.skillData.start_actions;
if (base.unit.StartActions != null)
{
array = base.unit.StartActions;
}
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
if (StringUtils.CheckValid(array[i]))
{
PerformAction performAction = ActionManager.PlayPerform(this.skillKey, array[i], base.unit, this.targetUnits, this.targetPosition, true, null);
performAction.OnDamageCallback = new Callback<BaseAction, List<Units>>(this.OnDamage);
performAction.OnDamageEndCallback = new Callback<BaseAction>(this.OnDamageEnd);
this.AddAction(performAction);
}
}
}
base.unit.StartActions = null;
return true;
}
protected override void OnSkillDamage(BaseSkillAction action, List<Units> targets)
{
this.AddAction(ActionManager.HitSkill(action.skillKey, base.unit, targets, true));
base.AddHighEff(action.skillKey, SkillPhrase.Hit, targets, this.targetPosition);
base.AddBuff(action.skillKey, SkillPhrase.Hit, targets);
base.OnSkillDamage(action, targets);
}
protected override void OnSkillEnd(BaseSkillAction action)
{
ActionManager.EndSkill(action.skillKey, base.unit, true);
base.OnSkillEnd(action);
}
}
}
| 29.666667 | 150 | 0.684732 | [
"MIT"
] | corefan/mobahero_src | MobaFrame.SkillAction/SimpleSkillAction.cs | 1,513 | C# |
using JTNE.Protocol.Attributes;
using JTNE.Protocol.Formatters.MessageBodyFormatters;
using System;
using System.Collections.Generic;
using System.Text;
namespace JTNE.Protocol.MessageBody
{
/// <summary>
/// 连续三次登入失败后,到下一次登入的时间间隔。有效值范围:1~240(表示1min~240min)
/// </summary>
[JTNEFormatter(typeof(JTNE_0x81_0x0C_Device_Formatter))]
public class JTNE_0x81_0x0C_Device: JTNE_0x81_Body_Device
{
public override byte ParamId { get; set; } = 0x0C;
/// <summary>
/// 数据 长度
/// </summary>
public override byte ParamLength { get; set; } = 1;
/// <summary>
/// 连续三次登入失败后,到下一次登入的时间间隔。有效值范围:1~240(表示1min~240min)
/// </summary>
public byte ParamValue { get; set; }
}
}
| 29.230769 | 61 | 0.644737 | [
"MIT"
] | SmallChi/GBNewEnergy | src/JTNE.Protocol/MessageBody/JTNE_0x81_0x0C_Device.cs | 898 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.AspNetCore.Components.WebView.WebView2;
using Microsoft.Web.WebView2.Core;
namespace Microsoft.AspNetCore.Components.WebView.Wpf
{
internal class WpfCoreWebView2WebResourceRequestedEventArgsWrapper : ICoreWebView2WebResourceRequestedEventArgsWrapper
{
private readonly CoreWebView2Environment _environment;
private readonly CoreWebView2WebResourceRequestedEventArgs _webResourceRequestedEventArgs;
public WpfCoreWebView2WebResourceRequestedEventArgsWrapper(CoreWebView2Environment environment, CoreWebView2WebResourceRequestedEventArgs webResourceRequestedEventArgs)
{
_environment = environment;
_webResourceRequestedEventArgs = webResourceRequestedEventArgs;
Request = new WpfCoreWebView2WebResourceRequestWrapper(webResourceRequestedEventArgs);
ResourceContext = (CoreWebView2WebResourceContextWrapper)webResourceRequestedEventArgs.ResourceContext;
}
public ICoreWebView2WebResourceRequestWrapper Request { get; }
public CoreWebView2WebResourceContextWrapper ResourceContext { get; }
public void SetResponse(Stream content, int statusCode, string statusMessage, string headerString)
{
_webResourceRequestedEventArgs.Response = _environment.CreateWebResourceResponse(content, statusCode, statusMessage, headerString);
}
}
}
| 43.294118 | 170 | 0.849185 | [
"MIT"
] | 41396/maui | src/BlazorWebView/src/Wpf/WpfCoreWebView2WebResourceRequestedEventArgsWrapper.cs | 1,474 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Logging.EventSource;
using Newtonsoft.Json;
using Xunit;
using Microsoft.Extensions.DependencyInjection;
// AddEventSourceLogger(ILoggerProvider) overload is obsolete
#pragma warning disable CS0618 // Type or member is obsolete
namespace Microsoft.Extensions.Logging.Test
{
public abstract class EventSourceLoggerTest: IDisposable
{
public class EventSourceLoggerFactoryTest: EventSourceLoggerTest
{
private LoggerFactory _factory;
protected override ILoggerFactory CreateLoggerFactory()
{
_factory = new LoggerFactory();
_factory.AddEventSourceLogger();
return _factory;
}
public override void Dispose()
{
_factory.Dispose();
}
}
public class EventSourceLoggerBuilderTest : EventSourceLoggerTest
{
private ServiceProvider _serviceProvider;
protected override ILoggerFactory CreateLoggerFactory()
{
_serviceProvider = new ServiceCollection()
.AddLogging(builder => builder.AddEventSourceLogger())
.BuildServiceProvider();
return _serviceProvider.GetRequiredService<ILoggerFactory>();
}
public override void Dispose()
{
_serviceProvider?.Dispose();
}
}
protected abstract ILoggerFactory CreateLoggerFactory();
public abstract void Dispose();
[Fact]
public void IsEnabledReturnsCorrectValue()
{
using (var testListener = new TestEventListener())
{
var loggerFactory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = null;
listenerSettings.Level = EventLevel.Warning;
testListener.EnableEvents(listenerSettings);
var logger = loggerFactory.CreateLogger("Logger1");
Assert.False(logger.IsEnabled(LogLevel.None));
Assert.True(logger.IsEnabled(LogLevel.Critical));
Assert.True(logger.IsEnabled(LogLevel.Error));
Assert.True(logger.IsEnabled(LogLevel.Warning));
Assert.False(logger.IsEnabled(LogLevel.Information));
Assert.False(logger.IsEnabled(LogLevel.Debug));
Assert.False(logger.IsEnabled(LogLevel.Trace));
}
}
[Fact]
public void Logs_AsExpected_WithDefaults()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = (EventKeywords)(-1);
listenerSettings.FilterSpec = null;
listenerSettings.Level = default(EventLevel);
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
// Use testListener.DumpEvents as necessary to examine what exactly the listener received
VerifyEvents(testListener,
"E1FM", "E1MSG", "E1JS",
// Second event is omitted because default LogLevel == Debug
"E3FM", "E3MSG", "E3JS",
"OuterScopeJsonStart",
"E4FM", "E4MSG", "E4JS",
"E5FM", "E5MSG", "E5JS",
"InnerScopeJsonStart",
"E6FM", "E6MSG", "E6JS",
"InnerScopeJsonStop",
"E7FM", "E7MSG", "E7JS",
"OuterScopeJsonStop",
"E8FM", "E8MSG", "E8JS");
}
}
[Fact]
public void Logs_Nothing_IfNotEnabled()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
LogStuff(factory);
VerifyEvents(testListener); // No verifiers = 0 events expected
}
}
[Fact]
public void Logs_OnlyFormattedMessage_IfKeywordSet()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.FormattedMessage;
listenerSettings.FilterSpec = null;
listenerSettings.Level = EventLevel.Verbose;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E1FM",
// Second event is omitted because default LogLevel == Debug
"E3FM",
"OuterScopeStart",
"E4FM",
"E5FM",
"InnerScopeStart",
"E6FM",
"InnerScopeStop",
"E7FM",
"OuterScopeStop",
"E8FM");
}
}
[Fact]
public void Logs_OnlyJson_IfKeywordSet()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = null;
listenerSettings.Level = EventLevel.Verbose;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E1JS",
// Second event is omitted because default LogLevel == Debug
"E3JS",
"OuterScopeJsonStart",
"E4JS",
"E5JS",
"InnerScopeJsonStart",
"E6JS",
"InnerScopeJsonStop",
"E7JS",
"OuterScopeJsonStop",
"E8JS");
}
}
[Fact]
public void Logs_OnlyMessage_IfKeywordSet()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.Message;
listenerSettings.FilterSpec = null;
listenerSettings.Level = EventLevel.Verbose;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E1MSG",
// Second event is omitted because default LogLevel == Debug
"E3MSG",
"OuterScopeStart",
"E4MSG",
"E5MSG",
"InnerScopeStart",
"E6MSG",
"InnerScopeStop",
"E7MSG",
"OuterScopeStop",
"E8MSG");
}
}
[Fact]
public void Logs_AllEvents_IfTraceSet()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = "Logger1:Trace;Logger2:Trace;Logger3:Trace";
listenerSettings.Level = EventLevel.Verbose;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E1JS",
"E2JS",
"E3JS",
"OuterScopeJsonStart",
"E4JS",
"E5JS",
"InnerScopeJsonStart",
"E6JS",
"InnerScopeJsonStop",
"E7JS",
"OuterScopeJsonStop",
"E8JS");
}
}
[Fact]
public void Logs_AsExpected_AtErrorLevel()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = null;
listenerSettings.Level = EventLevel.Error;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"OuterScopeJsonStart",
"E4JS",
"E5JS",
"InnerScopeJsonStart",
"InnerScopeJsonStop",
"OuterScopeJsonStop");
}
}
[Fact]
public void Logs_AsExpected_AtWarningLevel()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = null;
listenerSettings.Level = EventLevel.Warning;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"OuterScopeJsonStart",
"E4JS",
"E5JS",
"InnerScopeJsonStart",
"E6JS",
"InnerScopeJsonStop",
"OuterScopeJsonStop",
"E8JS");
}
}
[Fact]
public void Logs_AsExpected_WithSingleLoggerSpec()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = "Logger2";
listenerSettings.Level = EventLevel.Verbose;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E5JS",
"E6JS",
"E8JS");
}
}
[Fact]
public void Logs_AsExpected_WithSingleLoggerSpecWithVerbosity()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = "Logger2:Error";
listenerSettings.Level = EventLevel.Error;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E5JS");
}
}
[Fact]
public void Logs_AsExpected_AfterSettingsReload()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = "Logger2:Error";
listenerSettings.Level = EventLevel.Error;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E5JS");
listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = "Logger1:Error";
listenerSettings.Level = EventLevel.Error;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"E5JS",
"OuterScopeJsonStart",
"E4JS",
"OuterScopeJsonStop");
}
}
[Fact]
public void Logs_AsExpected_WithComplexLoggerSpec()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = "Logger1:Warning;Logger2:Error";
listenerSettings.Level = EventLevel.Verbose;
testListener.EnableEvents(listenerSettings);
LogStuff(factory);
VerifyEvents(testListener,
"OuterScopeJsonStart",
"E4JS",
"E5JS",
"OuterScopeJsonStop");
}
}
[Fact]
public void Logs_Nothing_AfterDispose()
{
using (var testListener = new TestEventListener())
{
var factory = CreateLoggerFactory();
var listenerSettings = new TestEventListener.ListenerSettings();
listenerSettings.Keywords = LoggingEventSource.Keywords.JsonMessage;
listenerSettings.FilterSpec = null;
listenerSettings.Level = EventLevel.Verbose;
testListener.EnableEvents(listenerSettings);
var logger = factory.CreateLogger("Logger1");
Dispose();
logger.LogDebug(new EventId(1), "Logger1 Event1 Debug {intParam}", 1);
VerifyEvents(testListener);
}
}
private void LogStuff(ILoggerFactory factory)
{
var logger1 = factory.CreateLogger("Logger1");
var logger2 = factory.CreateLogger("Logger2");
var logger3 = factory.CreateLogger("Logger3");
logger1.LogDebug(new EventId(1), "Logger1 Event1 Debug {intParam}", 1);
logger2.LogTrace(new EventId(2), "Logger2 Event2 Trace {doubleParam} {timeParam} {doubleParam2}", DoubleParam1, TimeParam.ToString("O"), DoubleParam2);
logger3.LogInformation(new EventId(3), "Logger3 Event3 Information {string1Param} {string2Param} {string3Param}", "foo", "bar", "baz");
using (logger1.BeginScope("Outer scope {stringParam} {intParam} {doubleParam}", "scoped foo", 13, DoubleParam1))
{
logger1.LogError(new EventId(4), "Logger1 Event4 Error {stringParam} {guidParam}", "foo", GuidParam);
logger2.LogCritical(new EventId(5), new Exception("oops", new Exception("inner oops")),
"Logger2 Event5 Critical {stringParam} {int1Param} {int2Param}", "bar", 23, 45);
using (logger3.BeginScope("Inner scope {timeParam} {guidParam}", TimeParam, GuidParam))
{
logger2.LogWarning(new EventId(6), "Logger2 Event6 Warning NoParams");
}
logger3.LogInformation(new EventId(7), "Logger3 Event7 Information {stringParam} {doubleParam} {intParam}", "inner scope closed", DoubleParam2, 37);
}
logger2.LogWarning(new EventId(8), "Logger2 Event8 Warning {stringParam} {timeParam}", "Outer scope closed", TimeParam.ToString("O"));
}
private static void VerifyEvents(TestEventListener eventListener, params string[] verifierIDs)
{
Assert.Collection(eventListener.Events, verifierIDs.Select(id => EventVerifiers[id]).ToArray());
}
private static void VerifySingleEvent(string eventJson, string loggerName, string eventName, int? eventId, LogLevel? level, params string[] fragments)
{
Assert.True(eventJson.Contains(@"""__EVENT_NAME"":""" + eventName + @""""), $"Event name does not match. Expected {eventName}, event data is '{eventJson}'");
Assert.True(eventJson.Contains(@"""LoggerName"":""" + loggerName + @""""), $"Logger name does not match. Expected {loggerName}, event data is '{eventJson}'");
if (level.HasValue)
{
Assert.True(eventJson.Contains(@"""Level"":" + ((int)level.Value).ToString()), $"Log level does not match. Expected level {((int)level.Value).ToString()}, event data is '{eventJson}'");
}
if (eventId.HasValue)
{
Assert.True(eventJson.Contains(@"""EventId"":""" + eventId.Value.ToString()), $"Event id does not match. Expected id {eventId.Value}, event data is '{eventJson}'");
}
for (int i = 0; i < fragments.Length; i++)
{
Assert.True(eventJson.Contains(fragments[i]), $"Event data '{eventJson}' does not contain expected fragment {fragments[i]}");
}
}
private class TestEventListener : EventListener
{
public class ListenerSettings
{
public EventKeywords Keywords;
public EventLevel Level;
public string FilterSpec;
}
private System.Diagnostics.Tracing.EventSource _loggingEventSource;
public TestEventListener()
{
Events = new List<string>();
}
public List<string> Events;
public void EnableEvents(ListenerSettings settings)
{
var args = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(settings.FilterSpec))
{
args["FilterSpecs"] = settings.FilterSpec;
}
EnableEvents(_loggingEventSource, settings.Level, settings.Keywords, args);
}
protected override void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource)
{
if (eventSource.Name == "Microsoft-Extensions-Logging")
{
_loggingEventSource = eventSource;
}
}
public override void Dispose()
{
if (_loggingEventSource != null)
{
DisableEvents(_loggingEventSource);
}
base.Dispose();
}
protected override void OnEventWritten(EventWrittenEventArgs eventWrittenArgs)
{
// We cannot hold onto EventWrittenEventArgs for long because they are agressively reused.
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.DateFormatString = "O";
writer.WriteStartObject();
writer.WritePropertyName("__EVENT_NAME");
writer.WriteValue(eventWrittenArgs.EventName);
string propertyName;
for (int i = 0; i < eventWrittenArgs.PayloadNames.Count; i++)
{
propertyName = eventWrittenArgs.PayloadNames[i];
writer.WritePropertyName(propertyName, true);
if (IsJsonProperty(eventWrittenArgs.EventId, i, propertyName))
{
writer.WriteRawValue(eventWrittenArgs.Payload[i].ToString());
}
else
{
if (eventWrittenArgs.Payload[i] == null || IsPrimitive(eventWrittenArgs.Payload[i].GetType()))
{
writer.WriteValue(eventWrittenArgs.Payload[i]);
}
else if (eventWrittenArgs.Payload[i] is IDictionary<string, object>)
{
var dictProperty = (IDictionary<string, object>)eventWrittenArgs.Payload[i];
// EventPayload claims to support IDictionary<string, object>, but you cannot get a KeyValuePair enumerator out of it
// So we need to serialize manually
writer.WriteStartObject();
for (int j = 0; j < dictProperty.Keys.Count; j++)
{
writer.WritePropertyName(dictProperty.Keys.ElementAt(j));
writer.WriteValue(dictProperty.Values.ElementAt(j));
}
writer.WriteEndObject();
}
else
{
string serializedComplexValue = JsonConvert.SerializeObject(eventWrittenArgs.Payload[i]);
writer.WriteRawValue(serializedComplexValue);
}
}
}
writer.WriteEndObject();
Events.Add(sw.ToString());
}
private bool IsPrimitive(Type type)
{
return type == typeof(string) || type == typeof(int) || type == typeof(bool) || type == typeof(double);
}
private bool IsJsonProperty(int eventId, int propertyOrdinal, string propertyName)
{
// __payload_nn is an artificial property name that we are using in the .NET 4.5 case, where EventWrittenEventArgs does not carry payload name information
if (!propertyName.StartsWith("__payload"))
{
return propertyName.EndsWith("Json");
}
else
{
// Refers to events as they are defined by LoggingEventSource
// MessageJson has ExceptionJson (#4) and ArgumentsJson (#5)
bool messageJsonProperties = eventId == 5 && (propertyOrdinal == 4 || propertyOrdinal == 5);
// ActivityJsonStart has ArgumentsJson (#3)
bool activityJsonStartProperty = eventId == 6 && propertyOrdinal == 3;
return messageJsonProperties || activityJsonStartProperty;
}
}
}
private static class EventTypes
{
public static readonly string FormattedMessage = "FormattedMessage";
public static readonly string MessageJson = "MessageJson";
public static readonly string Message = "Message";
public static readonly string ActivityJsonStart = "ActivityJsonStart";
public static readonly string ActivityJsonStop = "ActivityJsonStop";
public static readonly string ActivityStart = "ActivityStart";
public static readonly string ActivityStop = "ActivityStop";
}
private static readonly Guid GuidParam = new Guid("29bebd2c-7fa6-4e97-af68-b91fdaae24b6");
private static readonly double DoubleParam1 = 3.1416;
private static readonly double DoubleParam2 = -273.15;
private static readonly DateTime TimeParam = new DateTime(2016, 5, 3, 19, 0, 0, DateTimeKind.Utc);
private static readonly IDictionary<string, Action<string>> EventVerifiers = new Dictionary<string, Action<string>>
{
{ "E1FM", (e) => VerifySingleEvent(e, "Logger1", EventTypes.FormattedMessage, 1, LogLevel.Debug,
@"""FormattedMessage"":""Logger1 Event1 Debug 1""") },
{ "E1JS", (e) => VerifySingleEvent(e, "Logger1", EventTypes.MessageJson, 1, LogLevel.Debug,
@"""ArgumentsJson"":{""intParam"":""1""") },
{ "E1MSG", (e) => VerifySingleEvent(e, "Logger1", EventTypes.Message, 1, LogLevel.Debug,
@"{""Key"":""intParam"",""Value"":""1""}") },
{ "E2FM", (e) => VerifySingleEvent(e, "Logger2", EventTypes.FormattedMessage, 2, LogLevel.Trace,
@"""FormattedMessage"":""Logger2 Event2 Trace " + DoubleParam1.ToString() + " " + TimeParam.ToString("O") + " " + DoubleParam2.ToString()) },
{ "E2JS", (e) => VerifySingleEvent(e, "Logger2", EventTypes.MessageJson, 2, LogLevel.Trace,
@"""ArgumentsJson"":{""doubleParam"":""" + DoubleParam1.ToString() + @""",""timeParam"":"""
+ TimeParam.ToString("O") +@""",""doubleParam2"":""" + DoubleParam2.ToString()) },
{ "E2MSG", (e) => VerifySingleEvent(e, "Logger2", EventTypes.Message, 2, LogLevel.Trace,
@"{""Key"":""doubleParam"",""Value"":""" + DoubleParam1.ToString() +@"""}",
@"{""Key"":""timeParam"",""Value"":""" + TimeParam.ToString("O") +@"""}",
@"{""Key"":""doubleParam2"",""Value"":""" + DoubleParam2.ToString() +@"""}") },
{ "E3FM", (e) => VerifySingleEvent(e, "Logger3", EventTypes.FormattedMessage, 3, LogLevel.Information,
@"""FormattedMessage"":""Logger3 Event3 Information foo bar baz") },
{ "E3JS", (e) => VerifySingleEvent(e, "Logger3", EventTypes.MessageJson, 3, LogLevel.Information,
@"""ArgumentsJson"":{""string1Param"":""foo"",""string2Param"":""bar"",""string3Param"":""baz""") },
{ "E3MSG", (e) => VerifySingleEvent(e, "Logger3", EventTypes.Message, 3, LogLevel.Information,
@"{""Key"":""string1Param"",""Value"":""foo""}",
@"{""Key"":""string2Param"",""Value"":""bar""}",
@"{""Key"":""string3Param"",""Value"":""baz""}") },
{ "E4FM", (e) => VerifySingleEvent(e, "Logger1", EventTypes.FormattedMessage, 4, LogLevel.Error,
@"""FormattedMessage"":""Logger1 Event4 Error foo " + GuidParam.ToString("D") + @"""") },
{ "E4JS", (e) => VerifySingleEvent(e, "Logger1", EventTypes.MessageJson, 4, LogLevel.Error,
@"""ArgumentsJson"":{""stringParam"":""foo"",""guidParam"":""" + GuidParam.ToString("D") + @"""") },
{ "E4MSG", (e) => VerifySingleEvent(e, "Logger1", EventTypes.Message, 4, LogLevel.Error,
@"{""Key"":""stringParam"",""Value"":""foo""}",
@"{""Key"":""guidParam"",""Value"":""" + GuidParam.ToString("D") +@"""}") },
{ "E5FM", (e) => VerifySingleEvent(e, "Logger2", EventTypes.FormattedMessage, 5, LogLevel.Critical,
@"""FormattedMessage"":""Logger2 Event5 Critical bar 23 45") },
{ "E5JS", (e) => VerifySingleEvent(e, "Logger2", EventTypes.MessageJson, 5, LogLevel.Critical,
@"""ArgumentsJson"":{""stringParam"":""bar"",""int1Param"":""23"",""int2Param"":""45""",
@"""ExceptionJson"":{""TypeName"":""System.Exception"",""Message"":""oops"",""HResult"":""-2146233088"",""VerboseMessage"":""System.Exception: oops ---> System.Exception: inner oops") },
{ "E5MSG", (e) => VerifySingleEvent(e, "Logger2", EventTypes.Message, 5, LogLevel.Critical,
@"{""Key"":""stringParam"",""Value"":""bar""}",
@"{""Key"":""int1Param"",""Value"":""23""}",
@"{""Key"":""int2Param"",""Value"":""45""}",
@"""Exception"":{""TypeName"":""System.Exception"",""Message"":""oops"",""HResult"":-2146233088,""VerboseMessage"":""System.Exception: oops ---> System.Exception: inner oops") },
{ "E6FM", (e) => VerifySingleEvent(e, "Logger2", EventTypes.FormattedMessage, 6, LogLevel.Warning,
@"""FormattedMessage"":""Logger2 Event6 Warning NoParams""") },
{ "E6JS", (e) => VerifySingleEvent(e, "Logger2", EventTypes.MessageJson, 6, LogLevel.Warning) },
{ "E6MSG", (e) => VerifySingleEvent(e, "Logger2", EventTypes.Message, 6, LogLevel.Warning) },
{ "E7FM", (e) => VerifySingleEvent(e, "Logger3", EventTypes.FormattedMessage, 7, LogLevel.Information,
@"""FormattedMessage"":""Logger3 Event7 Information inner scope closed " + DoubleParam2.ToString() + " 37") },
{ "E7JS", (e) => VerifySingleEvent(e, "Logger3", EventTypes.MessageJson, 7, LogLevel.Information,
@"""ArgumentsJson"":{""stringParam"":""inner scope closed"",""doubleParam"":""" + DoubleParam2.ToString() + @""",""intParam"":""37""") },
{ "E7MSG", (e) => VerifySingleEvent(e, "Logger3", EventTypes.Message, 7, LogLevel.Information,
@"{""Key"":""stringParam"",""Value"":""inner scope closed""}",
@"{""Key"":""doubleParam"",""Value"":""" + DoubleParam2.ToString() +@"""}",
@"{""Key"":""intParam"",""Value"":""37""}") },
{ "E8FM", (e) => VerifySingleEvent(e, "Logger2", EventTypes.FormattedMessage, 8, LogLevel.Warning,
@"""FormattedMessage"":""Logger2 Event8 Warning Outer scope closed " + TimeParam.ToString("O")) },
{ "E8JS", (e) => VerifySingleEvent(e, "Logger2", EventTypes.MessageJson, 8, LogLevel.Warning,
@"""ArgumentsJson"":{""stringParam"":""Outer scope closed"",""timeParam"":""" + TimeParam.ToString("O")) },
{ "E8MSG", (e) => VerifySingleEvent(e, "Logger2", EventTypes.Message, 8, LogLevel.Warning,
@"{""Key"":""stringParam"",""Value"":""Outer scope closed""}",
@"{""Key"":""timeParam"",""Value"":""" + TimeParam.ToString("O") +@"""}") },
{ "OuterScopeJsonStart", (e) => VerifySingleEvent(e, "Logger1", EventTypes.ActivityJsonStart, null, null,
@"""ArgumentsJson"":{""stringParam"":""scoped foo"",""intParam"":""13"",""doubleParam"":""" + DoubleParam1.ToString()) },
{ "OuterScopeJsonStop", (e) => VerifySingleEvent(e, "Logger1", EventTypes.ActivityJsonStop, null, null) },
{ "OuterScopeStart", (e) => VerifySingleEvent(e, "Logger1", EventTypes.ActivityStart, null, null) },
{ "OuterScopeStop", (e) => VerifySingleEvent(e, "Logger1", EventTypes.ActivityStop, null, null) },
{ "InnerScopeJsonStart", (e) => VerifySingleEvent(e, "Logger3", EventTypes.ActivityJsonStart, null, null,
@"""ArgumentsJson"":{""timeParam"":""" + TimeParam.ToString() + @""",""guidParam"":""" + GuidParam.ToString("D")) },
{ "InnerScopeJsonStop", (e) => VerifySingleEvent(e, "Logger3", EventTypes.ActivityJsonStop, null, null) },
{ "InnerScopeStart", (e) => VerifySingleEvent(e, "Logger3", EventTypes.ActivityStart, null, null) },
{ "InnerScopeStop", (e) => VerifySingleEvent(e, "Logger3", EventTypes.ActivityStop, null, null) },
};
}
}
| 44.585196 | 202 | 0.543871 | [
"Apache-2.0"
] | RickyLin/Extensions | src/Logging/Logging.EventSource/test/EventSourceLoggerTest.cs | 31,925 | C# |
using Hashgraph.Extensions;
using Hashgraph.Test.Fixtures;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Hashgraph.Test.Token
{
[Collection(nameof(NetworkCredentials))]
public class DissociateTokenTests
{
private readonly NetworkCredentials _network;
public DissociateTokenTests(NetworkCredentials network, ITestOutputHelper output)
{
_network = network;
_network.Output = output;
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate token from Account")]
public async Task CanDissociateTokenFromAccount()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var association = await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.Revoked, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
var receipt = await fxAccount.Client.DissociateTokenAsync(fxToken.Record.Token, fxAccount.Record.Address, fxAccount.PrivateKey);
Assert.Equal(ResponseCode.Success, receipt.Status);
await AssertHg.TokenNotAssociatedAsync(fxToken, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate token from Account and get Record")]
public async Task CanDissociateTokenFromAccountAndGetRecord()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var association = await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.Revoked, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
var record = await fxAccount.Client.DissociateTokenWithRecordAsync(fxToken.Record.Token, fxAccount.Record.Address, fxAccount.PrivateKey);
Assert.Equal(ResponseCode.Success, record.Status);
Assert.Equal(ResponseCode.Success, record.Status);
Assert.False(record.Hash.IsEmpty);
Assert.NotNull(record.Concensus);
Assert.NotNull(record.CurrentExchangeRate);
Assert.NotNull(record.NextExchangeRate);
Assert.NotEmpty(record.Hash.ToArray());
Assert.Empty(record.Memo);
Assert.InRange(record.Fee, 0UL, ulong.MaxValue);
Assert.Equal(_network.Payer, record.Id.Address);
await AssertHg.TokenNotAssociatedAsync(fxToken, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate token from Account (No Extra Signatory)")]
public async Task CanDissociateTokenFromAccountNoExtraSignatory()
{
await using var fxAccount = await TestAccount.CreateAsync(_network, fx => fx.CreateParams.InitialBalance = 120_00_000_000);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var association = await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.Revoked, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
var receipt = await fxAccount.Client.DissociateTokenAsync(fxToken.Record.Token, fxAccount.Record.Address, ctx =>
{
ctx.Payer = fxAccount.Record.Address;
ctx.Signatory = fxAccount.PrivateKey;
});
Assert.Equal(ResponseCode.Success, receipt.Status);
await AssertHg.TokenNotAssociatedAsync(fxToken, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate token from Account and get Record (No Extra Signatory)")]
public async Task CanDissociateTokenFromAccountAndGetRecordNoExtraSignatory()
{
await using var fxAccount = await TestAccount.CreateAsync(_network, fx => fx.CreateParams.InitialBalance = 120_00_000_000);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var association = await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.Revoked, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
var record = await fxAccount.Client.DissociateTokenWithRecordAsync(fxToken.Record.Token, fxAccount.Record.Address, ctx =>
{
ctx.Payer = fxAccount.Record.Address;
ctx.Signatory = fxAccount.PrivateKey;
});
Assert.Equal(ResponseCode.Success, record.Status);
Assert.Equal(ResponseCode.Success, record.Status);
Assert.False(record.Hash.IsEmpty);
Assert.NotNull(record.Concensus);
Assert.NotNull(record.CurrentExchangeRate);
Assert.NotNull(record.NextExchangeRate);
Assert.NotEmpty(record.Hash.ToArray());
Assert.Empty(record.Memo);
Assert.InRange(record.Fee, 0UL, ulong.MaxValue);
Assert.Equal(fxAccount.Record.Address, record.Id.Address);
await AssertHg.TokenNotAssociatedAsync(fxToken, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate Multpile Tokens with Account")]
public async Task CanDissociateMultipleTokensWithAccount()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken1 = await TestToken.CreateAsync(_network, null, fxAccount);
await using var fxToken2 = await TestToken.CreateAsync(_network, null, fxAccount);
var tokens = new Address[] { fxToken1.Record.Token, fxToken2.Record.Token };
await AssertHg.TokenIsAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenIsAssociatedAsync(fxToken2, fxAccount);
var receipt = await fxAccount.Client.DissociateTokensAsync(tokens, fxAccount.Record.Address, fxAccount.PrivateKey);
Assert.Equal(ResponseCode.Success, receipt.Status);
await AssertHg.TokenNotAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenNotAssociatedAsync(fxToken2, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate Multiple Tokens with Account and get Record")]
public async Task CanDissociateMultipleTokensWithAccountAndGetRecord()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken1 = await TestToken.CreateAsync(_network, null, fxAccount);
await using var fxToken2 = await TestToken.CreateAsync(_network, null, fxAccount);
var tokens = new Address[] { fxToken1.Record.Token, fxToken2.Record.Token };
await AssertHg.TokenIsAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenIsAssociatedAsync(fxToken2, fxAccount);
var record = await fxAccount.Client.DissociateTokensWithRecordAsync(tokens, fxAccount.Record.Address, fxAccount.PrivateKey);
Assert.Equal(ResponseCode.Success, record.Status);
Assert.Equal(ResponseCode.Success, record.Status);
Assert.False(record.Hash.IsEmpty);
Assert.NotNull(record.Concensus);
Assert.NotNull(record.CurrentExchangeRate);
Assert.NotNull(record.NextExchangeRate);
Assert.NotEmpty(record.Hash.ToArray());
Assert.Empty(record.Memo);
Assert.InRange(record.Fee, 0UL, ulong.MaxValue);
Assert.Equal(_network.Payer, record.Id.Address);
await AssertHg.TokenNotAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenNotAssociatedAsync(fxToken2, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate Multiple Token with Account (No Extra Signatory)")]
public async Task CanDissociateMultipleTokensWithAccountNoExtraSignatory()
{
await using var fxAccount = await TestAccount.CreateAsync(_network, fx => fx.CreateParams.InitialBalance = 120_00_000_000);
await using var fxToken1 = await TestToken.CreateAsync(_network, null, fxAccount);
await using var fxToken2 = await TestToken.CreateAsync(_network, null, fxAccount);
var tokens = new Address[] { fxToken1.Record.Token, fxToken2.Record.Token };
await AssertHg.TokenIsAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenIsAssociatedAsync(fxToken2, fxAccount);
var receipt = await fxAccount.Client.DissociateTokensAsync(tokens, fxAccount.Record.Address, ctx =>
{
ctx.Payer = fxAccount.Record.Address;
ctx.Signatory = fxAccount.PrivateKey;
});
Assert.Equal(ResponseCode.Success, receipt.Status);
await AssertHg.TokenNotAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenNotAssociatedAsync(fxToken2, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate Multiple Token with Account and get Record (No Extra Signatory)")]
public async Task CanDissociateMultipleTokensWithAccountAndGetRecordNoExtraSignatory()
{
await using var fxAccount = await TestAccount.CreateAsync(_network, fx => fx.CreateParams.InitialBalance = 120_00_000_000);
await using var fxToken1 = await TestToken.CreateAsync(_network, null, fxAccount);
await using var fxToken2 = await TestToken.CreateAsync(_network, null, fxAccount);
var tokens = new Address[] { fxToken1.Record.Token, fxToken2.Record.Token };
await AssertHg.TokenIsAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenIsAssociatedAsync(fxToken2, fxAccount);
var record = await fxAccount.Client.DissociateTokensWithRecordAsync(tokens, fxAccount.Record.Address, ctx =>
{
ctx.Payer = fxAccount.Record.Address;
ctx.Signatory = fxAccount.PrivateKey;
});
Assert.Equal(ResponseCode.Success, record.Status);
Assert.Equal(ResponseCode.Success, record.Status);
Assert.False(record.Hash.IsEmpty);
Assert.NotNull(record.Concensus);
Assert.NotNull(record.CurrentExchangeRate);
Assert.NotNull(record.NextExchangeRate);
Assert.NotEmpty(record.Hash.ToArray());
Assert.Empty(record.Memo);
Assert.InRange(record.Fee, 0UL, ulong.MaxValue);
Assert.Equal(fxAccount.Record.Address, record.Id.Address);
await AssertHg.TokenNotAssociatedAsync(fxToken1, fxAccount);
await AssertHg.TokenNotAssociatedAsync(fxToken2, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: No Token Balance Record Exists When Dissociated")]
public async Task NoTokenBalanceRecordExistsWhenDissociated()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var association = await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.Revoked, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
var receipt = await fxAccount.Client.DissociateTokenAsync(fxToken.Record.Token, fxAccount.Record.Address, fxAccount.PrivateKey);
Assert.Equal(ResponseCode.Success, receipt.Status);
await AssertHg.TokenNotAssociatedAsync(fxToken, fxAccount);
}
[Fact(DisplayName = "Dissociate Tokens: Dissociation Requires Signing by Target Account")]
public async Task DissociationRequiresSigningByTargetAccount()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var association = await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.Revoked, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
var tex = await Assert.ThrowsAsync<TransactionException>(async () =>
{
await fxAccount.Client.DissociateTokenAsync(fxToken.Record.Token, fxAccount.Record.Address);
});
Assert.Equal(ResponseCode.InvalidSignature, tex.Status);
Assert.StartsWith("Unable to Dissociate Token from Account, status: InvalidSignature", tex.Message);
association = await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.Revoked, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
}
[Fact(DisplayName = "Dissociate Tokens: Dissociation Requires Token Account")]
public async Task DissociationRequiresTokenAccount()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
var ane = await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await fxAccount.Client.DissociateTokenAsync(Address.None, fxAccount.Record.Address);
});
Assert.Equal("token", ane.ParamName);
Assert.StartsWith("Token is missing. Please check that it is not null or empty.", ane.Message);
ane = await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await fxAccount.Client.DissociateTokenAsync(null, fxAccount.Record.Address);
});
Assert.Equal("token", ane.ParamName);
Assert.StartsWith("Token is missing. Please check that it is not null or empty.", ane.Message);
ane = await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await fxAccount.Client.DissociateTokensAsync(null, fxAccount.Record.Address);
});
Assert.Equal("tokens", ane.ParamName);
Assert.StartsWith("The list of tokens cannot be null.", ane.Message);
var aoe = await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
{
await fxAccount.Client.DissociateTokensAsync(new Address[] { null }, fxAccount.Record.Address);
});
Assert.Equal("tokens", aoe.ParamName);
Assert.StartsWith("The list of tokens cannot contain an empty or null address.", aoe.Message);
}
[Fact(DisplayName = "Dissociate Tokens: Dissociation Requires Account")]
public async Task DissociationRequiresAccount()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var ane = await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await fxAccount.Client.DissociateTokenAsync(fxToken.Record.Token, null);
});
Assert.Equal("account", ane.ParamName);
Assert.StartsWith("Account Address is missing. Please check that it is not null.", ane.Message);
var tex = await Assert.ThrowsAsync<TransactionException>(async () =>
{
await fxAccount.Client.DissociateTokenAsync(fxToken.Record.Token, Address.None);
});
Assert.Equal(ResponseCode.InvalidAccountId, tex.Status);
Assert.StartsWith("Unable to Dissociate Token from Account, status: InvalidAccountId", tex.Message);
}
[Fact(DisplayName = "Dissociate Tokens: Dissociating with Deleted Account Raises Error")]
public async Task DissociatingWithDeletedAccountRaisesError()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
await fxAccount.Client.DeleteAccountAsync(fxAccount, _network.Payer, fxAccount);
var tex = await Assert.ThrowsAsync<TransactionException>(async () =>
{
await fxAccount.Client.DissociateTokenAsync(fxToken.Record.Token, fxAccount.Record.Address, fxAccount.PrivateKey);
});
Assert.Equal(ResponseCode.AccountDeleted, tex.Status);
Assert.StartsWith("Unable to Dissociate Token from Account, status: AccountDelete", tex.Message);
}
[Fact(DisplayName = "Dissociate Tokens: Dissociating with Duplicate Token Raises Error")]
public async Task DissociatingWithDuplicateAccountRaisesError()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
var pex = await Assert.ThrowsAsync<PrecheckException>(async () =>
{
var tokens = new Address[] { fxToken.Record.Token, fxToken.Record.Token };
await fxToken.Client.DissociateTokensAsync(tokens, fxAccount.Record.Address, fxAccount.PrivateKey);
});
Assert.Equal(ResponseCode.TokenIdRepeatedInTokenList, pex.Status);
Assert.StartsWith("Transaction Failed Pre-Check: TokenIdRepeatedInTokenList", pex.Message);
}
[Fact(DisplayName = "Dissociate Tokens: Dissociate with Dissociated Token Raises Error")]
public async Task DissociateWithDissociatedTokenRaisesError()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken1 = await TestToken.CreateAsync(_network, null, fxAccount);
await using var fxToken2 = await TestToken.CreateAsync(_network);
var tex = await Assert.ThrowsAsync<TransactionException>(async () =>
{
var tokens = new Address[] { fxToken1.Record.Token, fxToken2.Record.Token };
await fxAccount.Client.DissociateTokensAsync(tokens, fxAccount.Record.Address, fxAccount.PrivateKey);
});
Assert.Equal(ResponseCode.TokenNotAssociatedToAccount, tex.Status);
Assert.StartsWith("Unable to Dissociate Token from Account, status: TokenNotAssociatedToAccount", tex.Message);
}
[Fact(DisplayName = "Dissociate Tokens: Can Dissociate token from Contract Consent")]
public async Task CanDissociateTokenFromContract()
{
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxContract = await GreetingContract.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, fx => fx.Params.GrantKycEndorsement = null);
var xferAmount = 2 * fxToken.Params.Circulation / 3;
var receipt = await fxContract.Client.AssociateTokenAsync(fxToken.Record.Token, fxContract.ContractRecord.Contract, fxContract.PrivateKey);
Assert.Equal(ResponseCode.Success, receipt.Status);
var info = await fxAccount.Client.GetContractInfoAsync(fxContract.ContractRecord.Contract);
Assert.NotNull(info);
var association = info.Tokens.FirstOrDefault(t => t.Token == fxToken.Record.Token);
Assert.NotNull(association);
Assert.Equal(fxToken.Record.Token, association.Token);
Assert.Equal(fxToken.Params.Symbol, association.Symbol);
Assert.Equal(0UL, association.Balance);
Assert.Equal(fxToken.Params.Decimals, association.Decimals);
Assert.Equal(TokenKycStatus.NotApplicable, association.KycStatus);
Assert.Equal(TokenTradableStatus.Tradable, association.TradableStatus);
receipt = await fxContract.Client.DissociateTokenAsync(fxToken.Record.Token, fxContract.ContractRecord.Contract, fxContract.PrivateKey);
Assert.Equal(ResponseCode.Success, receipt.Status);
info = await fxAccount.Client.GetContractInfoAsync(fxContract.ContractRecord.Contract);
Assert.NotNull(info);
Assert.Null(info.Tokens.FirstOrDefault(t => t.Token == fxToken.Record.Token));
var tex = await Assert.ThrowsAsync<TransactionException>(async () =>
{
await fxToken.Client.TransferTokensAsync(fxToken.Record.Token, fxToken.TreasuryAccount.Record.Address, fxContract.ContractRecord.Contract, (long)xferAmount, fxToken.TreasuryAccount.PrivateKey);
});
Assert.Equal(ResponseCode.TokenNotAssociatedToAccount, tex.Status);
Assert.StartsWith("Unable to execute transfers, status: TokenNotAssociatedToAccount", tex.Message);
Assert.Equal(0UL, await fxToken.Client.GetContractTokenBalanceAsync(fxContract, fxToken));
}
[Fact(DisplayName = "Token Delete: Can Delete Account Having Token Balance")]
public async Task CanDeleteAccountHavingTokenBalance()
{
await using var fxAccount1 = await TestAccount.CreateAsync(_network, fx => fx.CreateParams.InitialBalance = 120_00_000_000);
await using var fxAccount2 = await TestAccount.CreateAsync(_network, fx => fx.CreateParams.InitialBalance = 120_00_000_000);
await using var fxToken = await TestToken.CreateAsync(_network, fx => fx.Params.GrantKycEndorsement = null, fxAccount1, fxAccount2);
var xferAmount = (long)fxToken.Params.Circulation;
await AssertHg.TokenBalanceAsync(fxToken, fxAccount1, 0);
await AssertHg.TokenBalanceAsync(fxToken, fxAccount2, 0);
await AssertHg.TokenBalanceAsync(fxToken, fxToken.TreasuryAccount, fxToken.Params.Circulation);
await fxAccount1.Client.TransferTokensAsync(fxToken, fxToken.TreasuryAccount, fxAccount1, xferAmount, fxToken.TreasuryAccount);
await AssertHg.TokenBalanceAsync(fxToken, fxAccount1, fxToken.Params.Circulation);
await AssertHg.TokenBalanceAsync(fxToken, fxAccount2, 0);
await AssertHg.TokenBalanceAsync(fxToken, fxToken.TreasuryAccount, 0);
// Can't delete the account because it has tokens associated with it.
var tex = await Assert.ThrowsAsync<TransactionException>(async () =>
{
await fxAccount1.Client.DeleteAccountAsync(fxAccount1, fxAccount2, fxAccount1.PrivateKey);
});
Assert.Equal(ResponseCode.TransactionRequiresZeroTokenBalances, tex.Status);
Assert.StartsWith("Unable to delete account, status: TransactionRequiresZeroTokenBalances", tex.Message);
await AssertHg.TokenBalanceAsync(fxToken, fxAccount1, fxToken.Params.Circulation);
await AssertHg.TokenBalanceAsync(fxToken, fxAccount2, 0);
await AssertHg.TokenBalanceAsync(fxToken, fxToken.TreasuryAccount, 0);
await fxAccount1.Client.TransferTokensAsync(fxToken, fxAccount1, fxAccount2, xferAmount, fxAccount1);
await fxAccount1.Client.DeleteAccountAsync(fxAccount1, fxAccount2, fxAccount1.PrivateKey);
await AssertHg.TokenBalanceAsync(fxToken, fxAccount2, fxToken.Params.Circulation);
await AssertHg.TokenBalanceAsync(fxToken, fxToken.TreasuryAccount, 0);
}
[Fact(DisplayName = "Dissociate Tokens: Can Not Schedule Dissociate token from Account")]
public async Task CanNotScheduleDissociateTokenFromAccount()
{
await using var fxPayer = await TestAccount.CreateAsync(_network, fx => fx.CreateParams.InitialBalance = 20_00_000_000);
await using var fxAccount = await TestAccount.CreateAsync(_network);
await using var fxToken = await TestToken.CreateAsync(_network, null, fxAccount);
await AssertHg.TokenIsAssociatedAsync(fxToken, fxAccount);
var tex = await Assert.ThrowsAsync<TransactionException>(async () =>
{
await fxAccount.Client.DissociateTokenAsync(
fxToken.Record.Token,
fxAccount.Record.Address,
new Signatory(
fxAccount.PrivateKey,
new PendingParams
{
PendingPayer = fxPayer
}));
});
Assert.Equal(ResponseCode.ScheduledTransactionNotInWhitelist, tex.Status);
Assert.StartsWith("Unable to schedule transaction, status: ScheduledTransactionNotInWhitelist", tex.Message);
}
}
}
| 58.43871 | 210 | 0.666151 | [
"Apache-2.0"
] | ZhingShan/Hashgraph | test/Hashgraph.Test/Token/DissociateTokenTests.cs | 27,176 | C# |
using System.IO;
using System.Xml.Serialization;
namespace MyCalendar.App.Helpers
{
public class FileHelpersXml<T> where T : new()
{
private readonly string _filePath;
public FileHelpersXml(string filePath)
{
_filePath = filePath;
}
public void SerializeToFile(T param)
{
// CHECK IF FILE EXISTS
var fileInfo = new FileInfo(_filePath);
if (!fileInfo.Exists)
Directory.CreateDirectory(fileInfo.Directory.FullName);
// SAVE TO FILE
var serializer = new XmlSerializer(typeof(T));
using var streamWriter = new StreamWriter(_filePath);
serializer.Serialize(streamWriter, param);
streamWriter.Close();
}
public T DeserializeFromFile()
{
// CHECK IF FILE EXISTS
if (!File.Exists(_filePath))
return new T();
// DOWNLOAD FROM FILE
var serializer = new XmlSerializer(typeof(T));
using var streamReader = new StreamReader(_filePath);
var collectedData = (T)serializer.Deserialize(streamReader);
streamReader.Close();
return collectedData;
}
}
} | 28.840909 | 72 | 0.57368 | [
"MIT"
] | deSp44/MyCalendar | MyCalendar.App/Helpers/FileHelpersXml.cs | 1,271 | C# |
using UnityEngine;
using MacKay.PlayerController.Ship;
namespace MacKay.Animations
{
public class PlayerAnimationController : MonoBehaviour
{
private static PlayerAnimationController _instance;
public static PlayerAnimationController Instance { get { return _instance; } }
[SerializeField]
private ShipRumble anim_ShipRumble;
public ShipRumble ShipRumble
{
get
{
if (!anim_ShipRumble)
{
anim_ShipRumble = GetComponent<ShipRumble>();
if (!anim_ShipRumble)
{
anim_ShipRumble = gameObject.AddComponent<ShipRumble>();
}
}
return anim_ShipRumble;
}
}
#region Unity Methods
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
}
}
#endregion
}
} | 25.266667 | 86 | 0.487247 | [
"MIT"
] | mikebmac/VR-Local-Solar-System-for-Master-s-Thesis | Scripts/Runtime/Animations/Player/PlayerAnimationController.cs | 1,137 | C# |
using System;
using System.Xml;
using System.Xml.Schema;
using WebServiceXmlParser.Core.Interfaces;
using WebServiceXmlParser.Core.Models;
namespace WebServiceXmlParser.Services
{
public class ParseInputDocumentService : IParseInputDocumentService
{
/// <summary>
/// Parse an Xml document and validate that it has the correct structure, attributes and elements as defined by the business requirements.
/// </summary>
/// <param name="xmlDocument"></param>
/// <returns></returns>
public DocumentParseResult ValidateDocument(XmlDocument xmlDocument)
{
//
try
{
// Verify that the document structure is correct.
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", new XmlTextReader("../Core/InputDocumentSchema.xsd"));
xmlDocument.Validate(InputDocumentValidationEventHandler); // need to use the output from this
if (xmlDocument.FirstChild.InnerText != "InputDocument")
{
return new DocumentParseResult()
{
Status = -5,
Message = "Invalid document structure"
};
}
// Check question part b
// Verify that the Declaration element has the correct Command attribute
if (xmlDocument.GetElementById("Declaration").HasAttribute("Command")
&& xmlDocument.GetElementById("Declaration").GetAttribute("Command") != "DEFAULT")
{
return new DocumentParseResult()
{
Status = -1,
Message = "Invalid command specified"
};
}
// Check question part c
// Verify that the Site ID element has the correct Value
if (xmlDocument.GetElementById("SiteID").InnerText != "DUB")
{
return new DocumentParseResult()
{
Status = -2,
Message = "Invalid site specified"
};
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return new DocumentParseResult()
{
Status = 0,
Message = "Document is structured correctly"
};
}
private void InputDocumentValidationEventHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning)
{
Console.Write("WARNING: ");
Console.WriteLine(e.Message);
}
else if (e.Severity == XmlSeverityType.Error)
{
Console.Write("ERROR: ");
Console.WriteLine(e.Message);
}
}
}
}
| 34.942529 | 146 | 0.504934 | [
"MIT"
] | beirnem/upgraded-happiness | WebServiceXmlParser/Services/ParseInputDocumentService.cs | 3,042 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.EdgeOrder.Outputs
{
[OutputType]
public sealed class ImageInformationResponseResult
{
/// <summary>
/// Type of the image
/// </summary>
public readonly string ImageType;
/// <summary>
/// Url of the image
/// </summary>
public readonly string ImageUrl;
[OutputConstructor]
private ImageInformationResponseResult(
string imageType,
string imageUrl)
{
ImageType = imageType;
ImageUrl = imageUrl;
}
}
}
| 24.805556 | 81 | 0.620381 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/EdgeOrder/Outputs/ImageInformationResponseResult.cs | 893 | C# |
partial class InnerVerifier
{
public Task VerifyFile(string path)
{
Guard.FileExists(path, nameof(path));
settings.extension ??= EmptyFiles.Extensions.GetExtension(path);
return VerifyStream(FileHelpers.OpenRead(path));
}
public Task VerifyFile(FileInfo target)
{
return VerifyFile(target.FullName);
}
}
| 25.066667 | 73 | 0.643617 | [
"MIT"
] | 304NotModified/Verify | src/Verify/Verifier/InnerVerifier_File.cs | 364 | 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 healthlake-2017-07-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.HealthLake.Model;
using Amazon.HealthLake.Model.Internal.MarshallTransformations;
using Amazon.HealthLake.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.HealthLake
{
/// <summary>
/// Implementation for accessing HealthLake
///
/// Amazon HealthLake is a HIPAA eligibile service that allows customers to store, transform,
/// query, and analyze their FHIR-formatted data in a consistent fashion in the cloud.
/// </summary>
public partial class AmazonHealthLakeClient : AmazonServiceClient, IAmazonHealthLake
{
private static IServiceMetadata serviceMetadata = new AmazonHealthLakeMetadata();
#if BCL45 || AWS_ASYNC_ENUMERABLES_API
private IHealthLakePaginatorFactory _paginators;
/// <summary>
/// Paginators for the service
/// </summary>
public IHealthLakePaginatorFactory Paginators
{
get
{
if (this._paginators == null)
{
this._paginators = new HealthLakePaginatorFactory(this);
}
return this._paginators;
}
}
#endif
#region Constructors
/// <summary>
/// Constructs AmazonHealthLakeClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonHealthLakeClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonHealthLakeConfig()) { }
/// <summary>
/// Constructs AmazonHealthLakeClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonHealthLakeClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonHealthLakeConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonHealthLakeClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonHealthLakeClient Configuration Object</param>
public AmazonHealthLakeClient(AmazonHealthLakeConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonHealthLakeClient(AWSCredentials credentials)
: this(credentials, new AmazonHealthLakeConfig())
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonHealthLakeClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonHealthLakeConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Credentials and an
/// AmazonHealthLakeClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonHealthLakeClient Configuration Object</param>
public AmazonHealthLakeClient(AWSCredentials credentials, AmazonHealthLakeConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonHealthLakeClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonHealthLakeConfig())
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonHealthLakeClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonHealthLakeConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonHealthLakeClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonHealthLakeClient Configuration Object</param>
public AmazonHealthLakeClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonHealthLakeConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonHealthLakeClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonHealthLakeConfig())
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonHealthLakeClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonHealthLakeConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonHealthLakeClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonHealthLakeClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonHealthLakeClient Configuration Object</param>
public AmazonHealthLakeClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonHealthLakeConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateFHIRDatastore
/// <summary>
/// Creates a Data Store that can ingest and export FHIR formatted data.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateFHIRDatastore service method.</param>
///
/// <returns>The response from the CreateFHIRDatastore service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.AccessDeniedException">
/// Access is denied. Your account is not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/CreateFHIRDatastore">REST API Reference for CreateFHIRDatastore Operation</seealso>
public virtual CreateFHIRDatastoreResponse CreateFHIRDatastore(CreateFHIRDatastoreRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateFHIRDatastoreRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateFHIRDatastoreResponseUnmarshaller.Instance;
return Invoke<CreateFHIRDatastoreResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateFHIRDatastore operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateFHIRDatastore operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateFHIRDatastore
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/CreateFHIRDatastore">REST API Reference for CreateFHIRDatastore Operation</seealso>
public virtual IAsyncResult BeginCreateFHIRDatastore(CreateFHIRDatastoreRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateFHIRDatastoreRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateFHIRDatastoreResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateFHIRDatastore operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateFHIRDatastore.</param>
///
/// <returns>Returns a CreateFHIRDatastoreResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/CreateFHIRDatastore">REST API Reference for CreateFHIRDatastore Operation</seealso>
public virtual CreateFHIRDatastoreResponse EndCreateFHIRDatastore(IAsyncResult asyncResult)
{
return EndInvoke<CreateFHIRDatastoreResponse>(asyncResult);
}
#endregion
#region DeleteFHIRDatastore
/// <summary>
/// Deletes a Data Store.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteFHIRDatastore service method.</param>
///
/// <returns>The response from the DeleteFHIRDatastore service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.AccessDeniedException">
/// Access is denied. Your account is not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ConflictException">
/// The Data Store is in a transition state and the user requested action can not be performed.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DeleteFHIRDatastore">REST API Reference for DeleteFHIRDatastore Operation</seealso>
public virtual DeleteFHIRDatastoreResponse DeleteFHIRDatastore(DeleteFHIRDatastoreRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFHIRDatastoreRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFHIRDatastoreResponseUnmarshaller.Instance;
return Invoke<DeleteFHIRDatastoreResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteFHIRDatastore operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteFHIRDatastore operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteFHIRDatastore
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DeleteFHIRDatastore">REST API Reference for DeleteFHIRDatastore Operation</seealso>
public virtual IAsyncResult BeginDeleteFHIRDatastore(DeleteFHIRDatastoreRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteFHIRDatastoreRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteFHIRDatastoreResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteFHIRDatastore operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteFHIRDatastore.</param>
///
/// <returns>Returns a DeleteFHIRDatastoreResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DeleteFHIRDatastore">REST API Reference for DeleteFHIRDatastore Operation</seealso>
public virtual DeleteFHIRDatastoreResponse EndDeleteFHIRDatastore(IAsyncResult asyncResult)
{
return EndInvoke<DeleteFHIRDatastoreResponse>(asyncResult);
}
#endregion
#region DescribeFHIRDatastore
/// <summary>
/// Gets the properties associated with the FHIR Data Store, including the Data Store
/// ID, Data Store ARN, Data Store name, Data Store status, created at, Data Store type
/// version, and Data Store endpoint.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeFHIRDatastore service method.</param>
///
/// <returns>The response from the DescribeFHIRDatastore service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRDatastore">REST API Reference for DescribeFHIRDatastore Operation</seealso>
public virtual DescribeFHIRDatastoreResponse DescribeFHIRDatastore(DescribeFHIRDatastoreRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFHIRDatastoreRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFHIRDatastoreResponseUnmarshaller.Instance;
return Invoke<DescribeFHIRDatastoreResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeFHIRDatastore operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeFHIRDatastore operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeFHIRDatastore
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRDatastore">REST API Reference for DescribeFHIRDatastore Operation</seealso>
public virtual IAsyncResult BeginDescribeFHIRDatastore(DescribeFHIRDatastoreRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFHIRDatastoreRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFHIRDatastoreResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeFHIRDatastore operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeFHIRDatastore.</param>
///
/// <returns>Returns a DescribeFHIRDatastoreResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRDatastore">REST API Reference for DescribeFHIRDatastore Operation</seealso>
public virtual DescribeFHIRDatastoreResponse EndDescribeFHIRDatastore(IAsyncResult asyncResult)
{
return EndInvoke<DescribeFHIRDatastoreResponse>(asyncResult);
}
#endregion
#region DescribeFHIRExportJob
/// <summary>
/// Displays the properties of a FHIR export job, including the ID, ARN, name, and the
/// status of the job.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeFHIRExportJob service method.</param>
///
/// <returns>The response from the DescribeFHIRExportJob service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRExportJob">REST API Reference for DescribeFHIRExportJob Operation</seealso>
public virtual DescribeFHIRExportJobResponse DescribeFHIRExportJob(DescribeFHIRExportJobRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFHIRExportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFHIRExportJobResponseUnmarshaller.Instance;
return Invoke<DescribeFHIRExportJobResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeFHIRExportJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeFHIRExportJob operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeFHIRExportJob
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRExportJob">REST API Reference for DescribeFHIRExportJob Operation</seealso>
public virtual IAsyncResult BeginDescribeFHIRExportJob(DescribeFHIRExportJobRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFHIRExportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFHIRExportJobResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeFHIRExportJob operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeFHIRExportJob.</param>
///
/// <returns>Returns a DescribeFHIRExportJobResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRExportJob">REST API Reference for DescribeFHIRExportJob Operation</seealso>
public virtual DescribeFHIRExportJobResponse EndDescribeFHIRExportJob(IAsyncResult asyncResult)
{
return EndInvoke<DescribeFHIRExportJobResponse>(asyncResult);
}
#endregion
#region DescribeFHIRImportJob
/// <summary>
/// Displays the properties of a FHIR import job, including the ID, ARN, name, and the
/// status of the job.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeFHIRImportJob service method.</param>
///
/// <returns>The response from the DescribeFHIRImportJob service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRImportJob">REST API Reference for DescribeFHIRImportJob Operation</seealso>
public virtual DescribeFHIRImportJobResponse DescribeFHIRImportJob(DescribeFHIRImportJobRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFHIRImportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFHIRImportJobResponseUnmarshaller.Instance;
return Invoke<DescribeFHIRImportJobResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeFHIRImportJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeFHIRImportJob operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeFHIRImportJob
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRImportJob">REST API Reference for DescribeFHIRImportJob Operation</seealso>
public virtual IAsyncResult BeginDescribeFHIRImportJob(DescribeFHIRImportJobRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeFHIRImportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeFHIRImportJobResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeFHIRImportJob operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeFHIRImportJob.</param>
///
/// <returns>Returns a DescribeFHIRImportJobResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/DescribeFHIRImportJob">REST API Reference for DescribeFHIRImportJob Operation</seealso>
public virtual DescribeFHIRImportJobResponse EndDescribeFHIRImportJob(IAsyncResult asyncResult)
{
return EndInvoke<DescribeFHIRImportJobResponse>(asyncResult);
}
#endregion
#region ListFHIRDatastores
/// <summary>
/// Lists all FHIR Data Stores that are in the user’s account, regardless of Data Store
/// status.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFHIRDatastores service method.</param>
///
/// <returns>The response from the ListFHIRDatastores service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRDatastores">REST API Reference for ListFHIRDatastores Operation</seealso>
public virtual ListFHIRDatastoresResponse ListFHIRDatastores(ListFHIRDatastoresRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFHIRDatastoresRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFHIRDatastoresResponseUnmarshaller.Instance;
return Invoke<ListFHIRDatastoresResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListFHIRDatastores operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListFHIRDatastores operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListFHIRDatastores
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRDatastores">REST API Reference for ListFHIRDatastores Operation</seealso>
public virtual IAsyncResult BeginListFHIRDatastores(ListFHIRDatastoresRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFHIRDatastoresRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFHIRDatastoresResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListFHIRDatastores operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListFHIRDatastores.</param>
///
/// <returns>Returns a ListFHIRDatastoresResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRDatastores">REST API Reference for ListFHIRDatastores Operation</seealso>
public virtual ListFHIRDatastoresResponse EndListFHIRDatastores(IAsyncResult asyncResult)
{
return EndInvoke<ListFHIRDatastoresResponse>(asyncResult);
}
#endregion
#region ListFHIRExportJobs
/// <summary>
/// Lists all FHIR export jobs associated with an account and their statuses.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFHIRExportJobs service method.</param>
///
/// <returns>The response from the ListFHIRExportJobs service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.AccessDeniedException">
/// Access is denied. Your account is not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRExportJobs">REST API Reference for ListFHIRExportJobs Operation</seealso>
public virtual ListFHIRExportJobsResponse ListFHIRExportJobs(ListFHIRExportJobsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFHIRExportJobsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFHIRExportJobsResponseUnmarshaller.Instance;
return Invoke<ListFHIRExportJobsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListFHIRExportJobs operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListFHIRExportJobs operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListFHIRExportJobs
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRExportJobs">REST API Reference for ListFHIRExportJobs Operation</seealso>
public virtual IAsyncResult BeginListFHIRExportJobs(ListFHIRExportJobsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFHIRExportJobsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFHIRExportJobsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListFHIRExportJobs operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListFHIRExportJobs.</param>
///
/// <returns>Returns a ListFHIRExportJobsResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRExportJobs">REST API Reference for ListFHIRExportJobs Operation</seealso>
public virtual ListFHIRExportJobsResponse EndListFHIRExportJobs(IAsyncResult asyncResult)
{
return EndInvoke<ListFHIRExportJobsResponse>(asyncResult);
}
#endregion
#region ListFHIRImportJobs
/// <summary>
/// Lists all FHIR import jobs associated with an account and their statuses.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFHIRImportJobs service method.</param>
///
/// <returns>The response from the ListFHIRImportJobs service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.AccessDeniedException">
/// Access is denied. Your account is not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRImportJobs">REST API Reference for ListFHIRImportJobs Operation</seealso>
public virtual ListFHIRImportJobsResponse ListFHIRImportJobs(ListFHIRImportJobsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFHIRImportJobsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFHIRImportJobsResponseUnmarshaller.Instance;
return Invoke<ListFHIRImportJobsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListFHIRImportJobs operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListFHIRImportJobs operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListFHIRImportJobs
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRImportJobs">REST API Reference for ListFHIRImportJobs Operation</seealso>
public virtual IAsyncResult BeginListFHIRImportJobs(ListFHIRImportJobsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFHIRImportJobsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFHIRImportJobsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListFHIRImportJobs operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListFHIRImportJobs.</param>
///
/// <returns>Returns a ListFHIRImportJobsResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListFHIRImportJobs">REST API Reference for ListFHIRImportJobs Operation</seealso>
public virtual ListFHIRImportJobsResponse EndListFHIRImportJobs(IAsyncResult asyncResult)
{
return EndInvoke<ListFHIRImportJobsResponse>(asyncResult);
}
#endregion
#region ListTagsForResource
/// <summary>
/// Returns a list of all existing tags associated with a Data Store.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return Invoke<ListTagsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param>
///
/// <returns>Returns a ListTagsForResourceResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult)
{
return EndInvoke<ListTagsForResourceResponse>(asyncResult);
}
#endregion
#region StartFHIRExportJob
/// <summary>
/// Begins a FHIR export job.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartFHIRExportJob service method.</param>
///
/// <returns>The response from the StartFHIRExportJob service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.AccessDeniedException">
/// Access is denied. Your account is not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/StartFHIRExportJob">REST API Reference for StartFHIRExportJob Operation</seealso>
public virtual StartFHIRExportJobResponse StartFHIRExportJob(StartFHIRExportJobRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartFHIRExportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartFHIRExportJobResponseUnmarshaller.Instance;
return Invoke<StartFHIRExportJobResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the StartFHIRExportJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartFHIRExportJob operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartFHIRExportJob
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/StartFHIRExportJob">REST API Reference for StartFHIRExportJob Operation</seealso>
public virtual IAsyncResult BeginStartFHIRExportJob(StartFHIRExportJobRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartFHIRExportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartFHIRExportJobResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the StartFHIRExportJob operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartFHIRExportJob.</param>
///
/// <returns>Returns a StartFHIRExportJobResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/StartFHIRExportJob">REST API Reference for StartFHIRExportJob Operation</seealso>
public virtual StartFHIRExportJobResponse EndStartFHIRExportJob(IAsyncResult asyncResult)
{
return EndInvoke<StartFHIRExportJobResponse>(asyncResult);
}
#endregion
#region StartFHIRImportJob
/// <summary>
/// Begins a FHIR Import job.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartFHIRImportJob service method.</param>
///
/// <returns>The response from the StartFHIRImportJob service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.AccessDeniedException">
/// Access is denied. Your account is not authorized to perform this operation.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.InternalServerException">
/// Unknown error occurs in the service.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ThrottlingException">
/// The user has exceeded their maximum number of allowed calls to the given API.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/StartFHIRImportJob">REST API Reference for StartFHIRImportJob Operation</seealso>
public virtual StartFHIRImportJobResponse StartFHIRImportJob(StartFHIRImportJobRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartFHIRImportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartFHIRImportJobResponseUnmarshaller.Instance;
return Invoke<StartFHIRImportJobResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the StartFHIRImportJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartFHIRImportJob operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartFHIRImportJob
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/StartFHIRImportJob">REST API Reference for StartFHIRImportJob Operation</seealso>
public virtual IAsyncResult BeginStartFHIRImportJob(StartFHIRImportJobRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartFHIRImportJobRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartFHIRImportJobResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the StartFHIRImportJob operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartFHIRImportJob.</param>
///
/// <returns>Returns a StartFHIRImportJobResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/StartFHIRImportJob">REST API Reference for StartFHIRImportJob Operation</seealso>
public virtual StartFHIRImportJobResponse EndStartFHIRImportJob(IAsyncResult asyncResult)
{
return EndInvoke<StartFHIRImportJobResponse>(asyncResult);
}
#endregion
#region TagResource
/// <summary>
/// Adds a user specifed key and value tag to a Data Store.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult)
{
return EndInvoke<TagResourceResponse>(asyncResult);
}
#endregion
#region UntagResource
/// <summary>
/// Removes tags from a Data Store.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by HealthLake.</returns>
/// <exception cref="Amazon.HealthLake.Model.ResourceNotFoundException">
/// The requested Data Store was not found.
/// </exception>
/// <exception cref="Amazon.HealthLake.Model.ValidationException">
/// The user input parameter was invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonHealthLakeClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from HealthLake.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/healthlake-2017-07-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult)
{
return EndInvoke<UntagResourceResponse>(asyncResult);
}
#endregion
}
} | 54.188393 | 175 | 0.673362 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/HealthLake/Generated/_bcl35/AmazonHealthLakeClient.cs | 60,693 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraSystem : MonoBehaviour {
public GameObject target;
public float movementVelocity;
void Update () {
Vector3 targetPos = new Vector3(target.transform.position.x, target.transform.position.y, -10); //Set the distance correctly
transform.position = Vector3.Lerp (transform.position, targetPos, movementVelocity * Time.deltaTime); //Set the camera in atual player
}
}
| 31.533333 | 136 | 0.780127 | [
"Apache-2.0"
] | JustDevGuy/NotAccurateShots | Assets/Scripts/CameraSystem.cs | 475 | C# |
using System.Xml.Linq;
namespace Dovetail.SDK.Bootstrap.Clarify.Metadata
{
public interface IXElementVisitor
{
bool Matches(XElement element, ParsingContext context);
void Visit(XElement element, ParsingContext context);
void ChildrenBound(ParsingContext context);
}
}
| 21.615385 | 57 | 0.793594 | [
"Apache-2.0"
] | DovetailSoftware/dovetail-bootstrap | source/Dovetail.SDK.Bootstrap/Clarify/Metadata/IXElementVisitor.cs | 283 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
using R5T.Lombardy;
using R5T.D0048;
using R5T.D0078;
using R5T.D0079;
using R5T.D0083;
using R5T.D0096;
using R5T.D0096.D003;
using R5T.D0101;
using R5T.D0105;
using R5T.L0017.D001;
using R5T.T0063;
using N004 = R5T.S0030.T003.N004;
namespace R5T.S0030
{
public static partial class IServiceCollectionExtensions
{
/// <summary>
/// Adds the <see cref="O201_AddServiceImplementationMarkerAttributeAndInterface"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO201_AddServiceImplementationMarkerAttributeAndInterface(this IServiceCollection services,
IServiceAction<IProjectRepository> projectRepositoryAction,
IServiceAction<IStringlyTypedPathOperator> stringlyTypedPathOperatorAction,
IServiceAction<IVisualStudioProjectFileOperator> visualStudioProjectFileOperatorAction,
IServiceAction<IVisualStudioProjectFileReferencesProvider> visualStudioProjectFileReferencesProviderAction,
IServiceAction<IVisualStudioSolutionFileOperator> visualStudioSolutionFileOperatorAction)
{
services
.Run(projectRepositoryAction)
.Run(stringlyTypedPathOperatorAction)
.Run(visualStudioProjectFileOperatorAction)
.Run(visualStudioProjectFileReferencesProviderAction)
.Run(visualStudioSolutionFileOperatorAction)
.AddSingleton<O201_AddServiceImplementationMarkerAttributeAndInterface>();
return services;
}
/// <summary>
/// Adds the <see cref="O200_AddServiceDefinitionMarkerAttributeAndInterface"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO200_AddServiceDefinitionMarkerAttributeAndInterface(this IServiceCollection services,
IServiceAction<IProjectRepository> projectRepositoryAction,
IServiceAction<IStringlyTypedPathOperator> stringlyTypedPathOperatorAction,
IServiceAction<IVisualStudioProjectFileOperator> visualStudioProjectFileOperatorAction,
IServiceAction<IVisualStudioProjectFileReferencesProvider> visualStudioProjectFileReferencesProviderAction,
IServiceAction<IVisualStudioSolutionFileOperator> visualStudioSolutionFileOperatorAction)
{
services
.Run(projectRepositoryAction)
.Run(stringlyTypedPathOperatorAction)
.Run(visualStudioProjectFileOperatorAction)
.Run(visualStudioProjectFileReferencesProviderAction)
.Run(visualStudioSolutionFileOperatorAction)
.AddSingleton<O200_AddServiceDefinitionMarkerAttributeAndInterface>();
return services;
}
/// <summary>
/// Adds the <see cref="O106_OutputServiceAddMethodsForProject"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO106_OutputServiceAddMethodsForProject(this IServiceCollection services,
IServiceAction<N004.IClassContextProvider> classContextProviderAction_N004,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IServiceImplementationCodeFilePathsProvider> serviceImplementationCodeFilePathsProviderAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(classContextProviderAction_N004)
.Run(notepadPlusPlusOperatorAction)
.Run(serviceImplementationCodeFilePathsProviderAction)
.Run(serviceRepositoryAction)
.AddSingleton<O106_OutputServiceAddMethodsForProject>();
return services;
}
/// <summary>
/// Adds the <see cref="O105_AddServiceImplementationsToRepository"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO105_AddServiceImplementationsToRepository(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction,
IServiceAction<O105A_IdentifyServiceImplementations> o105A_IdentifyServiceImplementationsAction,
IServiceAction<O105B_AddServiceImplementationsToRepository> o105B_AddServiceImplementationsToRepositoryAction)
{
services
.Run(loggerUnboundAction)
.Run(projectFilePathsProviderAction)
.Run(serviceRepositoryAction)
.Run(o105A_IdentifyServiceImplementationsAction)
.Run(o105B_AddServiceImplementationsToRepositoryAction)
.AddSingleton<O105_AddServiceImplementationsToRepository>();
return services;
}
/// <summary>
/// Adds the <see cref="O105B_AddServiceImplementationsToRepository"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO105B_AddServiceImplementationsToRepository(this IServiceCollection services,
IServiceAction<IHumanOutput> humanOutputAction,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IProjectRepository> projectRepositoryAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(humanOutputAction)
.Run(loggerUnboundAction)
.Run(projectRepositoryAction)
.Run(serviceRepositoryAction)
.AddSingleton<O105B_AddServiceImplementationsToRepository>();
return services;
}
/// <summary>
/// Adds the <see cref="O105A_IdentifyServiceImplementations"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO105A_IdentifyServiceImplementations(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IServiceImplementationCodeFilePathsProvider> serviceImplementationCodeFilePathsProviderAction)
{
services
.Run(loggerUnboundAction)
.Run(serviceImplementationCodeFilePathsProviderAction)
.AddSingleton<O105A_IdentifyServiceImplementations>();
return services;
}
/// <summary>
/// Adds the <see cref="O104_AddDependencyDefinitionsToRepository"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO104_AddDependencyDefinitionsToRepository(this IServiceCollection services,
IServiceAction<IHumanOutput> humanOutputAction,
IServiceAction<IHumanOutputFilePathProvider> humanOutputFilePathProviderAction,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IMainFileContextFilePathsProvider> mainFileContextFilePathsProviderAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IOutputFilePathProvider> outputFilePathProviderAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(humanOutputAction)
.Run(humanOutputFilePathProviderAction)
.Run(loggerUnboundAction)
.Run(mainFileContextFilePathsProviderAction)
.Run(notepadPlusPlusOperatorAction)
.Run(outputFilePathProviderAction)
.Run(serviceRepositoryAction)
.AddSingleton<O104_AddDependencyDefinitionsToRepository>();
return services;
}
/// <summary>
/// Adds the <see cref="O103_AddImplementedDefinitionToRepository"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO103_AddImplementedDefinitionToRepository(this IServiceCollection services,
IServiceAction<IHumanOutput> humanOutputAction,
IServiceAction<IHumanOutputFilePathProvider> humanOutputFilePathProviderAction,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IMainFileContextFilePathsProvider> mainFileContextFilePathsProviderAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IOutputFilePathProvider> outputFilePathProviderAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(humanOutputAction)
.Run(humanOutputFilePathProviderAction)
.Run(loggerUnboundAction)
.Run(mainFileContextFilePathsProviderAction)
.Run(notepadPlusPlusOperatorAction)
.Run(outputFilePathProviderAction)
.Run(serviceRepositoryAction)
.AddSingleton<O103_AddImplementedDefinitionToRepository>();
return services;
}
/// <summary>
/// Adds the <see cref="O102_AddServiceImplementationsToRepository"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO102_AddServiceImplementationsToRepository(this IServiceCollection services,
IServiceAction<IHumanOutput> humanOutputAction,
IServiceAction<IHumanOutputFilePathProvider> humanOutputFilePathProviderAction,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IMainFileContextFilePathsProvider> mainFileContextFilePathsProviderAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IProjectRepository> projectRepositoryAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction,
IServiceAction<O003_IdentifyServiceImplementationsCore> o003_IdentifyServiceImplementationsCoreAction)
{
services
.Run(humanOutputAction)
.Run(humanOutputFilePathProviderAction)
.Run(loggerUnboundAction)
.Run(mainFileContextFilePathsProviderAction)
.Run(notepadPlusPlusOperatorAction)
.Run(projectRepositoryAction)
.Run(serviceRepositoryAction)
.Run(o003_IdentifyServiceImplementationsCoreAction)
.AddSingleton<O102_AddServiceImplementationsToRepository>();
return services;
}
/// <summary>
/// Adds the <see cref="O101_AddServiceDefinitionsToRepository"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO101_AddServiceDefinitionsToRepository(this IServiceCollection services,
IServiceAction<IExecutableDirectoryFilePathProvider> executableDirectoryFilePathProviderAction,
IServiceAction<IHumanOutput> humanOutputAction,
IServiceAction<IHumanOutputFilePathProvider> humanOutputFilePathProviderAction,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IMainFileContextFilePathsProvider> mainFileContextFilePathsProviderAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IProjectRepository> projectRepositoryAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction,
IServiceAction<O001_IdentifyServiceDefinitionsCore> o001_IdentifyServiceDefinitionsCoreAction)
{
services
.Run(executableDirectoryFilePathProviderAction)
.Run(humanOutputAction)
.Run(humanOutputFilePathProviderAction)
.Run(loggerUnboundAction)
.Run(mainFileContextFilePathsProviderAction)
.Run(notepadPlusPlusOperatorAction)
.Run(projectRepositoryAction)
.Run(serviceRepositoryAction)
.Run(o001_IdentifyServiceDefinitionsCoreAction)
.AddSingleton<O101_AddServiceDefinitionsToRepository>();
return services;
}
/// <summary>
/// Adds the <see cref="O100_PerformAllSurveys"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO100_PerformAllSurveys(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<IServiceDefinitionCodeFilePathsProvider> serviceDefinitionCodeFilePathsProviderAction,
IServiceAction<IServiceDefinitionTypeIdentifier> serviceDefinitionTypeIdentifierAction,
IServiceAction<IServiceImplementationCodeFilePathsProvider> serviceImplementationCodeFilePathsProviderAction,
IServiceAction<IServiceImplementationTypeIdentifier> serviceImplementationTypeIdentifierAction,
IServiceAction<O001A_DescribeServiceComponents> o001A_DescribeServiceComponentsAction,
IServiceAction<O002A_DescribePossibleServiceComponents> o002A_DescribePossibleServiceComponentsAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(projectFilePathsProviderAction)
.Run(serviceDefinitionCodeFilePathsProviderAction)
.Run(serviceDefinitionTypeIdentifierAction)
.Run(serviceImplementationCodeFilePathsProviderAction)
.Run(serviceImplementationTypeIdentifierAction)
.Run(o001A_DescribeServiceComponentsAction)
.Run(o002A_DescribePossibleServiceComponentsAction)
.AddSingleton<O100_PerformAllSurveys>();
return services;
}
/// <summary>
/// Adds the <see cref="O010_DescribeAllServiceImplementations"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO010_DescribeAllServiceImplementations(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<IServiceImplementationCodeFilePathsProvider> serviceImplementationCodeFilePathsProviderAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(projectFilePathsProviderAction)
.Run(serviceImplementationCodeFilePathsProviderAction)
.Run(serviceRepositoryAction)
.AddSingleton<O010_DescribeAllServiceImplementations>();
return services;
}
/// <summary>
/// Adds the <see cref="O009a_DescribeAllServiceImplementationsInProject"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO009a_DescribeAllServiceImplementationsInProject(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IServiceImplementationCodeFilePathsProvider> serviceImplementationCodeFilePathsProviderAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(serviceImplementationCodeFilePathsProviderAction)
.Run(serviceRepositoryAction)
.AddSingleton<O009a_DescribeAllServiceImplementationsInProject>();
return services;
}
/// <summary>
/// Adds the <see cref="O009_DescribeServiceImplementationsInFile"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO009_DescribeServiceImplementationsInFile(this IServiceCollection services,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(notepadPlusPlusOperatorAction)
.Run(serviceRepositoryAction)
.AddSingleton<O009_DescribeServiceImplementationsInFile>();
return services;
}
/// <summary>
/// Adds the <see cref="O008_DescribeSingleServiceImplementation"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO008_DescribeSingleServiceImplementation(this IServiceCollection services,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(notepadPlusPlusOperatorAction)
.Run(serviceRepositoryAction)
.AddSingleton<O008_DescribeSingleServiceImplementation>();
return services;
}
/// <summary>
/// Adds the <see cref="O007_IdentifyServiceImplementations"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO007_IdentifyServiceImplementations(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<IServiceImplementationCandidateIdentifier> serviceImplementationCandidateIdentifierAction,
IServiceAction<IServiceImplementationCodeFilePathsProvider> serviceImplementationCodeFilePathsProviderAction,
IServiceAction<Repositories.IServiceRepository> serviceRepositoryAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(projectFilePathsProviderAction)
.Run(serviceImplementationCandidateIdentifierAction)
.Run(serviceImplementationCodeFilePathsProviderAction)
.Run(serviceRepositoryAction)
.AddSingleton<O007_IdentifyServiceImplementations>();
return services;
}
/// <summary>
/// Adds the <see cref="O006_IdentityServiceImplementationsLackingMarkerInterface"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO006_IdentityServiceImplementationsLackingMarkerInterface(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<O001A_DescribeServiceComponents> o001A_DescribeServiceComponentsAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(projectFilePathsProviderAction)
.Run(projectFilePathsProviderAction)
.Run(o001A_DescribeServiceComponentsAction)
.AddSingleton<O006_IdentityServiceImplementationsLackingMarkerInterface>();
return services;
}
/// <summary>
/// Adds the <see cref="O005_IdentityServiceDefinitionsLackingMarkerInterface"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO005_IdentityServiceDefinitionsLackingMarkerInterface(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<O001A_DescribeServiceComponents> o001A_DescribeServiceComponentsAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(projectFilePathsProviderAction)
.Run(projectFilePathsProviderAction)
.Run(o001A_DescribeServiceComponentsAction)
.AddSingleton<O005_IdentityServiceDefinitionsLackingMarkerInterface>();
return services;
}
/// <summary>
/// Adds the <see cref="O004_IdentifyPossibleServiceImplementations"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO004_IdentifyPossibleServiceImplementations(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<O001A_DescribeServiceComponents> o001A_DescribeServiceComponentsAction,
IServiceAction<O002A_DescribePossibleServiceComponents> o002A_DescribePossibleServiceComponentsAction,
IServiceAction<O004_IdentifyPossibleServiceImplementationsCore> o004_IdentifyPossibleServiceImplementationsCoreAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(o001A_DescribeServiceComponentsAction)
.Run(o002A_DescribePossibleServiceComponentsAction)
.Run(o004_IdentifyPossibleServiceImplementationsCoreAction)
.AddSingleton<O004_IdentifyPossibleServiceImplementations>();
return services;
}
/// <summary>
/// Adds the <see cref="O004_IdentifyPossibleServiceImplementationsCore"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO004_IdentifyPossibleServiceImplementationsCore(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction)
{
services
.Run(loggerUnboundAction)
.Run(projectFilePathsProviderAction)
.AddSingleton<O004_IdentifyPossibleServiceImplementationsCore>();
return services;
}
/// <summary>
/// Adds the <see cref="O003_IdentifyServiceImplementations"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO003_IdentifyServiceImplementations(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<O001A_DescribeServiceComponents> o001A_DescribeServiceComponentsAction,
IServiceAction<O003_IdentifyServiceImplementationsCore> o003_IdentifyServiceImplementationsCoreAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(o001A_DescribeServiceComponentsAction)
.Run(o003_IdentifyServiceImplementationsCoreAction)
.AddSingleton<O003_IdentifyServiceImplementations>();
return services;
}
/// <summary>
/// Adds the <see cref="O003_IdentifyServiceImplementationsCore"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO003_IdentifyServiceImplementationsCore(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<IServiceImplementationCodeFilePathsProvider> serviceImplementationCodeFilePathsProviderAction,
IServiceAction<IServiceImplementationTypeIdentifier> serviceImplementationTypeIdentifierAction)
{
services
.Run(loggerUnboundAction)
.Run(projectFilePathsProviderAction)
.Run(serviceImplementationCodeFilePathsProviderAction)
.Run(serviceImplementationTypeIdentifierAction)
.AddSingleton<O003_IdentifyServiceImplementationsCore>();
return services;
}
/// <summary>
/// Adds the <see cref="O002_IdentifyPossibleServiceDefinitions"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO002_IdentifyPossibleServiceDefinitions(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<O001A_DescribeServiceComponents> o001A_DescribeServiceComponentsAction,
IServiceAction<O002A_DescribePossibleServiceComponents> o002A_DescribePossibleServiceComponentsAction,
IServiceAction<O002_IdentifyPossibleServiceDefinitionsCore> o002_IdentifyPossibleServiceDefinitionsCoreAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(o001A_DescribeServiceComponentsAction)
.Run(o002A_DescribePossibleServiceComponentsAction)
.Run(o002_IdentifyPossibleServiceDefinitionsCoreAction)
.AddSingleton<O002_IdentifyPossibleServiceDefinitions>();
return services;
}
/// <summary>
/// Adds the <see cref="O002_IdentifyPossibleServiceDefinitionsCore"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO002_IdentifyPossibleServiceDefinitionsCore(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction)
{
services
.Run(loggerUnboundAction)
.Run(projectFilePathsProviderAction)
.AddSingleton<O002_IdentifyPossibleServiceDefinitionsCore>();
return services;
}
/// <summary>
/// Adds the <see cref="O002A_DescribePossibleServiceComponents"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO002A_DescribePossibleServiceComponents(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction)
{
services
.Run(loggerUnboundAction)
.AddSingleton<O002A_DescribePossibleServiceComponents>();
return services;
}
/// <summary>
/// Adds the <see cref="O001_IdentifyServiceDefinitions"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO001_IdentityServiceDefinitions(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction,
IServiceAction<INotepadPlusPlusOperator> notepadPlusPlusOperatorAction,
IServiceAction<O001_IdentifyServiceDefinitionsCore> o001_IdentityServiceDefinitionsCoreAction,
IServiceAction<O001A_DescribeServiceComponents> o001A_DescribeServiceDefinitionsAction)
{
services
.Run(loggerUnboundAction)
.Run(notepadPlusPlusOperatorAction)
.Run(o001_IdentityServiceDefinitionsCoreAction)
.Run(o001A_DescribeServiceDefinitionsAction)
.AddSingleton<O001_IdentifyServiceDefinitions>();
return services;
}
/// <summary>
/// Adds the <see cref="O001A_DescribeServiceComponents"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO001A_DescribeServiceComponents(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerUnboundAction)
{
services
.Run(loggerUnboundAction)
.AddSingleton<O001A_DescribeServiceComponents>();
return services;
}
/// <summary>
/// Adds the <see cref="O001_IdentifyServiceDefinitionsCore"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO001_IdentityServiceDefinitionsCore(this IServiceCollection services,
IServiceAction<ILoggerUnbound> loggerAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<IServiceDefinitionCodeFilePathsProvider> serviceDefinitionCodeFilePathsProviderAction,
IServiceAction<IServiceDefinitionTypeIdentifier> serviceDefinitionDescriptorProviderAction)
{
services
.Run(loggerAction)
.Run(projectFilePathsProviderAction)
.Run(serviceDefinitionCodeFilePathsProviderAction)
.Run(serviceDefinitionDescriptorProviderAction)
.AddSingleton<O001_IdentifyServiceDefinitionsCore>();
return services;
}
/// <summary>
/// Adds the <see cref="O900_SortExternalServiceComponentDataFiles"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO900_SortExternalServiceComponentDataFiles(this IServiceCollection services)
{
services.AddSingleton<O900_SortExternalServiceComponentDataFiles>();
return services;
}
/// <summary>
/// Adds the <see cref="O999_Scratch"/> operation as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
public static IServiceCollection AddO999_Scratch(this IServiceCollection services,
IServiceAction<IHumanOutput> humanOutputAction,
IServiceAction<ILoggerUnbound> loggerAction,
IServiceAction<IProjectFilePathsProvider> projectFilePathsProviderAction,
IServiceAction<IServiceDefinitionCodeFilePathsProvider> serviceDefinitionCodeFilePathsProviderAction,
IServiceAction<IServiceDefinitionTypeIdentifier> serviceDefinitionDescriptorProviderAction)
{
services
.Run(humanOutputAction)
.Run(loggerAction)
.Run(projectFilePathsProviderAction)
.Run(serviceDefinitionCodeFilePathsProviderAction)
.Run(serviceDefinitionDescriptorProviderAction)
.AddSingleton<O999_Scratch>();
return services;
}
}
} | 52.263844 | 148 | 0.702275 | [
"MIT"
] | SafetyCone/R5T.S0030 | source/R5T.S0030/Code/Extensions/IServiceCollectionExtensions-Operations.cs | 32,090 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// This code was generated by an automated template.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.ARMv8A32.Instructions
{
/// <summary>
/// RsfImm - Reverse Subtract
/// </summary>
/// <seealso cref="Mosa.Platform.ARMv8A32.ARMv8A32Instruction" />
public sealed class RsfImm : ARMv8A32Instruction
{
internal RsfImm()
: base(1, 2)
{
}
public override bool IsCommutative { get { return true; } }
public override void Emit(InstructionNode node, BaseCodeEmitter emitter)
{
System.Diagnostics.Debug.Assert(node.ResultCount == 1);
System.Diagnostics.Debug.Assert(node.OperandCount == 2);
if (node.Operand1.IsCPURegister && node.Operand2.IsCPURegister)
{
emitter.OpcodeEncoder.Append4Bits(GetConditionCode(node.ConditionCode));
emitter.OpcodeEncoder.Append4Bits(0b1110);
emitter.OpcodeEncoder.Append4Bits(0b0011);
emitter.OpcodeEncoder.Append1Bit(0b0);
emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode);
emitter.OpcodeEncoder.Append1Bit(0b0);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append4Bits(0b0001);
emitter.OpcodeEncoder.Append1Bit(node.Result.IsR4 ? 0 : 1);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append1Bit(0b0);
emitter.OpcodeEncoder.Append1Bit(0b1);
emitter.OpcodeEncoder.Append4BitImmediate(node.Operand2);
return;
}
throw new Compiler.Common.Exceptions.CompilerException("Invalid Opcode");
}
}
}
| 32.204082 | 76 | 0.750317 | [
"BSD-3-Clause"
] | Arakis/MOSA-Project | Source/Mosa.Platform.ARMv8A32/Instructions/RsfImm.cs | 1,578 | C# |
using System.Collections.Generic;
using System.Collections;
using System;
namespace UnityEditor.iOS.Xcode.GetSocial
{
class PBXElement
{
protected PBXElement() {}
// convenience methods
public string AsString() { return ((PBXElementString)this).value; }
public PBXElementArray AsArray() { return (PBXElementArray)this; }
public PBXElementDict AsDict() { return (PBXElementDict)this; }
public PBXElement this[string key]
{
get { return AsDict()[key]; }
set { AsDict()[key] = value; }
}
}
class PBXElementString : PBXElement
{
public PBXElementString(string v) { value = v; }
public string value;
}
class PBXElementDict : PBXElement
{
public PBXElementDict() : base() {}
private Dictionary<string, PBXElement> m_PrivateValue = new Dictionary<string, PBXElement>();
public IDictionary<string, PBXElement> values { get { return m_PrivateValue; }}
new public PBXElement this[string key]
{
get {
if (values.ContainsKey(key))
return values[key];
return null;
}
set { this.values[key] = value; }
}
public bool Contains(string key)
{
return values.ContainsKey(key);
}
public void Remove(string key)
{
values.Remove(key);
}
public void SetString(string key, string val)
{
values[key] = new PBXElementString(val);
}
public PBXElementArray CreateArray(string key)
{
var v = new PBXElementArray();
values[key] = v;
return v;
}
public PBXElementDict CreateDict(string key)
{
var v = new PBXElementDict();
values[key] = v;
return v;
}
}
class PBXElementArray : PBXElement
{
public PBXElementArray() : base() {}
public List<PBXElement> values = new List<PBXElement>();
// convenience methods
public void AddString(string val)
{
values.Add(new PBXElementString(val));
}
public PBXElementArray AddArray()
{
var v = new PBXElementArray();
values.Add(v);
return v;
}
public PBXElementDict AddDict()
{
var v = new PBXElementDict();
values.Add(v);
return v;
}
}
} // namespace UnityEditor.iOS.Xcode.GetSocial
| 24.35514 | 101 | 0.540675 | [
"Apache-2.0"
] | MySt1KxSyL3nT/getsocial-capture | demo/sampleapp/Assets/GetSocial/Editor/iOS/xcodeapi/PBX/Elements.cs | 2,606 | C# |
/*
* Copyright 2012-2018 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.Collections.Generic;
using Aerospike.Client;
namespace Aerospike.Demo
{
public class ScanSeries : SyncExample
{
private Dictionary<string, Metrics> setMap = new Dictionary<string, Metrics>();
public ScanSeries(Console console) : base(console)
{
}
/// <summary>
/// Scan all nodes in series and read all records in all sets.
/// </summary>
public override void RunExample(AerospikeClient client, Arguments args)
{
console.Info("Scan series: namespace=" + args.ns + " set=" + args.set);
setMap.Clear();
// Use low scan priority. This will take more time, but it will reduce
// the load on the server.
ScanPolicy policy = new ScanPolicy();
policy.maxRetries = 1;
policy.priority = Priority.LOW;
Node[] nodes = client.Nodes;
DateTime begin = DateTime.Now;
foreach (Node node in nodes)
{
console.Info("Scan node " + node.Name);
client.ScanNode(policy, node, args.ns, args.set, ScanCallback);
foreach (KeyValuePair<string, Metrics> entry in setMap)
{
console.Info("Node " + node.Name + " set " + entry.Key + " count: " + entry.Value.count);
entry.Value.count = 0;
}
}
DateTime end = DateTime.Now;
double seconds = end.Subtract(begin).TotalSeconds;
console.Info("Elapsed time: " + seconds + " seconds");
long total = 0;
foreach (KeyValuePair<string, Metrics> entry in setMap)
{
console.Info("Total set " + entry.Key + " count: " + entry.Value.total);
total += entry.Value.total;
}
console.Info("Grand total: " + total);
double performance = Math.Round((double)total / seconds);
console.Info("Records/second: " + performance);
}
public void ScanCallback(Key key, Record record)
{
Metrics metrics;
if (! setMap.TryGetValue(key.setName, out metrics))
{
metrics = new Metrics();
}
metrics.count++;
metrics.total++;
setMap[key.setName] = metrics;
}
private class Metrics
{
public long count = 0;
public long total = 0;
}
}
}
| 28.354167 | 94 | 0.680015 | [
"MIT"
] | Jac21/aerospike-client-csharp | Framework/AerospikeDemo/ScanSeries.cs | 2,722 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using SoonLearning.Assessment.Player.Data;
using SoonLearning.Assessment.Data;
using System.Reflection;
namespace SoonLearning.Math_Fast.SYSS300.FZLJ
{
public class FZLJDataCreator : DataCreator
{
private static FZLJDataCreator creator;
public static FZLJDataCreator Instance
{
get
{
if (creator == null)
creator = new FZLJDataCreator();
return creator;
}
}
private List<int> questionValueList = new List<int>();
private int currentIndex = 2;
public struct valuesStruct
{
public decimal[] valuesRef; //基准值
public decimal[] values; //所有加数的值
public decimal[] valueList1; //各个加数的值
public decimal[] valueList2; //对应的互补数
public decimal[] errors; //各个加数跟基准数的差
public bool[] signs; //正负号标志
public int number; //加数的个数
public decimal answer; //所有加数的和,即答案
public int[] complementPos; //互为补数对的原下标
public int[] complementList1Pos; //互为补数对的原下标
public int[] complementList2Pos; //互为补数对的原下标
public valuesStruct(int valueSize)
{
valuesRef = new decimal[valueSize];
values = new decimal[valueSize];
valueList1 = new decimal[valueSize];
valueList2 = new decimal[valueSize];
errors = new decimal[valueSize];
signs = new bool[valueSize];
complementPos = new int[valueSize];
complementList1Pos = new int[valueSize];
complementList2Pos = new int[valueSize];
number = 5;
answer = 0;
}
}
public struct valuesCompare
{
public decimal valueRef; //基准值
public decimal[] valuesGT; //大于基准值
public decimal numGT; //大于基准值的个数
public decimal[] valuesLT; //小于基准值
public decimal numLT; //小于基准值的个数
public decimal[] valuesEQ; //等于基准值
public decimal numEQ; //等于基准值的个数
public valuesCompare(int GTSize, int LTSize, int EQSize)
{
valueRef = 50;
valuesGT = new decimal[GTSize];
valuesLT = new decimal[LTSize];
valuesEQ = new decimal[EQSize];
numGT = 0;
numLT = 0;
numEQ = 0;
}
}
protected override void PrepareSectionInfoCollection()
{
this.exerciseTitle = "分组连加法练习";
this.examTitle = "分组连加法测验";
this.flowDocumentFile = "SoonLearning.Math_Fast.SYSS300.FZLJ.FZLJ_Document.xaml";
this.sectionInfoCollection.Add(new SectionValueRangeInfo(QuestionType.MultiChoice,
"单选题:",
"(下面每道题都只有一个选项是正确的)",
5,
100,
1000));
this.sectionInfoCollection.Add(new SectionValueRangeInfo(QuestionType.FillInBlank,
"填空题:",
"(在空格中填入符合条件的数)",
5,
100,
1000));
}
protected override void AppendQuestion(SectionBaseInfo info, Section section)
{
switch (info.QuestionType)
{
case QuestionType.MultiChoice:
this.CreateMCQuestion(info, section);
break;
case QuestionType.FillInBlank:
this.CreateFIBQuestion(info, section);
break;
}
}
private void GetRandomValues1(SectionBaseInfo info,
ref int value1, ref int value2, ref int value3, ref int value4, ref int value5, ref int value6, ref int value7, ref int num, ref int valueAnswer)
{
int minValue = 10;
int maxValue = 100;
if (info is SectionValueRangeInfo)
{
SectionValueRangeInfo rangeInfo = info as SectionValueRangeInfo;
minValue = decimal.ToInt32(rangeInfo.MinValue);
maxValue = decimal.ToInt32(rangeInfo.MaxValue);
}
Random rand = new Random((int)DateTime.Now.Ticks);
num = rand.Next(3, 7 + 1);
int error;
int j = 0;
int sign;
valueAnswer = 0;
while (true)
{
if (j >= num)
break;
value1 = rand.Next(minValue, maxValue + 1);
error = rand.Next(0, 3);
sign = rand.Next(0, 2);
if (sign == 0)
{
value1 += error;
}
else
{
value1 -= error;
}
valueAnswer += value1;
j++;
if (j >= num)
break;
value2 = value1;
error = rand.Next(0, 3);
sign = rand.Next(0, 2);
if (sign == 0)
{
value2 += error;
}
else
{
value2 -= error;
}
valueAnswer += value2;
j++;
if (j >= num)
break;
value3 = value1;
error = rand.Next(0, 3);
sign = rand.Next(0, 2);
if (sign == 0)
{
value3 += error;
}
else
{
value3 -= error;
}
valueAnswer += value3;
j++;
if (j >= num)
break;
value4 = value1;
error = rand.Next(0, 3);
sign = rand.Next(0, 2);
if (sign == 0)
{
value4 += error;
}
else
{
value4 -= error;
}
valueAnswer += value4;
j++;
if (j >= num)
break;
value5 = value1;
error = rand.Next(0, 3);
sign = rand.Next(0, 2);
if (sign == 0)
{
value5 += error;
}
else
{
value5 -= error;
}
valueAnswer += value5;
j++;
if (j >= num)
break;
value6 = value1;
error = rand.Next(0, 3);
sign = rand.Next(0, 2);
if (sign == 0)
{
value6 += error;
}
else
{
value6 -= error;
}
valueAnswer += value6;
j++;
if (j >= num)
break;
value7 = value1;
error = rand.Next(0, 3);
sign = rand.Next(0, 2);
if (sign == 0)
{
value7 += error;
}
else
{
value7 -= error;
}
valueAnswer += value7;
j++;
}
}
private void GetRandomValues(SectionBaseInfo info, ref valuesStruct valueOrg, ref valuesStruct valueABC)
{
int minValue = 10;
int maxValue = 100;
if (info is SectionValueRangeInfo)
{
SectionValueRangeInfo rangeInfo = info as SectionValueRangeInfo;
minValue = decimal.ToInt32(rangeInfo.MinValue);
maxValue = decimal.ToInt32(rangeInfo.MaxValue);
}
Random rand = new Random((int)DateTime.Now.Ticks);
valueABC.number = rand.Next(4, 8 + 1);
valueOrg.number = valueABC.number;
////题干数为偶数个
//valueABC.number >>= 1;
//valueABC.number <<= 1;
int j = 0, i = 0;
valueABC.answer = 0;
int tmp;
int iCom = 1;
int iNum = 0, iRef = 0, iNumList1 = 0, iNumList2 = 0; ;
decimal[] tmpValues = new decimal[valueABC.number];
int[] tmpComplements = new int[valueABC.number];
int tmpNumber = valueABC.number;
//取两两互补数
while (true)
{
valueOrg.values[iNum] = rand.Next(minValue, maxValue + 1);
tmp = decimal.ToInt32(valueOrg.values[iNum]);
tmpValues[iNum] = valueOrg.values[iNum];
valueOrg.complementPos[iNum] = iNum;
tmpComplements[iNum] = iNum;
iNum++;
if (iNum >= valueABC.number)
break;
int complment = 0;
iCom = 1;
while (true)
{
tmp /= 10;
if (tmp > 0 && tmp < 10)
{
break;
}
else
{
iCom++;
}
}
tmp = rand.Next(tmp + 1, 9 + 1);
for (i = 0; i < iCom; i++)
{
tmp *= 10;
}
//mplment = rand.Next(tmp, maxValue + 1);
valueOrg.valuesRef[iRef++] = tmp;
complment = tmp - decimal.ToInt32(valueOrg.values[iNum - 1]);
valueOrg.values[iNum] = complment;
tmpValues[iNum] = complment;
valueOrg.complementPos[iNum] = iNum;
tmpComplements[iNum] = iNum;
iNum++;
if (iNum >= valueABC.number)
break;
}
//随机存放取到的数
//for (i = 0; i < valueABC.number / 2 + valueABC.number % 2; i++)
//{
// valueABC.complementList1Pos[i] = rand.Next(0
// }
//for (i = 0; i < valueABC.number / 2; i++)
//{
//}
//complementList2Pos
for (i = 0; i < valueABC.number; i++)
{
int tmpRand = rand.Next(0, tmpNumber--);
valueABC.values[i] = tmpValues[tmpRand];
valueABC.complementPos[i] = tmpComplements[tmpRand];
//valueABC.complementMatchPos[i] = tmpRand;//存下互补数对的位置(下坐标)
for (j = tmpRand; j < valueABC.number - 1; j++)
{
tmpValues[j] = tmpValues[j + 1];
tmpComplements[j] = tmpComplements[j + 1];
}
valueABC.answer += valueABC.values[i];
}
valueOrg.answer = valueABC.answer;
}
private String SolveSteps(valuesStruct valueOrg, valuesStruct valueMC)
{
valuesCompare valuesRank = new valuesCompare(10, 10, 10);
decimal[] valuesTmp = new decimal[10];
int[] iComplements = new int[10];
int i, j;
//题干
valuesTmp[0] = valueMC.values[0];
string calSteps = valueMC.values[0].ToString();
for (i = 1; i < valueMC.number; i++)
{
calSteps += "+";
calSteps += valueMC.values[i].ToString();
valuesTmp[i] = valueMC.values[i];
}
calSteps += "=";
//解题步骤
//第一步
decimal[] valuesPeek = new decimal[10];
int iPeek = 0;
decimal lastValue;
int iNum = 0, iNum2 = 0, iTmp = 0;
for (j = 0; j < valueMC.number; j++)
{
bool flagPeek = false;
for (i = 0; i < iPeek; i++)
{
if (valueMC.values[j] == valuesPeek[i])
{
flagPeek = true;
break;
}
}
if (flagPeek == true)
{
continue;
}
//找到相对应的互补数
iNum = j;
iComplements[2 * iNum] = valueMC.complementPos[j];
if (iComplements[2 * iNum] == valueMC.number - 1 && valueMC.number % 2 != 0) //最后一个数,且总共的数为奇数个
{
lastValue = valueOrg.values[iComplements[2 * iNum]];
continue;
}
else
{
if (iComplements[2 * iNum] % 2 == 0)
{
iComplements[2 * iNum + 1] = iComplements[2 * iNum] + 1;
}
else
{
iComplements[2 * iNum + 1] = iComplements[2 * iNum] - 1;
}
}
calSteps += "(";
calSteps += valueMC.values[j].ToString(); //互补数A
//valuesPeek[iPeek++] = valueMC.values[j];
calSteps += "+";
valuesTmp[iTmp++] = valueMC.values[j];
calSteps += valueOrg.values[iComplements[2 * iNum + 1]].ToString(); //互补数A'
valuesPeek[iPeek++] = valueOrg.values[iComplements[2 * iNum + 1]];
calSteps += ")";
valuesTmp[iTmp++] = valueOrg.values[iComplements[2 * iNum + 1]];
iNum2 += 2;
if (valueMC.number % 2 == 0)
{
if (iNum2 < valueMC.number)
{
calSteps += "+";
}
}
else
{
if (iNum2 < valueMC.number - 1)
{
calSteps += "+";
}
}
}
if (valueMC.number % 2 != 0)
{
calSteps += "+";
calSteps += valueOrg.values[valueMC.number - 1];
valuesTmp[iTmp++] = valueOrg.values[valueMC.number - 1];
}
//第二步
calSteps += "=";
for (j = 0; j < valueMC.number / 2; j++)
{
decimal _tmp = valuesTmp[2 * j] + valuesTmp[2 * j + 1];
calSteps += _tmp.ToString();
if (j != valueMC.number / 2 - 1)
{
calSteps += "+";
}
}
if (valueMC.number % 2 != 0)
{
calSteps += "+";
calSteps += valuesTmp[valueMC.number - 1];
}
//第三步
calSteps += "=";
calSteps += valueMC.answer.ToString();
calSteps += ",是正确答案。";
return calSteps;
}
private String QuestionText(valuesStruct valueMC)
{
string questionText = "";
for (int i = 0; i < valueMC.number; i++)
{
questionText += valueMC.values[i].ToString();
if (i != valueMC.number - 1)
{
questionText += "+";
}
else
{
questionText += "=";
}
}
return questionText;
}
private MCQuestion CreateMCQuestion(SectionBaseInfo info, Section section)
{
valuesStruct valueOrg = new valuesStruct(10); //原始产生的值
valuesStruct valueMC = new valuesStruct(10); //题干展示的值
//随即获得数值
this.GetRandomValues(info, ref valueOrg, ref valueMC);
questionValueList.Add((decimal.ToInt32(valueMC.values[0])));
//生产题干文本
string questionText = QuestionText(valueMC);
MCQuestion mcQuestion = ObjectCreator.CreateMCQuestion((content) =>
{
content.Content = questionText;
content.ContentType = ContentType.Text;
return;
},
() =>
{
List<QuestionOption> optionList = new List<QuestionOption>();
int valueLst = (decimal.ToInt32(valueMC.answer)) - 30, valueMst = (decimal.ToInt32(valueMC.answer)) + 30;
if (valueLst - 30 <= 1)
{
valueLst = 1;
}
foreach (QuestionOption option in ObjectCreator.CreateDecimalOptions(
4, valueLst, valueMst, false, (c => (c == decimal.ToInt32(valueMC.answer))), decimal.ToInt32(valueMC.answer)))
optionList.Add(option);
return optionList;
}
);
StringBuilder strBuilder = new StringBuilder();
//解题步骤
string Steps = SolveSteps(valueOrg, valueMC);
strBuilder.AppendLine(Steps);
mcQuestion.Solution.Content = strBuilder.ToString();
section.QuestionCollection.Add(mcQuestion);
return mcQuestion;
}
private void CreateFIBQuestion(SectionBaseInfo info, Section section)
{
valuesStruct valueOrg = new valuesStruct(10); //原始产生的值
valuesStruct valueMC = new valuesStruct(10); //题干展示的值
//随即获得数值
this.GetRandomValues(info, ref valueOrg, ref valueMC);
//生产题干文本
string questionText = QuestionText(valueMC);
FIBQuestion fibQuestion = new FIBQuestion();
fibQuestion.Content.Content = questionText;
fibQuestion.Content.ContentType = ContentType.Text;
section.QuestionCollection.Add(fibQuestion);
QuestionBlank blank = new QuestionBlank();
QuestionContent blankContent = new QuestionContent();
blankContent.Content = valueMC.answer.ToString();
blankContent.ContentType = ContentType.Text;
blank.ReferenceAnswerList.Add(blankContent);
fibQuestion.QuestionBlankCollection.Add(blank);
fibQuestion.Content.Content += blank.PlaceHolder;
StringBuilder strBuilder = new StringBuilder();
//解题步骤
string Steps = SolveSteps(valueOrg, valueMC);
strBuilder.AppendLine(Steps);
fibQuestion.Solution.Content = strBuilder.ToString();
}
private string CreateSolution(int divValue)
{
if (divValue == 2)
{
return "";
}
return string.Empty;
}
public FZLJDataCreator()
{
}
}
}
| 31.434211 | 157 | 0.430096 | [
"MIT"
] | LigangSun/AppCenter | source/Apps/Math_Fast_SYSS300/1-10/SoonLearning.Math_Fast.SYSS300.FZLJ/FZLJ_DataCreator.cs | 19,742 | C# |
using System;
using Akka.Actor;
using Akka.Event;
using TIK.Core.Application.Messaging;
namespace TIK.Applications.Online.BackLogs
{
public class BackLogsActor : ReceiveActor
{
private readonly ILoggingAdapter _logger = Context.GetLogger();
private IActorRef JobActor { get; }
public BackLogsActor(IActorRef jobActor)
{
this.JobActor = jobActor;
ReceiveAny(m => {
if (m is MessageWithMemberId)
{
var envelope = m as MessageWithMemberId;
var backLogActor = Context.Child(envelope.MemberId.ToString()) is Nobody ?
Context.ActorOf(BackLogActor.Props(this.JobActor), envelope.MemberId.ToString()) :
Context.Child(envelope.MemberId.ToString());
backLogActor.Forward(m);
}
});
}
public static Props Props(IActorRef jobsActor)
{
return Akka.Actor.Props.Create(() => new BackLogsActor(jobsActor));
}
#region Lifecycle hooks
protected override void PreStart()
{
_logger.Debug("BackLogsActor PreStart");
}
protected override void PostStop()
{
_logger.Debug("BackLogsActor PostStop");
}
protected override void PreRestart(Exception reason, object message)
{
_logger.Debug("BackLogsActor PreRestart because {Reason}", reason);
base.PreRestart(reason, message);
}
protected override void PostRestart(Exception reason)
{
_logger.Debug("BackLogsActor PostRestart because {Reason}", reason);
base.PostRestart(reason);
}
#endregion
}
}
| 29.190476 | 127 | 0.564437 | [
"MIT"
] | sripirom/T-I-K | TIK/Applications/Online/BackLogs/BackLogsActor.cs | 1,841 | C# |
//Released under the MIT License.
//
//Copyright (c) 2018 Ntreev Soft co., Ltd.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
//rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
//persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
//Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using Ntreev.Library.ObjectModel;
using Ntreev.Crema.ServiceModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using Ntreev.Crema.Services.UserService;
using System.Collections.Specialized;
namespace Ntreev.Crema.Services.Users
{
class UserCategoryCollection : CategoryContainer<User, UserCategory, UserCollection, UserCategoryCollection, UserContext>,
IUserCategoryCollection
{
private ItemsCreatedEventHandler<IUserCategory> categoriesCreated;
private ItemsRenamedEventHandler<IUserCategory> categoriesRenamed;
private ItemsMovedEventHandler<IUserCategory> categoriesMoved;
private ItemsDeletedEventHandler<IUserCategory> categoriesDeleted;
public UserCategoryCollection()
{
}
public UserCategory AddNew(Authentication authentication, string name, string parentPath)
{
this.Dispatcher.VerifyAccess();
var categoryName = new CategoryName(parentPath, name);
var result = this.Context.Service.NewUserCategory(categoryName);
result.Validate(authentication);
var category = this.BaseAddNew(name, parentPath, authentication);
this.InvokeCategoriesCreatedEvent(authentication, new UserCategory[] { category });
return category;
}
public void InvokeCategoriesCreatedEvent(Authentication authentication, UserCategory[] categories)
{
var args = categories.Select(item => (object)null).ToArray();
var eventLog = EventLogBuilder.BuildMany(authentication, this, nameof(InvokeCategoriesCreatedEvent), categories);
var comment = EventMessageBuilder.CreateUserCategory(authentication, categories);
this.CremaHost.Debug(eventLog);
this.CremaHost.Info(comment);
this.OnCategoriesCreated(new ItemsCreatedEventArgs<IUserCategory>(authentication, categories, args));
this.Context.InvokeItemsCreatedEvent(authentication, categories, null);
}
public void InvokeCategoriesRenamedEvent(Authentication authentication, UserCategory[] categories, string[] oldNames, string[] oldPaths)
{
var eventLog = EventLogBuilder.BuildMany(authentication, this, nameof(InvokeCategoriesRenamedEvent), categories, oldNames, oldPaths);
var comment = EventMessageBuilder.RenameUserCategory(authentication, categories, oldNames);
this.CremaHost.Debug(eventLog);
this.CremaHost.Info(comment);
this.OnCategoriesRenamed(new ItemsRenamedEventArgs<IUserCategory>(authentication, categories, oldNames, oldPaths));
this.Context.InvokeItemsRenamedEvent(authentication, categories, oldNames, oldPaths);
}
public void InvokeCategoriesMovedEvent(Authentication authentication, UserCategory[] categories, string[] oldPaths, string[] oldParentPaths)
{
var eventLog = EventLogBuilder.BuildMany(authentication, this, nameof(InvokeCategoriesMovedEvent), categories, oldPaths, oldParentPaths);
var comment = EventMessageBuilder.MoveUserCategory(authentication, categories, oldParentPaths);
this.CremaHost.Debug(eventLog);
this.CremaHost.Info(comment);
this.OnCategoriesMoved(new ItemsMovedEventArgs<IUserCategory>(authentication, categories, oldPaths, oldParentPaths));
this.Context.InvokeItemsMovedEvent(authentication, categories, oldPaths, oldParentPaths);
}
public void InvokeCategoriesDeletedEvent(Authentication authentication, UserCategory[] categories, string[] categoryPaths)
{
var eventLog = EventLogBuilder.BuildMany(authentication, this, nameof(InvokeCategoriesDeletedEvent), categoryPaths);
var comment = EventMessageBuilder.DeleteUserCategory(authentication, categories);
this.CremaHost.Debug(eventLog);
this.CremaHost.Info(comment);
this.OnCategoriesDeleted(new ItemsDeletedEventArgs<IUserCategory>(authentication, categories, categoryPaths));
this.Context.InvokeItemsDeleteEvent(authentication, categories, categoryPaths);
}
public IUserService Service
{
get { return this.Context.Service; }
}
public CremaHost CremaHost
{
get { return this.Context.CremaHost; }
}
public CremaDispatcher Dispatcher
{
get { return this.CremaHost.Dispatcher; }
}
public new int Count
{
get
{
this.Dispatcher.VerifyAccess();
return base.Count;
}
}
public event ItemsCreatedEventHandler<IUserCategory> CategoriesCreated
{
add
{
this.Dispatcher.VerifyAccess();
this.categoriesCreated += value;
}
remove
{
this.Dispatcher.VerifyAccess();
this.categoriesCreated -= value;
}
}
public event ItemsRenamedEventHandler<IUserCategory> CategoriesRenamed
{
add
{
this.Dispatcher.VerifyAccess();
this.categoriesRenamed += value;
}
remove
{
this.Dispatcher.VerifyAccess();
this.categoriesRenamed -= value;
}
}
public event ItemsMovedEventHandler<IUserCategory> CategoriesMoved
{
add
{
this.Dispatcher.VerifyAccess();
this.categoriesMoved += value;
}
remove
{
this.Dispatcher.VerifyAccess();
this.categoriesMoved -= value;
}
}
public event ItemsDeletedEventHandler<IUserCategory> CategoriesDeleted
{
add
{
this.Dispatcher.VerifyAccess();
this.categoriesDeleted += value;
}
remove
{
this.Dispatcher.VerifyAccess();
this.categoriesDeleted -= value;
}
}
public new event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
this.Dispatcher.VerifyAccess();
base.CollectionChanged += value;
}
remove
{
this.Dispatcher.VerifyAccess();
base.CollectionChanged -= value;
}
}
protected virtual void OnCategoriesCreated(ItemsCreatedEventArgs<IUserCategory> e)
{
this.categoriesCreated?.Invoke(this, e);
}
protected virtual void OnCategoriesRenamed(ItemsRenamedEventArgs<IUserCategory> e)
{
this.categoriesRenamed?.Invoke(this, e);
}
protected virtual void OnCategoriesMoved(ItemsMovedEventArgs<IUserCategory> e)
{
this.categoriesMoved?.Invoke(this, e);
}
protected virtual void OnCategoriesDeleted(ItemsDeletedEventArgs<IUserCategory> e)
{
this.categoriesDeleted?.Invoke(this, e);
}
#region IUserCategoryCollection
bool IUserCategoryCollection.Contains(string categoryPath)
{
this.Dispatcher.VerifyAccess();
return this.Contains(categoryPath);
}
IUserCategory IUserCategoryCollection.Root
{
get
{
this.Dispatcher.VerifyAccess();
return this.Root;
}
}
IUserCategory IUserCategoryCollection.this[string categoryPath]
{
get
{
this.Dispatcher.VerifyAccess();
return this[categoryPath];
}
}
IEnumerator<IUserCategory> IEnumerable<IUserCategory>.GetEnumerator()
{
this.Dispatcher.VerifyAccess();
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
this.Dispatcher.VerifyAccess();
return this.GetEnumerator();
}
#endregion
#region IServiceProvider
object IServiceProvider.GetService(System.Type serviceType)
{
return (this.Context as IUserContext).GetService(serviceType);
}
#endregion
}
}
| 37.421456 | 149 | 0.637145 | [
"MIT"
] | NtreevSoft/Crema | client/Ntreev.Crema.Services/Users/UserCategoryCollection.cs | 9,769 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Kamishibai.Wpf.MaterialDesignThemes.Demo
{
/// <summary>
/// UserDialog.xaml の相互作用ロジック
/// </summary>
public partial class UserDialog : UserControl
{
public UserDialog()
{
InitializeComponent();
}
}
}
| 22.586207 | 50 | 0.722137 | [
"MIT"
] | nuitsjp/KAMISHIBAI | Source/Kamishibai.Wpf.MaterialDesignThemes.Demo/UserDialog.xaml.cs | 675 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Microsoft.Owin.Security.OAuth;
using Owin;
using TechPortal.Data.Client.Providers;
using TechPortal.Data.Client.Models;
namespace TechPortal.Data.Client
{
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
}
| 40.085714 | 125 | 0.649323 | [
"MIT"
] | gmckin/TechPortal | TechPortal.Data.Client/App_Start/Startup.Auth.cs | 2,808 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Composition.Hosting;
using System.Composition.Hosting.Core;
using System.Composition.UnitTests.Util;
using System.Composition.Runtime;
using Xunit;
namespace System.Composition.UnitTests
{
public class CircularityTests : ContainerTests
{
public interface IA { }
[Export, Shared]
public class BLazy
{
public Lazy<IA> A;
[ImportingConstructor]
public BLazy(Lazy<IA> ia)
{
A = ia;
}
}
[Export(typeof(IA))]
public class ACircular : IA
{
public BLazy B;
[ImportingConstructor]
public ACircular(BLazy b)
{
B = b;
}
}
[Export, Shared]
public class PropertyPropertyA
{
[Import]
public PropertyPropertyB B { get; set; }
}
[Export]
public class PropertyPropertyB
{
[Import]
public PropertyPropertyA A { get; set; }
}
[Export]
public class ConstructorPropertyA
{
[Import]
public ConstructorPropertyB B { get; set; }
}
[Export, Shared]
public class ConstructorPropertyB
{
[ImportingConstructor]
public ConstructorPropertyB(ConstructorPropertyA a)
{
A = a;
}
public ConstructorPropertyA A { get; private set; }
}
public class CircularM
{
public string Name { get; set; }
}
[Export, ExportMetadata("Name", "A")]
public class MetadataCircularityA
{
[Import]
public Lazy<MetadataCircularityB, CircularM> B { get; set; }
}
[Export, ExportMetadata("Name", "B"), Shared]
public class MetadataCircularityB
{
[Import]
public Lazy<MetadataCircularityA, CircularM> A { get; set; }
}
[Export, Shared]
public class NonPrereqSelfDependency
{
[Import]
public NonPrereqSelfDependency Self { get; set; }
}
[Export]
public class PrDepA
{
[ImportingConstructor]
public PrDepA(PrDepB b) { }
}
[Export]
public class PrDepB
{
[ImportingConstructor]
public PrDepB(PrDepA a) { }
}
[Fact]
public void CanHandleDefinitionCircularity()
{
var cc = CreateContainer(typeof(ACircular), typeof(BLazy));
var x = cc.GetExport<BLazy>();
Assert.IsAssignableFrom<ACircular>(x.A.Value);
Assert.IsAssignableFrom<BLazy>(((ACircular)x.A.Value).B);
}
[Fact]
public void CanHandleDefinitionCircularity2()
{
var cc = CreateContainer(typeof(ACircular), typeof(BLazy));
var x = cc.GetExport<IA>();
Assert.IsAssignableFrom<BLazy>(((ACircular)((ACircular)x).B.A.Value).B);
}
[Fact]
public void HandlesPropertyPropertyCircularity()
{
var cc = CreateContainer(typeof(PropertyPropertyA), typeof(PropertyPropertyB));
var a = cc.GetExport<PropertyPropertyA>();
Assert.Same(a.B.A, a);
}
[Fact]
public void HandlesPropertyPropertyCircularityReversed()
{
var cc = CreateContainer(typeof(PropertyPropertyA), typeof(PropertyPropertyB));
var b = cc.GetExport<PropertyPropertyB>();
Assert.Same(b.A.B, b.A.B.A.B);
}
[Fact]
public void HandlesConstructorPropertyCircularity()
{
var cc = CreateContainer(typeof(ConstructorPropertyA), typeof(ConstructorPropertyB));
var a = cc.GetExport<ConstructorPropertyA>();
Assert.Same(a.B.A.B.A, a.B.A);
}
[Fact]
public void HandlesConstructorPropertyCircularityReversed()
{
var cc = CreateContainer(typeof(ConstructorPropertyA), typeof(ConstructorPropertyB));
var b = cc.GetExport<ConstructorPropertyB>();
Assert.Same(b, b.A.B);
}
[Fact]
public void HandlesMetadataCircularity()
{
var cc = CreateContainer(typeof(MetadataCircularityA), typeof(MetadataCircularityB));
var a = cc.GetExport<MetadataCircularityA>();
Assert.Equal("B", a.B.Metadata.Name);
Assert.Equal("A", a.B.Value.A.Metadata.Name);
}
[Fact]
public void SharedPartCanHaveNonPrereqDependencyOnSelf()
{
var cc = CreateContainer(typeof(NonPrereqSelfDependency));
var npsd = cc.GetExport<NonPrereqSelfDependency>();
Assert.Same(npsd, npsd.Self);
}
[Fact]
public void PrerequisiteCircularitiesAreDetected()
{
var cc = CreateContainer(typeof(PrDepA), typeof(PrDepB));
var x = Assert.Throws<CompositionFailedException>(
() =>
{
cc.GetExport<PrDepA>();
}
);
}
}
}
| 27.688442 | 97 | 0.54882 | [
"MIT"
] | belav/runtime | src/libraries/System.Composition/tests/CircularityTests.cs | 5,510 | C# |
using System.IO;
using System.IO.Compression;
using System.Text;
using Azure.Storage.Blobs;
#pragma warning disable CS1591
namespace Frends.Community.Azure.Blob
{
public class Utils
{
public static BlobContainerClient GetBlobContainer(string connectionString, string containerName)
{
// initialize azure account
var blobServiceClient = new BlobServiceClient(connectionString);
// Fetch the container client
return blobServiceClient.GetBlobContainerClient(containerName);
}
public static string GetRenamedFileName(string fileName, string directory)
{
// if fileName is available, just return that
if (!File.Exists(Path.Combine(directory, fileName)))
return fileName;
var index = 1;
var name = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
// loop until available indexed filename found
while (File.Exists(Path.Combine(directory, $"{name}({index}){extension}"))) index++;
return $"{name}({index}){extension}";
}
/// <summary>
/// Gets correct stream object. Does not always dispose, so use using.
/// </summary>
/// <param name="compress"></param>
/// <param name="file"></param>
/// <param name="fromString"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static Stream GetStream(bool compress, bool fromString, Encoding encoding, FileInfo file)
{
var fileStream = File.OpenRead(file.FullName);
if (!compress && !fromString)
return fileStream; // as uncompressed binary
byte[] bytes;
if (!compress)
{
using (var reader = new StreamReader(fileStream, encoding))
{
bytes = encoding.GetBytes(reader.ReadToEnd());
}
return new MemoryStream(bytes); // as uncompressed string
}
using (var outStream = new MemoryStream())
{
using (var gzip = new GZipStream(outStream, CompressionMode.Compress))
{
if (!fromString)
fileStream.CopyTo(gzip); // as compressed binary
else
using (var reader = new StreamReader(fileStream, encoding))
{
var content = reader.ReadToEnd();
using (var encodedMemory = new MemoryStream(encoding.GetBytes(content)))
{
encodedMemory.CopyTo(gzip); // as compressed string
}
}
}
bytes = outStream.ToArray();
}
fileStream.Dispose();
var memStream = new MemoryStream(bytes);
return memStream;
}
}
} | 36.341176 | 105 | 0.534153 | [
"MIT"
] | CommunityHiQ/Frends.Community.Azure.Blob | Frends.Community.Azure.Blob/Utils.cs | 3,091 | C# |
// 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.
//
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Author:
// Rolf Bjarne Kvinge (RKvinge@novell.com)
//
#if NET_2_0
using NUnit.Framework;
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections;
namespace MonoTests.System.Windows.Forms
{
[TestFixture]
public class DataGridViewTextBoxColumnTest : TestHelper
{
[Test]
public void InitialValues ()
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn ();
Assert.AreEqual ("DataGridViewTextBoxColumn { Name=, Index=-1 }", col.ToString (), "T3");
Assert.AreEqual ("DataGridViewTextBoxColumn", col.GetType ().Name, "G2");
Assert.AreEqual (DataGridViewAutoSizeColumnMode.NotSet, col.AutoSizeMode, "#A col.AutoSizeMode");
Assert.IsNotNull (col.CellTemplate, "#A col.CellTemplate");
Assert.IsNotNull (col.CellType, "#A col.CellType");
Assert.IsNull (col.ContextMenuStrip, "#A col.ContextMenuStrip");
Assert.IsNull (col.DataGridView, "#A col.DataGridView");
Assert.AreEqual (@"", col.DataPropertyName, "#A col.DataPropertyName");
Assert.IsNotNull (col.DefaultCellStyle, "#A col.DefaultCellStyle");
Assert.IsNotNull (col.DefaultHeaderCellType, "#A col.DefaultHeaderCellType");
Assert.AreEqual (false, col.Displayed, "#A col.Displayed");
Assert.AreEqual (-1, col.DisplayIndex, "#A col.DisplayIndex");
Assert.AreEqual (0, col.DividerWidth, "#A col.DividerWidth");
Assert.AreEqual (100, col.FillWeight, "#A col.FillWeight");
Assert.AreEqual (false, col.Frozen, "#A col.Frozen");
Assert.AreEqual (true, col.HasDefaultCellStyle, "#A col.HasDefaultCellStyle");
Assert.IsNotNull (col.HeaderCell, "#A col.HeaderCell");
Assert.AreEqual (@"", col.HeaderText, "#A col.HeaderText");
Assert.AreEqual (-1, col.Index, "#A col.Index");
Assert.AreEqual (DataGridViewAutoSizeColumnMode.NotSet, col.InheritedAutoSizeMode, "#A col.InheritedAutoSizeMode");
Assert.IsNotNull (col.InheritedStyle, "#A col.InheritedStyle");
Assert.AreEqual (false, col.IsDataBound, "#A col.IsDataBound");
Assert.AreEqual (32767, col.MaxInputLength, "#A col.MaxInputLength");
Assert.AreEqual (5, col.MinimumWidth, "#A col.MinimumWidth");
Assert.AreEqual (@"", col.Name, "#A col.Name");
Assert.AreEqual (false, col.ReadOnly, "#A col.ReadOnly");
Assert.AreEqual (DataGridViewTriState.NotSet, col.Resizable, "#A col.Resizable");
Assert.AreEqual (false, col.Selected, "#A col.Selected");
Assert.IsNull (col.Site, "#A col.Site");
Assert.AreEqual (DataGridViewColumnSortMode.Automatic, col.SortMode, "#A col.SortMode");
Assert.AreEqual (DataGridViewElementStates.Visible, col.State, "#A col.State");
Assert.IsNull (col.Tag, "#A col.Tag");
Assert.AreEqual (@"", col.ToolTipText, "#A col.ToolTipText");
Assert.IsNull (col.ValueType, "#A col.ValueType");
Assert.AreEqual (true, col.Visible, "#A col.Visible");
Assert.AreEqual (100, col.Width, "#A col.Width");
}
}
}
#endif | 47.209302 | 118 | 0.732266 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/Managed.Windows.Forms/Test/System.Windows.Forms/DataGridViewTextBoxColumnTest.cs | 4,060 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Threading;
using log4net;
using log4net.Appender;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Amib.Threading;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.Web;
namespace OpenSim.Framework
{
[Flags]
public enum PermissionMask : uint
{
None = 0,
// folded perms
FoldedTransfer = 1,
FoldedModify = 1 << 1,
FoldedCopy = 1 << 2,
FoldedExport = 1 << 3,
// DO NOT USE THIS FOR NEW WORK. IT IS DEPRECATED AND
// EXISTS ONLY TO REACT TO EXISTING OBJECTS HAVING IT.
// NEW CODE SHOULD NEVER SET THIS BIT!
// Use InventoryItemFlags.ObjectSlamPerm in the Flags field of
// this legacy slam bit. It comes from prior incomplete
// understanding of the code and the prohibition on
// reading viewer code that used to be in place.
Slam = (1 << 4),
FoldedMask = 0x0f,
FoldingShift = 13 , // number of bit shifts from normal perm to folded or back (same as Transfer shift below)
// when doing as a block
Transfer = 1 << 13, // 0x02000
Modify = 1 << 14, // 0x04000
Copy = 1 << 15, // 0x08000
Export = 1 << 16, // 0x10000
Move = 1 << 19, // 0x80000
Damage = 1 << 20, // 0x100000 does not seem to be in use
// All does not contain Export, which is special and must be
// explicitly given
All = 0x8e000,
AllAndExport = 0x9e000,
AllAndExportNoMod = 0x9a000,
AllEffective = 0x9e000,
UnfoldedMask = 0x1e000
}
/// <summary>
/// The method used by Util.FireAndForget for asynchronously firing events
/// </summary>
/// <remarks>
/// None is used to execute the method in the same thread that made the call. It should only be used by regression
/// test code that relies on predictable event ordering.
/// RegressionTest is used by regression tests. It fires the call synchronously and does not catch any exceptions.
/// </remarks>
public enum FireAndForgetMethod
{
None,
RegressionTest,
QueueUserWorkItem,
SmartThreadPool,
Thread
}
/// <summary>
/// Class for delivering SmartThreadPool statistical information
/// </summary>
/// <remarks>
/// We do it this way so that we do not directly expose STP.
/// </remarks>
public class STPInfo
{
public string Name { get; set; }
public STPStartInfo STPStartInfo { get; set; }
public WIGStartInfo WIGStartInfo { get; set; }
public bool IsIdle { get; set; }
public bool IsShuttingDown { get; set; }
public int MaxThreads { get; set; }
public int MinThreads { get; set; }
public int InUseThreads { get; set; }
public int ActiveThreads { get; set; }
public int WaitingCallbacks { get; set; }
public int MaxConcurrentWorkItems { get; set; }
}
/// <summary>
/// Miscellaneous utility functions
/// </summary>
public static class Util
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Log-level for the thread pool:
/// 0 = no logging
/// 1 = only first line of stack trace; don't log common threads
/// 2 = full stack trace; don't log common threads
/// 3 = full stack trace, including common threads
/// </summary>
public static int LogThreadPool { get; set; }
public static bool LogOverloads { get; set; }
public static readonly int MAX_THREADPOOL_LEVEL = 3;
public static double TimeStampClockPeriodMS;
public static double TimeStampClockPeriod;
static Util()
{
LogThreadPool = 0;
LogOverloads = true;
TimeStampClockPeriod = 1.0D/ (double)Stopwatch.Frequency;
TimeStampClockPeriodMS = 1e3 * TimeStampClockPeriod;
m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS,6,MidpointRounding.AwayFromZero));
}
private static uint nextXferID = 5000;
private static Random randomClass = new ThreadSafeRandom();
// Get a list of invalid file characters (OS dependent)
private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
private static object XferLock = new object();
/// <summary>
/// Thread pool used for Util.FireAndForget if FireAndForgetMethod.SmartThreadPool is used
/// </summary>
private static SmartThreadPool m_ThreadPool;
// Watchdog timer that aborts threads that have timed-out
private static Timer m_threadPoolWatchdog;
// Unix-epoch starts at January 1st 1970, 00:00:00 UTC. And all our times in the server are (or at least should be) in UTC.
public static readonly DateTime UnixEpoch =
DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
private static readonly string rawUUIDPattern
= "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));
public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;
public static bool IsPlatformMono
{
get { return Type.GetType("Mono.Runtime") != null; }
}
/// <summary>
/// Gets the name of the directory where the current running executable
/// is located
/// </summary>
/// <returns>Filesystem path to the directory containing the current
/// executable</returns>
public static string ExecutingDirectory()
{
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
/// <summary>
/// Linear interpolates B<->C using percent A
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <returns></returns>
public static double lerp(double a, double b, double c)
{
return (b*a) + (c*(1 - a));
}
/// <summary>
/// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
/// Layout:
/// A B
/// C D
/// A<->C = Y
/// C<->D = X
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="d"></param>
/// <returns></returns>
public static double lerp2D(double x, double y, double a, double b, double c, double d)
{
return lerp(y, lerp(x, a, b), lerp(x, c, d));
}
public static Encoding UTF8 = Encoding.UTF8;
public static Encoding UTF8NoBomEncoding = new UTF8Encoding(false);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static byte[] UTF8Getbytes(string s)
{
return UTF8.GetBytes(s);
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static byte[] UTF8NBGetbytes(string s)
{
return UTF8NoBomEncoding.GetBytes(s);
}
/// <value>
/// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
/// </value>
public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
#region Vector Equations
/// <summary>
/// Get the distance between two 3d vectors
/// </summary>
/// <param name="a">A 3d vector</param>
/// <param name="b">A 3d vector</param>
/// <returns>The distance between the two vectors</returns>
public static double GetDistanceTo(Vector3 a, Vector3 b)
{
return Vector3.Distance(a,b);
}
/// <summary>
/// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="amount"></param>
/// <returns></returns>
public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
{
return Vector3.DistanceSquared(a,b) < (amount * amount);
}
/// <summary>
/// Get the magnitude of a 3d vector
/// </summary>
/// <param name="a">A 3d vector</param>
/// <returns>The magnitude of the vector</returns>
public static double GetMagnitude(Vector3 a)
{
return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
}
/// <summary>
/// Get a normalized form of a 3d vector
/// </summary>
/// <param name="a">A 3d vector</param>
/// <returns>A new vector which is normalized form of the vector</returns>
public static Vector3 GetNormalizedVector(Vector3 a)
{
Vector3 v = new Vector3(a.X, a.Y, a.Z);
v.Normalize();
return v;
}
/// <summary>
/// Returns if a vector is a zero vector (has all zero components)
/// </summary>
/// <returns></returns>
public static bool IsZeroVector(Vector3 v)
{
if (v.X == 0 && v.Y == 0 && v.Z == 0)
{
return true;
}
return false;
}
# endregion
public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
{
float s;
float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
if (tr >= 1.0)
{
s = (float) (0.5 / Math.Sqrt(tr));
return new Quaternion(
(left.Z - up.Y) * s,
(up.X - fwd.Z) * s,
(fwd.Y - left.X) * s,
(float) 0.25 / s);
}
else
{
float max = (left.Y > up.Z) ? left.Y : up.Z;
if (max < fwd.X)
{
s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
float x = (float) (s * 0.5);
s = (float) (0.5 / s);
return new Quaternion(
x,
(fwd.Y + left.X) * s,
(up.X + fwd.Z) * s,
(left.Z - up.Y) * s);
}
else if (max == left.Y)
{
s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
float y = (float) (s * 0.5);
s = (float) (0.5 / s);
return new Quaternion(
(fwd.Y + left.X) * s,
y,
(left.Z + up.Y) * s,
(up.X - fwd.Z) * s);
}
else
{
s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
float z = (float) (s * 0.5);
s = (float) (0.5 / s);
return new Quaternion(
(up.X + fwd.Z) * s,
(left.Z + up.Y) * s,
z,
(fwd.Y - left.X) * s);
}
}
}
public static Random RandomClass
{
get { return randomClass; }
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ulong UIntsToLong(uint X, uint Y)
{
return ((ulong)X << 32) | (ulong)Y;
}
// Regions are identified with a 'handle' made up of its world coordinates packed into a ulong.
// Region handles are based on the coordinate of the region corner with lower X and Y
// var regions need more work than this to get that right corner from a generic world position
// this corner must be on a grid point
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ulong RegionWorldLocToHandle(uint X, uint Y)
{
ulong handle = X & 0xffffff00; // make sure it matchs grid coord points.
handle <<= 32; // to higher half
handle |= (Y & 0xffffff00);
return handle;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static ulong RegionGridLocToHandle(uint X, uint Y)
{
ulong handle = X;
handle <<= 40; // shift to higher half and mult by 256)
handle |= (Y << 8); // mult by 256)
return handle;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static void RegionHandleToWorldLoc(ulong handle, out uint X, out uint Y)
{
X = (uint)(handle >> 32);
Y = (uint)(handle & 0xfffffffful);
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static void RegionHandleToRegionLoc(ulong handle, out uint X, out uint Y)
{
X = (uint)(handle >> 40) & 0x00ffffffu; // bring from higher half, divide by 256 and clean
Y = (uint)(handle >> 8) & 0x00ffffffu; // divide by 256 and clean
// if you trust the uint cast then the clean can be removed.
}
// A region location can be 'world coordinates' (meters) or 'region grid coordinates'
// grid coordinates have a fixed step of 256m as defined by viewers
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static uint WorldToRegionLoc(uint worldCoord)
{
return worldCoord >> 8;
}
// Convert a region's 'region grid coordinate' to its 'world coordinate'.
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static uint RegionToWorldLoc(uint regionCoord)
{
return regionCoord << 8;
}
public static bool checkServiceURI(string uristr, out string serviceURI, out string serviceHost, out string serviceIPstr)
{
serviceURI = string.Empty;
serviceHost = string.Empty;
serviceIPstr = string.Empty;
try
{
Uri uri = new Uri(uristr);
serviceURI = uri.AbsoluteUri;
if(uri.Port == 80)
serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) +":80/";
else if(uri.Port == 443)
serviceURI = serviceURI.Trim(new char[] { '/', ' ' }) +":443/";
serviceHost = uri.Host;
IPEndPoint ep = Util.getEndPoint(serviceHost,uri.Port);
if(ep == null)
return false;
serviceIPstr = ep.Address.ToString();
return true;
}
catch
{
serviceURI = string.Empty;
}
return false;
}
public static bool buildHGRegionURI(string inputName, out string serverURI, out string serverHost, out string regionName)
{
serverURI = string.Empty;
serverHost = string.Empty;
regionName = string.Empty;
inputName = inputName.Trim();
if (!inputName.StartsWith("http") && !inputName.StartsWith("https"))
{
// Formats: grid.example.com:8002:region name
// grid.example.com:region name
// grid.example.com:8002
// grid.example.com
string host;
uint port = 80;
string[] parts = inputName.Split(new char[] { ':' });
int indx;
if(parts.Length == 0)
return false;
if (parts.Length == 1)
{
indx = inputName.IndexOf('/');
if (indx < 0)
serverURI = "http://"+ inputName + "/";
else
{
serverURI = "http://"+ inputName.Substring(0,indx + 1);
if(indx + 2 < inputName.Length)
regionName = inputName.Substring(indx + 1);
}
}
else
{
host = parts[0];
if (parts.Length >= 2)
{
indx = parts[1].IndexOf('/');
if(indx < 0)
{
// If it's a number then assume it's a port. Otherwise, it's a region name.
if (!UInt32.TryParse(parts[1], out port))
{
port = 80;
regionName = parts[1];
}
}
else
{
string portstr = parts[1].Substring(0, indx);
if(indx + 2 < parts[1].Length)
regionName = parts[1].Substring(indx + 1);
if (!UInt32.TryParse(portstr, out port))
port = 80;
}
}
// always take the last one
if (parts.Length >= 3)
{
regionName = parts[2];
}
serverURI = "http://"+ host +":"+ port.ToString() + "/";
}
}
else
{
// Formats: http://grid.example.com region name
// http://grid.example.com "region name"
// http://grid.example.com
string[] parts = inputName.Split(new char[] { ' ' });
if (parts.Length == 0)
return false;
serverURI = parts[0];
int indx = serverURI.LastIndexOf('/');
if(indx > 10)
{
if(indx + 2 < inputName.Length)
regionName = inputName.Substring(indx + 1);
serverURI = inputName.Substring(0, indx + 1);
}
else if (parts.Length >= 2)
{
regionName = inputName.Substring(serverURI.Length);
}
}
// use better code for sanity check
Uri uri;
try
{
uri = new Uri(serverURI);
}
catch
{
return false;
}
if(!string.IsNullOrEmpty(regionName))
regionName = regionName.Trim(new char[] { '"', ' ' });
serverURI = uri.AbsoluteUri;
if(uri.Port == 80)
serverURI = serverURI.Trim(new char[] { '/', ' ' }) +":80/";
else if(uri.Port == 443)
serverURI = serverURI.Trim(new char[] { '/', ' ' }) +":443/";
serverHost = uri.Host;
return true;
}
public static T Clamp<T>(T x, T min, T max)
where T : IComparable<T>
{
return x.CompareTo(max) > 0 ? max :
x.CompareTo(min) < 0 ? min :
x;
}
// Clamp the maximum magnitude of a vector
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static Vector3 ClampV(Vector3 x, float max)
{
float lenSq = x.LengthSquared();
if (lenSq > (max * max))
{
lenSq = max / (float)Math.Sqrt(lenSq);
x = x * lenSq;
}
return x;
}
/// <summary>
/// Check if any of the values in a Vector3 are NaN or Infinity
/// </summary>
/// <param name="v">Vector3 to check</param>
/// <returns></returns>
public static bool IsNanOrInfinity(Vector3 v)
{
if (float.IsNaN(v.X) || float.IsNaN(v.Y) || float.IsNaN(v.Z))
return true;
if (float.IsInfinity(v.X) || float.IsInfinity(v.Y) || float.IsNaN(v.Z))
return true;
return false;
}
// Inclusive, within range test (true if equal to the endpoints)
public static bool InRange<T>(T x, T min, T max)
where T : IComparable<T>
{
return x.CompareTo(max) <= 0 && x.CompareTo(min) >= 0;
}
public static uint GetNextXferID()
{
uint id = 0;
lock (XferLock)
{
id = nextXferID;
nextXferID++;
}
return id;
}
public static string GetFileName(string file)
{
// Return just the filename on UNIX platforms
// TODO: this should be customisable with a prefix, but that's something to do later.
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
return file;
}
// Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
// TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
{
Directory.CreateDirectory("%APPDATA%\\OpenSim");
}
return "%APPDATA%\\OpenSim\\" + file;
}
// Catch all - covers older windows versions
// (but those probably wont work anyway)
return file;
}
/// <summary>
/// Debug utility function to convert OSD into formatted XML for debugging purposes.
/// </summary>
/// <param name="osd">
/// A <see cref="OSD"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public static string GetFormattedXml(OSD osd)
{
return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
}
/// <summary>
/// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
/// </summary>
/// <remarks>
/// Please don't delete me even if I appear currently unused!
/// </remarks>
/// <param name="rawXml"></param>
/// <returns></returns>
public static string GetFormattedXml(string rawXml)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(rawXml);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
try
{
xd.WriteTo(xtw);
}
finally
{
xtw.Close();
}
return sb.ToString();
}
public static byte[] DocToBytes(XmlDocument doc)
{
using (MemoryStream ms = new MemoryStream())
using (XmlTextWriter xw = new XmlTextWriter(ms, null))
{
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
static bool IsHexa(char c)
{
if (c >= '0' && c <= '9')
return true;
if (c >= 'a' && c <= 'f')
return true;
if (c >= 'A' && c <= 'F')
return true;
return false;
}
public static List<UUID> GetUUIDsOnString(ref string s, int indx, int len)
{
var ids = new List<UUID>();
int endA = indx + len;
if(endA > s.Length)
endA = s.Length;
if (endA - indx < 36)
return ids;
int endB = endA - 26;
endA -= 35;
int idbase;
int next;
int retry;
while (indx < endA)
{
for (; indx < endA; ++indx)
{
if (IsHexa(s[indx]))
break;
}
if (indx == endA)
break;
idbase = indx;
for (; indx < endB; ++indx)
{
if (!IsHexa(s[indx]))
break;
if (indx - idbase >= 8)
++idbase;
}
if (s[indx] != '-')
continue;
++indx;
retry = indx;
next = indx + 4;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (s[indx] != '-')
{
indx = retry;
continue;
}
++indx;
retry = indx;
next = indx + 4;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (s[indx] != '-')
{
indx = retry;
continue;
}
++indx;
retry = indx;
next = indx + 4;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (s[indx] != '-')
{
indx = retry;
continue;
}
++indx;
retry = indx;
next = indx + 12;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (UUID.TryParse(s.Substring(idbase, 36), out UUID u))
{
ids.Add(u);
}
++indx;
}
return ids;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
static bool IsHexa(byte c)
{
if (c >= '0' && c <= '9')
return true;
if (c >= 'a' && c <= 'f')
return true;
if (c >= 'A' && c <= 'F')
return true;
return false;
}
public static List<UUID> GetUUIDsOnData(byte[] s, int indx, int len)
{
var ids = new List<UUID>();
int endA = indx + len;
if (endA > s.Length)
endA = s.Length;
if (endA - indx < 36)
return ids;
int endB = endA - 26;
endA -= 35;
int idbase;
int next;
int retry;
while (indx < endA)
{
for (; indx < endA; ++indx)
{
if (IsHexa(s[indx]))
break;
}
if (indx == endA)
break;
idbase = indx;
for (; indx < endB; ++indx)
{
if (!IsHexa(s[indx]))
break;
if (indx - idbase >= 8)
++idbase;
}
if (s[indx] != '-')
continue;
++indx;
retry = indx;
next = indx + 4;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (s[indx] != '-')
{
indx = retry;
continue;
}
++indx;
retry = indx;
next = indx + 4;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (s[indx] != '-')
{
indx = retry;
continue;
}
++indx;
retry = indx;
next = indx + 4;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (s[indx] != '-')
{
indx = retry;
continue;
}
++indx;
retry = indx;
next = indx + 12;
for (; indx < next; ++indx)
{
if (!IsHexa(s[indx]))
break;
}
if (indx != next)
continue;
if (UUID.TryParse(Encoding.ASCII.GetString(s, idbase, 36), out UUID u))
{
ids.Add(u);
}
++indx;
}
return ids;
}
/// <summary>
/// Is the platform Windows?
/// </summary>
/// <returns>true if so, false otherwise</returns>
public static bool IsWindows()
{
PlatformID platformId = Environment.OSVersion.Platform;
return (platformId == PlatformID.Win32NT
|| platformId == PlatformID.Win32S
|| platformId == PlatformID.Win32Windows
|| platformId == PlatformID.WinCE);
}
public static bool LoadArchSpecificWindowsDll(string libraryName)
{
return LoadArchSpecificWindowsDll(libraryName, string.Empty);
}
public static bool LoadArchSpecificWindowsDll(string libraryName, string path)
{
// We do this so that OpenSimulator on Windows loads the correct native library depending on whether
// it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
// will find it already loaded later on.
//
// This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
// controlled in config files.
string nativeLibraryPath;
if (Environment.Is64BitProcess)
nativeLibraryPath = Path.Combine(Path.Combine(path, "lib64"), libraryName);
else
nativeLibraryPath = Path.Combine(Path.Combine(path, "lib32"), libraryName);
m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);
if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
{
m_log.ErrorFormat(
"[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);
return false;
}
else
{
return true;
}
}
public static bool IsEnvironmentSupported(ref string reason)
{
// Must have .NET 2.0 (Generics / libsl)
if (Environment.Version.Major < 2)
{
reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
return false;
}
// Windows 95/98/ME are unsupported
if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
Environment.OSVersion.Platform != PlatformID.Win32NT)
{
reason = "Windows 95/98/ME will not run OpenSim";
return false;
}
// Windows 2000 / Pre-SP2 XP
if (Environment.OSVersion.Version.Major == 5 &&
Environment.OSVersion.Version.Minor == 0)
{
reason = "Please update to Windows XP Service Pack 2 or Server2003";
return false;
}
return true;
}
public static int UnixTimeSinceEpoch()
{
return ToUnixTime(DateTime.UtcNow);
}
public static int ToUnixTime(DateTime stamp)
{
TimeSpan t = stamp.ToUniversalTime() - UnixEpoch;
return (int)t.TotalSeconds;
}
public static DateTime ToDateTime(ulong seconds)
{
return UnixEpoch.AddSeconds(seconds);
}
public static DateTime ToDateTime(int seconds)
{
return UnixEpoch.AddSeconds(seconds);
}
/// <summary>
/// Return an md5 hash of the given string
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string Md5Hash(string data)
{
return Md5Hash(data, Encoding.Default);
}
public static string Md5Hash(string data, Encoding encoding)
{
byte[] dataMd5 = ComputeMD5Hash(data, encoding);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dataMd5.Length; i++)
sb.AppendFormat("{0:x2}", dataMd5[i]);
return sb.ToString();
}
private static byte[] ComputeMD5Hash(string data, Encoding encoding)
{
using(MD5 md5 = MD5.Create())
return md5.ComputeHash(encoding.GetBytes(data));
}
/// <summary>
/// Return an SHA1 hash
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string SHA1Hash(string data, Encoding enc)
{
return SHA1Hash(enc.GetBytes(data));
}
public static string SHA1Hash(string data)
{
return SHA1Hash(Encoding.Default.GetBytes(data));
}
/// <summary>
/// Return an SHA1 hash
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string SHA1Hash(byte[] data)
{
byte[] hash = ComputeSHA1Hash(data);
return BitConverter.ToString(hash).Replace("-", String.Empty);
}
private static byte[] ComputeSHA1Hash(byte[] src)
{
byte[] ret;
using (SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider())
ret = SHA1.ComputeHash(src);
return ret;
}
public static UUID ComputeSHA1UUID(string src)
{
return ComputeSHA1UUID(Encoding.Default.GetBytes(src));
}
public static UUID ComputeSHA1UUID(byte[] src)
{
byte[] ret;
using (SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider())
ret = SHA1.ComputeHash(src);
return new UUID(ret, 2);
}
public static int fast_distance2d(int x, int y)
{
x = Math.Abs(x);
y = Math.Abs(y);
int min = Math.Min(x, y);
return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
}
/// <summary>
/// Determines whether a point is inside a bounding box.
/// </summary>
/// <param name='v'></param>
/// <param name='min'></param>
/// <param name='max'></param>
/// <returns></returns>
public static bool IsInsideBox(Vector3 v, Vector3 min, Vector3 max)
{
return v.X >= min.X && v.Y >= min.Y && v.Z >= min.Z
&& v.X <= max.X && v.Y <= max.Y && v.Z <= max.Z;
}
/// <summary>
/// Are the co-ordinates of the new region visible from the old region?
/// </summary>
/// <param name="oldx">Old region x-coord</param>
/// <param name="newx">New region x-coord</param>
/// <param name="oldy">Old region y-coord</param>
/// <param name="newy">New region y-coord</param>
/// <returns></returns>
public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy,
int oldsizex, int oldsizey, int newsizex, int newsizey)
{
// we still need to make sure we see new region 1stNeighbors
drawdist--;
oldx *= Constants.RegionSize;
newx *= Constants.RegionSize;
if (oldx + oldsizex + drawdist < newx)
return true;
if (newx + newsizex + drawdist < oldx)
return true;
oldy *= Constants.RegionSize;
newy *= Constants.RegionSize;
if (oldy + oldsizey + drawdist < newy)
return true;
if (newy + newsizey + drawdist < oldy)
return true;
return false;
}
public static string FieldToString(byte[] bytes)
{
return FieldToString(bytes, String.Empty);
}
/// <summary>
/// Convert a variable length field (byte array) to a string, with a
/// field name prepended to each line of the output
/// </summary>
/// <remarks>If the byte array has unprintable characters in it, a
/// hex dump will be put in the string instead</remarks>
/// <param name="bytes">The byte array to convert to a string</param>
/// <param name="fieldName">A field name to prepend to each line of output</param>
/// <returns>An ASCII string or a string containing a hex dump, minus
/// the null terminator</returns>
public static string FieldToString(byte[] bytes, string fieldName)
{
// Check for a common case
if (bytes.Length == 0) return String.Empty;
StringBuilder output = new StringBuilder();
bool printable = true;
for (int i = 0; i < bytes.Length; ++i)
{
// Check if there are any unprintable characters in the array
if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
&& bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
{
printable = false;
break;
}
}
if (printable)
{
if (fieldName.Length > 0)
{
output.Append(fieldName);
output.Append(": ");
}
output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
}
else
{
for (int i = 0; i < bytes.Length; i += 16)
{
if (i != 0)
output.Append(Environment.NewLine);
if (fieldName.Length > 0)
{
output.Append(fieldName);
output.Append(": ");
}
for (int j = 0; j < 16; j++)
{
if ((i + j) < bytes.Length)
output.Append(String.Format("{0:X2} ", bytes[i + j]));
else
output.Append(" ");
}
for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
{
if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
output.Append((char) bytes[i + j]);
else
output.Append(".");
}
}
}
return output.ToString();
}
private static ExpiringCache<string,IPAddress> dnscache = new ExpiringCache<string, IPAddress>();
/// <summary>
/// Converts a URL to a IPAddress
/// </summary>
/// <param name="url">URL Standard Format</param>
/// <returns>A resolved IP Address</returns>
public static IPAddress GetHostFromURL(string url)
{
return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
}
/// <summary>
/// Returns a IP address from a specified DNS, favouring IPv4 addresses.
/// </summary>
/// <param name="dnsAddress">DNS Hostname</param>
/// <returns>An IP address, or null</returns>
public static IPAddress GetHostFromDNS(string dnsAddress)
{
if(String.IsNullOrWhiteSpace(dnsAddress))
return null;
IPAddress ia = null;
if(dnscache.TryGetValue(dnsAddress, out ia) && ia != null)
{
dnscache.AddOrUpdate(dnsAddress, ia, 300);
return ia;
}
ia = null;
// If it is already an IP, don't let GetHostEntry see it
if (IPAddress.TryParse(dnsAddress, out ia) && ia != null)
{
if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
return null;
dnscache.AddOrUpdate(dnsAddress, ia, 300);
return ia;
}
IPHostEntry IPH;
try
{
IPH = Dns.GetHostEntry(dnsAddress);
}
catch // (SocketException e)
{
return null;
}
if(IPH == null || IPH.AddressList.Length == 0)
return null;
ia = null;
foreach (IPAddress Adr in IPH.AddressList)
{
if (ia == null)
ia = Adr;
if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
ia = Adr;
break;
}
}
if(ia != null)
dnscache.AddOrUpdate(dnsAddress, ia, 300);
return ia;
}
public static IPEndPoint getEndPoint(IPAddress ia, int port)
{
if(ia == null)
return null;
IPEndPoint newEP = null;
try
{
newEP = new IPEndPoint(ia, port);
}
catch
{
newEP = null;
}
return newEP;
}
public static IPEndPoint getEndPoint(string hostname, int port)
{
if(String.IsNullOrWhiteSpace(hostname))
return null;
IPAddress ia = null;
if(dnscache.TryGetValue(hostname, out ia) && ia != null)
{
dnscache.AddOrUpdate(hostname, ia, 300);
return getEndPoint(ia, port);
}
ia = null;
// If it is already an IP, don't let GetHostEntry see it
if (IPAddress.TryParse(hostname, out ia) && ia != null)
{
if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
return null;
dnscache.AddOrUpdate(hostname, ia, 300);
return getEndPoint(ia, port);
}
IPHostEntry IPH;
try
{
IPH = Dns.GetHostEntry(hostname);
}
catch // (SocketException e)
{
return null;
}
if(IPH == null || IPH.AddressList.Length == 0)
return null;
ia = null;
foreach (IPAddress Adr in IPH.AddressList)
{
if (ia == null)
ia = Adr;
if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
ia = Adr;
break;
}
}
if(ia != null)
dnscache.AddOrUpdate(hostname, ia, 300);
return getEndPoint(ia,port);
}
public static Uri GetURI(string protocol, string hostname, int port, string path)
{
return new UriBuilder(protocol, hostname, port, path).Uri;
}
/// <summary>
/// Gets a list of all local system IP addresses
/// </summary>
/// <returns></returns>
public static IPAddress[] GetLocalHosts()
{
return Dns.GetHostAddresses(Dns.GetHostName());
}
public static IPAddress GetLocalHost()
{
IPAddress[] iplist = GetLocalHosts();
if (iplist.Length == 0) // No accessible external interfaces
{
IPAddress[] loopback = Dns.GetHostAddresses("localhost");
IPAddress localhost = loopback[0];
return localhost;
}
foreach (IPAddress host in iplist)
{
if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
{
return host;
}
}
if (iplist.Length > 0)
{
foreach (IPAddress host in iplist)
{
if (host.AddressFamily == AddressFamily.InterNetwork)
return host;
}
// Well all else failed...
return iplist[0];
}
return null;
}
/// <summary>
/// Parses a foreign asset ID.
/// </summary>
/// <param name="id">A possibly-foreign asset ID: http://grid.example.com:8002/00000000-0000-0000-0000-000000000000 </param>
/// <param name="url">The URL: http://grid.example.com:8002</param>
/// <param name="assetID">The asset ID: 00000000-0000-0000-0000-000000000000. Returned even if 'id' isn't foreign.</param>
/// <returns>True: this is a foreign asset ID; False: it isn't</returns>
public static bool ParseForeignAssetID(string id, out string url, out string assetID)
{
url = String.Empty;
assetID = String.Empty;
UUID uuid;
if (UUID.TryParse(id, out uuid))
{
assetID = uuid.ToString();
return false;
}
if ((id.Length == 0) || (id[0] != 'h' && id[0] != 'H'))
return false;
Uri assetUri;
if (!Uri.TryCreate(id, UriKind.Absolute, out assetUri) || assetUri.Scheme != Uri.UriSchemeHttp)
return false;
// Simian
if (assetUri.Query != string.Empty)
{
NameValueCollection qscoll = HttpUtility.ParseQueryString(assetUri.Query);
assetID = qscoll["id"];
if (assetID != null)
url = id.Replace(assetID, ""); // Malformed again, as simian expects
else
url = id; // !!! best effort
}
else // robust
{
url = "http://" + assetUri.Authority;
assetID = assetUri.LocalPath.Trim(new char[] { '/' });
}
if (!UUID.TryParse(assetID, out uuid))
return false;
return true;
}
/// <summary>
/// Removes all invalid path chars (OS dependent)
/// </summary>
/// <param name="path">path</param>
/// <returns>safe path</returns>
public static string safePath(string path)
{
return Regex.Replace(path, regexInvalidPathChars, String.Empty);
}
/// <summary>
/// Removes all invalid filename chars (OS dependent)
/// </summary>
/// <param name="path">filename</param>
/// <returns>safe filename</returns>
public static string safeFileName(string filename)
{
return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
;
}
//
// directory locations
//
public static string homeDir()
{
string temp;
// string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
// temp = Path.Combine(personal,".OpenSim");
temp = ".";
return temp;
}
public static string assetsDir()
{
return Path.Combine(configDir(), "assets");
}
public static string inventoryDir()
{
return Path.Combine(configDir(), "inventory");
}
public static string configDir()
{
return ".";
}
public static string dataDir()
{
return ".";
}
public static string logFile()
{
foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
{
if (appender is FileAppender && appender.Name == "LogFileAppender")
{
return ((FileAppender)appender).File;
}
}
return "./OpenSim.log";
}
public static string statsLogFile()
{
foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
{
if (appender is FileAppender && appender.Name == "StatsLogFileAppender")
{
return ((FileAppender)appender).File;
}
}
return "./OpenSimStats.log";
}
public static string logDir()
{
return Path.GetDirectoryName(logFile());
}
// From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
public static string GetUniqueFilename(string FileName)
{
int count = 0;
string Name;
if (File.Exists(FileName))
{
FileInfo f = new FileInfo(FileName);
if (!String.IsNullOrEmpty(f.Extension))
{
Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
}
else
{
Name = f.FullName;
}
while (File.Exists(FileName))
{
count++;
FileName = Name + count + f.Extension;
}
}
return FileName;
}
#region Nini (config) related Methods
public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
{
if (!File.Exists(fileName))
{
// create new file
}
XmlConfigSource config = new XmlConfigSource(fileName);
AddDataRowToConfig(config, row);
config.Save();
return config;
}
public static void AddDataRowToConfig(IConfigSource config, DataRow row)
{
config.Configs.Add((string) row[0]);
for (int i = 0; i < row.Table.Columns.Count; i++)
{
config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
}
}
public static string GetConfigVarWithDefaultSection(IConfigSource config, string varname, string section)
{
// First, check the Startup section, the default section
IConfig cnf = config.Configs["Startup"];
if (cnf == null)
return string.Empty;
string val = cnf.GetString(varname, string.Empty);
// Then check for an overwrite of the default in the given section
if (!string.IsNullOrEmpty(section))
{
cnf = config.Configs[section];
if (cnf != null)
val = cnf.GetString(varname, val);
}
return val;
}
/// <summary>
/// Gets the value of a configuration variable by looking into
/// multiple sections in order. The latter sections overwrite
/// any values previously found.
/// </summary>
/// <typeparam name="T">Type of the variable</typeparam>
/// <param name="config">The configuration object</param>
/// <param name="varname">The configuration variable</param>
/// <param name="sections">Ordered sequence of sections to look at</param>
/// <returns></returns>
public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections)
{
return GetConfigVarFromSections<T>(config, varname, sections, default(T));
}
/// <summary>
/// Gets the value of a configuration variable by looking into
/// multiple sections in order. The latter sections overwrite
/// any values previously found.
/// </summary>
/// <remarks>
/// If no value is found then the given default value is returned
/// </remarks>
/// <typeparam name="T">Type of the variable</typeparam>
/// <param name="config">The configuration object</param>
/// <param name="varname">The configuration variable</param>
/// <param name="sections">Ordered sequence of sections to look at</param>
/// <param name="val">Default value</param>
/// <returns></returns>
public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections, object val)
{
foreach (string section in sections)
{
IConfig cnf = config.Configs[section];
if (cnf == null)
continue;
if (typeof(T) == typeof(String))
val = cnf.GetString(varname, (string)val);
else if (typeof(T) == typeof(Boolean))
val = cnf.GetBoolean(varname, (bool)val);
else if (typeof(T) == typeof(Int32))
val = cnf.GetInt(varname, (int)val);
else if (typeof(T) == typeof(float))
val = cnf.GetFloat(varname, (float)val);
else
m_log.ErrorFormat("[UTIL]: Unhandled type {0}", typeof(T));
}
return (T)val;
}
public static void MergeEnvironmentToConfig(IConfigSource ConfigSource)
{
IConfig enVars = ConfigSource.Configs["Environment"];
// if section does not exist then user isn't expecting them, so don't bother.
if( enVars != null )
{
// load the values from the environment
EnvConfigSource envConfigSource = new EnvConfigSource();
// add the requested keys
string[] env_keys = enVars.GetKeys();
foreach ( string key in env_keys )
{
envConfigSource.AddEnv(key, string.Empty);
}
// load the values from environment
envConfigSource.LoadEnv();
// add them in to the master
ConfigSource.Merge(envConfigSource);
ConfigSource.ExpandKeyValues();
}
}
public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
{
Type settingsType = settingsClass.GetType();
FieldInfo[] fieldInfos = settingsType.GetFields();
foreach (FieldInfo fieldInfo in fieldInfos)
{
if (!fieldInfo.IsStatic)
{
if (fieldInfo.FieldType == typeof(System.String))
{
fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
}
else if (fieldInfo.FieldType == typeof(System.Boolean))
{
fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
}
else if (fieldInfo.FieldType == typeof(System.Int32))
{
fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
}
else if (fieldInfo.FieldType == typeof(System.Single))
{
fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
}
else if (fieldInfo.FieldType == typeof(System.UInt32))
{
fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
}
}
}
PropertyInfo[] propertyInfos = settingsType.GetProperties();
foreach (PropertyInfo propInfo in propertyInfos)
{
if ((propInfo.CanRead) && (propInfo.CanWrite))
{
if (propInfo.PropertyType == typeof(System.String))
{
propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
}
else if (propInfo.PropertyType == typeof(System.Boolean))
{
propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
}
else if (propInfo.PropertyType == typeof(System.Int32))
{
propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
}
else if (propInfo.PropertyType == typeof(System.Single))
{
propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
}
if (propInfo.PropertyType == typeof(System.UInt32))
{
propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
}
}
}
return settingsClass;
}
/// <summary>
/// Reads a configuration file, configFile, merging it with the main configuration, config.
/// If the file doesn't exist, it copies a given exampleConfigFile onto configFile, and then
/// merges it.
/// </summary>
/// <param name="config">The main configuration data</param>
/// <param name="configFileName">The name of a configuration file in ConfigDirectory variable, no path</param>
/// <param name="exampleConfigFile">Full path to an example configuration file</param>
/// <param name="configFilePath">Full path ConfigDirectory/configFileName</param>
/// <param name="created">True if the file was created in ConfigDirectory, false if it existed</param>
/// <returns>True if success</returns>
public static bool MergeConfigurationFile(IConfigSource config, string configFileName, string exampleConfigFile, out string configFilePath, out bool created)
{
created = false;
configFilePath = string.Empty;
IConfig cnf = config.Configs["Startup"];
if (cnf == null)
{
m_log.WarnFormat("[UTILS]: Startup section doesn't exist");
return false;
}
string configDirectory = cnf.GetString("ConfigDirectory", ".");
string configFile = Path.Combine(configDirectory, configFileName);
if (!File.Exists(configFile) && !string.IsNullOrEmpty(exampleConfigFile))
{
// We need to copy the example onto it
if (!Directory.Exists(configDirectory))
Directory.CreateDirectory(configDirectory);
try
{
File.Copy(exampleConfigFile, configFile);
created = true;
}
catch (Exception e)
{
m_log.WarnFormat("[UTILS]: Exception copying configuration file {0} to {1}: {2}", configFile, exampleConfigFile, e.Message);
return false;
}
}
if (File.Exists(configFile))
{
// Merge
config.Merge(new IniConfigSource(configFile));
config.ExpandKeyValues();
configFilePath = configFile;
return true;
}
else
return false;
}
#endregion
public static float Clip(float x, float min, float max)
{
return Math.Min(Math.Max(x, min), max);
}
public static int Clip(int x, int min, int max)
{
return Math.Min(Math.Max(x, min), max);
}
public static Vector3 Clip(Vector3 vec, float min, float max)
{
return new Vector3(Clip(vec.X, min, max), Clip(vec.Y, min, max),
Clip(vec.Z, min, max));
}
/// <summary>
/// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
/// </summary>
/// <param name="UUID"></param>
/// <returns></returns>
public static String ToRawUuidString(UUID UUID)
{
return UUID.Guid.ToString("n");
}
public static string CleanString(string input)
{
if (input.Length == 0)
return input;
int clip = input.Length;
// Test for ++ string terminator
int pos = input.IndexOf("\0");
if (pos != -1 && pos < clip)
clip = pos;
// Test for CR
pos = input.IndexOf("\r");
if (pos != -1 && pos < clip)
clip = pos;
// Test for LF
pos = input.IndexOf("\n");
if (pos != -1 && pos < clip)
clip = pos;
// Truncate string before first end-of-line character found
return input.Substring(0, clip);
}
/// <summary>
/// returns the contents of /etc/issue on Unix Systems
/// Use this for where it's absolutely necessary to implement platform specific stuff
/// </summary>
/// <returns></returns>
public static string ReadEtcIssue()
{
try
{
StreamReader sr = new StreamReader("/etc/issue.net");
string issue = sr.ReadToEnd();
sr.Close();
return issue;
}
catch (Exception)
{
return "";
}
}
public static void SerializeToFile(string filename, Object obj)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = null;
try
{
stream = new FileStream(
filename, FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}
public static Object DeserializeFromFile(string filename)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = null;
Object ret = null;
try
{
stream = new FileStream(
filename, FileMode.Open,
FileAccess.Read, FileShare.None);
ret = formatter.Deserialize(stream);
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
finally
{
if (stream != null)
{
stream.Close();
}
}
return ret;
}
public static string Compress(string text)
{
byte[] buffer = Util.UTF8.GetBytes(text);
MemoryStream memory = new MemoryStream();
using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
{
compressor.Write(buffer, 0, buffer.Length);
}
memory.Position = 0;
byte[] compressed = new byte[memory.Length];
memory.Read(compressed, 0, compressed.Length);
byte[] compressedBuffer = new byte[compressed.Length + 4];
Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
return Convert.ToBase64String(compressedBuffer);
}
public static string Decompress(string compressedText)
{
byte[] compressedBuffer = Convert.FromBase64String(compressedText);
using (MemoryStream memory = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
memory.Position = 0;
using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
{
decompressor.Read(buffer, 0, buffer.Length);
}
return Util.UTF8.GetString(buffer);
}
}
/// <summary>
/// Copy data from one stream to another, leaving the read position of both streams at the beginning.
/// </summary>
/// <param name='inputStream'>
/// Input stream. Must be seekable.
/// </param>
/// <exception cref='ArgumentException'>
/// Thrown if the input stream is not seekable.
/// </exception>
public static Stream Copy(Stream inputStream)
{
if (!inputStream.CanSeek)
throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");
const int readSize = 256;
byte[] buffer = new byte[readSize];
MemoryStream ms = new MemoryStream();
int count = inputStream.Read(buffer, 0, readSize);
while (count > 0)
{
ms.Write(buffer, 0, count);
count = inputStream.Read(buffer, 0, readSize);
}
ms.Position = 0;
inputStream.Position = 0;
return ms;
}
public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
{
return SendXmlRpcCommand(url, methodName, args);
}
public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
{
XmlRpcRequest client = new XmlRpcRequest(methodName, args);
return client.Send(url, 6000);
}
/// <summary>
/// Returns an error message that the user could not be found in the database
/// </summary>
/// <returns>XML string consisting of a error element containing individual error(s)</returns>
public static XmlRpcResponse CreateUnknownUserErrorResponse()
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
responseData["error_type"] = "unknown_user";
responseData["error_desc"] = "The user requested is not in the database";
response.Value = responseData;
return response;
}
/// <summary>
/// Converts a byte array in big endian order into an ulong.
/// </summary>
/// <param name="bytes">
/// The array of bytes
/// </param>
/// <returns>
/// The extracted ulong
/// </returns>
public static ulong BytesToUInt64Big(byte[] bytes)
{
if (bytes.Length < 8) return 0;
return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
}
// used for RemoteParcelRequest (for "About Landmark")
public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
{
byte[] bytes =
{
(byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
(byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
(byte)x, (byte)(x >> 8), 0, 0,
(byte)y, (byte)(y >> 8), 0, 0 };
return new UUID(bytes, 0);
}
public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
{
byte[] bytes =
{
(byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
(byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
(byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
(byte)y, (byte)(y >> 8), 0, 0 };
return new UUID(bytes, 0);
}
public static bool ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
{
byte[] bytes = parcelID.GetBytes();
regionHandle = Utils.BytesToUInt64(bytes);
x = Utils.BytesToUInt(bytes, 8) & 0xffff;
y = Utils.BytesToUInt(bytes, 12) & 0xffff;
// validation may fail, just reducing the odds of using a real UUID as encoded parcel
return ( bytes[0] == 0 && bytes[4] == 0 && // handler x,y multiples of 256
bytes[9] < 64 && bytes[13] < 64 && // positions < 16km
bytes[14] == 0 && bytes[15] == 0);
}
public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
{
byte[] bytes = parcelID.GetBytes();
regionHandle = Utils.BytesToUInt64(bytes);
x = Utils.BytesToUInt(bytes, 8) & 0xffff;
z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
y = Utils.BytesToUInt(bytes, 12) & 0xffff;
}
public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
{
ulong regionHandle;
uint rx, ry;
ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
Utils.LongToUInts(regionHandle, out rx, out ry);
x += rx;
y += ry;
}
/// <summary>
/// Get operating system information if available. Returns only the first 45 characters of information
/// </summary>
/// <returns>
/// Operating system information. Returns an empty string if none was available.
/// </returns>
public static string GetOperatingSystemInformation()
{
string os = String.Empty;
// if (Environment.OSVersion.Platform != PlatformID.Unix)
// {
// os = Environment.OSVersion.ToString();
// }
// else
// {
// os = ReadEtcIssue();
// }
//
// if (os.Length > 45)
// {
// os = os.Substring(0, 45);
// }
return os;
}
public static string GetRuntimeInformation()
{
string ru = String.Empty;
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
ru = "Unix/Mono";
}
else
if (Environment.OSVersion.Platform == PlatformID.MacOSX)
ru = "OSX/Mono";
else
{
if (IsPlatformMono)
ru = "Win/Mono";
else
ru = "Win/.NET";
}
return ru;
}
/// <summary>
/// Is the given string a UUID?
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static bool isUUID(string s)
{
return UUIDPattern.IsMatch(s);
}
public static string GetDisplayConnectionString(string connectionString)
{
int passPosition = 0;
int passEndPosition = 0;
string displayConnectionString = null;
// hide the password in the connection string
passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
if (passPosition == -1)
return connectionString;
passPosition = connectionString.IndexOf("=", passPosition);
if (passPosition < connectionString.Length)
passPosition += 1;
passEndPosition = connectionString.IndexOf(";", passPosition);
displayConnectionString = connectionString.Substring(0, passPosition);
displayConnectionString += "***";
displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
return displayConnectionString;
}
public static string Base64ToString(string str)
{
Decoder utf8Decode = Encoding.UTF8.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(str);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
public static void BinaryToASCII(char[] chars)
{
for (int i = 0; i < chars.Length; i++)
{
char ch = chars[i];
if (ch < 32 || ch > 127)
chars[i] = '.';
}
}
public static string BinaryToASCII(string src)
{
char[] chars = src.ToCharArray();
BinaryToASCII(chars);
return new String(chars);
}
/// <summary>
/// Reads a known number of bytes from a stream.
/// Throws EndOfStreamException if the stream doesn't contain enough data.
/// </summary>
/// <param name="stream">The stream to read data from</param>
/// <param name="data">The array to write bytes into. The array
/// will be completely filled from the stream, so an appropriate
/// size must be given.</param>
public static void ReadStream(Stream stream, byte[] data)
{
int offset = 0;
int remaining = data.Length;
while (remaining > 0)
{
int read = stream.Read(data, offset, remaining);
if (read <= 0)
throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
public static Guid GetHashGuid(string data, string salt)
{
byte[] hash = ComputeMD5Hash(data + salt, Encoding.Default);
//string s = BitConverter.ToString(hash);
Guid guid = new Guid(hash);
return guid;
}
public static byte ConvertMaturityToAccessLevel(uint maturity)
{
byte retVal = 0;
switch (maturity)
{
case 0: //PG
retVal = 13;
break;
case 1: //Mature
retVal = 21;
break;
case 2: // Adult
retVal = 42;
break;
}
return retVal;
}
public static uint ConvertAccessLevelToMaturity(byte maturity)
{
if (maturity <= 13)
return 0;
else if (maturity <= 21)
return 1;
else
return 2;
}
/// <summary>
/// Produces an OSDMap from its string representation on a stream
/// </summary>
/// <param name="data">The stream</param>
/// <param name="length">The size of the data on the stream</param>
/// <returns>The OSDMap or an exception</returns>
public static OSDMap GetOSDMap(Stream stream, int length)
{
byte[] data = new byte[length];
stream.Read(data, 0, length);
string strdata = Util.UTF8.GetString(data);
OSDMap args = null;
OSD buffer;
buffer = OSDParser.DeserializeJson(strdata);
if (buffer.Type == OSDType.Map)
{
args = (OSDMap)buffer;
return args;
}
return null;
}
public static OSDMap GetOSDMap(string data)
{
OSDMap args = null;
try
{
OSD buffer;
// We should pay attention to the content-type, but let's assume we know it's Json
buffer = OSDParser.DeserializeJson(data);
if (buffer.Type == OSDType.Map)
{
args = (OSDMap)buffer;
return args;
}
else
{
// uh?
m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
return null;
}
}
catch (Exception ex)
{
m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
return null;
}
}
public static string[] Glob(string path)
{
string vol=String.Empty;
if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
{
string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
if (vcomps.Length > 1)
{
path = vcomps[1];
vol = vcomps[0];
}
}
string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
// Glob
path = vol;
if (vol != String.Empty)
path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
else
path = new String(new char[] {Path.DirectorySeparatorChar});
List<string> paths = new List<string>();
List<string> found = new List<string>();
paths.Add(path);
int compIndex = -1;
foreach (string c in comps)
{
compIndex++;
List<string> addpaths = new List<string>();
foreach (string p in paths)
{
string[] dirs = Directory.GetDirectories(p, c);
if (dirs.Length != 0)
{
foreach (string dir in dirs)
addpaths.Add(Path.Combine(path, dir));
}
// Only add files if that is the last path component
if (compIndex == comps.Length - 1)
{
string[] files = Directory.GetFiles(p, c);
foreach (string f in files)
found.Add(f);
}
}
paths = addpaths;
}
return found.ToArray();
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static string AppendEndSlash(string path)
{
int len = path.Length;
--len;
if (len > 0 && path[len] != '/')
return path + '/';
return path;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static string TrimEndSlash(string path)
{
int len = path.Length;
--len;
if (len > 0 && path[len] == '/')
return path.Substring(0, len);
return path;
}
public static string ServerURIasIP(string uri)
{
if (uri == string.Empty)
return string.Empty;
// Get rid of eventual slashes at the end
uri = uri.TrimEnd('/');
IPAddress ipaddr1 = null;
string port1 = "";
try
{
ipaddr1 = Util.GetHostFromURL(uri);
}
catch { }
try
{
port1 = uri.Split(new char[] { ':' })[2];
}
catch { }
// We tried our best to convert the domain names to IP addresses
return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
}
/// <summary>
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
/// </summary>
/// <param name="str">
/// If null or empty, then an bytes[0] is returned.
/// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
/// </param>
/// <param name="args">
/// Arguments to substitute into the string via the {} mechanism.
/// </param>
/// <returns></returns>
public static byte[] StringToBytes256(string str, params object[] args)
{
return StringToBytes256(string.Format(str, args));
}
/// <summary>
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
/// </summary>
/// <param name="str">
/// If null or empty, then an bytes[0] is returned.
/// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
/// </param>
/// <returns></returns>
public static byte[] StringToBytes256(string str)
{
if (String.IsNullOrEmpty(str))
return Utils.EmptyBytes;
byte[] data = new byte[255];
int r = osUTF8Getbytes(str, data, 255, true); // real use limit is 255 not 256
if (r != 255)
Array.Resize<byte>(ref data, r);
return data;
}
/// <summary>
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
/// </summary>
/// <param name="str">
/// If null or empty, then an bytes[0] is returned.
/// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
/// </param>
/// <param name="args">
/// Arguments to substitute into the string via the {} mechanism.
/// </param>
/// <returns></returns>
public static byte[] StringToBytes1024(string str, params object[] args)
{
return StringToBytes1024(string.Format(str, args));
}
/// <summary>
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
/// </summary>
/// <param name="str">
/// If null or empty, then an bytes[0] is returned.
/// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
/// </param>
/// <returns></returns>
public static byte[] StringToBytes1024(string str)
{
if (String.IsNullOrEmpty(str))
return Utils.EmptyBytes;
byte[] data = new byte[1024];
int r = osUTF8Getbytes(str, data, 1024, true);
if (r != 1024)
Array.Resize<byte>(ref data, r);
return data;
}
/// <summary>
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to MaxLength bytes if necessary.
/// </summary>
/// <param name="str">
/// If null or empty, then an bytes[0] is returned.
/// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
/// </param>
/// <param name="args">
/// Arguments to substitute into the string via the {} mechanism.
/// </param>
/// <returns></returns>
public static byte[] StringToBytes(string str, int MaxLength, params object[] args)
{
return StringToBytes1024(string.Format(str, args), MaxLength);
}
/// <summary>
/// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to MaxLength bytes if necessary.
/// </summary>
/// <param name="str">
/// If null or empty, then an bytes[0] is returned.
/// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
/// </param>
/// <returns></returns>
public static byte[] StringToBytes(string str, int MaxLength)
{
if (String.IsNullOrEmpty(str))
return Utils.EmptyBytes;
byte[] data = new byte[MaxLength];
int r = osUTF8Getbytes(str, data, MaxLength, true);
if (r != MaxLength)
Array.Resize<byte>(ref data, r);
return data;
}
public static byte[] StringToBytesNoTerm(string str, int MaxLength)
{
if (String.IsNullOrEmpty(str))
return Utils.EmptyBytes;
byte[] data = new byte[MaxLength];
int r = osUTF8Getbytes(str, data, MaxLength, false);
if (r != MaxLength)
Array.Resize<byte>(ref data, r);
return data;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static int osUTF8Getbytes(string srcstr, byte[] dstarray, int maxdstlen, bool NullTerm = true)
{
return osUTF8Getbytes(srcstr, dstarray, 0, maxdstlen, NullTerm);
}
public static unsafe int osUTF8Getbytes(string srcstr, byte* dstarray, int maxdstlen, bool NullTerm = true)
{
if (string.IsNullOrEmpty(srcstr))
return 0;
fixed (char* srcbase = srcstr)
{
return osUTF8Getbytes(srcbase, srcstr.Length, dstarray, maxdstlen, NullTerm);
}
}
public static unsafe int osUTF8Getbytes(string srcstr, byte[] dstarray, int pos, int maxdstlen, bool NullTerm = true)
{
if (string.IsNullOrEmpty(srcstr))
return 0;
if (pos + maxdstlen > dstarray.Length)
return 0;
fixed (char* srcbase = srcstr)
{
fixed (byte* dstbase = &dstarray[pos])
{
return osUTF8Getbytes(srcbase, srcstr.Length, dstbase, maxdstlen, NullTerm);
}
}
}
public static unsafe int osUTF8Getbytes(char* srcarray, int srclenght, byte* dstarray, int maxdstlen, bool NullTerm = true)
{
int dstlen = NullTerm ? maxdstlen - 1 : maxdstlen;
int srclen = srclenght >= dstlen ? dstlen : srclenght;
char c;
char* src = srcarray;
char* srcend = src + srclen;
byte* dst = dstarray;
byte* dstend = dst + dstlen;
while (src < srcend && dst < dstend)
{
c = *src;
++src;
if (c <= 0x7f)
{
*dst = (byte)c;
++dst;
continue;
}
if (c < 0x800)
{
if (dst + 1 >= dstend)
break;
*dst = (byte)(0xC0 | (c >> 6));
++dst;
*dst = (byte)(0x80 | (c & 0x3F));
++dst;
continue;
}
if (c >= 0xD800 && c < 0xE000)
{
if (c >= 0xDC00)
continue; // ignore invalid
if (src + 1 >= srcend || dst + 3 >= dstend)
break;
int a = c;
c = *src;
++src;
if (c < 0xDC00 || c > 0xDFFF)
continue; // ignore invalid
a = (a << 10) + c - 0x35fdc00;
*dst = (byte)(0xF0 | (a >> 18));
++dst;
*dst = (byte)(0x80 | ((a >> 12) & 0x3f));
++dst;
*dst = (byte)(0x80 | ((a >> 6) & 0x3f));
++dst;
*dst = (byte)(0x80 | (a & 0x3f));
++dst;
continue;
}
if (dst + 2 >= dstend)
break;
*dst = (byte)(0xE0 | (c >> 12));
++dst;
*dst = (byte)(0x80 | ((c >> 6) & 0x3f));
++dst;
*dst = (byte)(0x80 | (c & 0x3f));
++dst;
}
int ret = (int)(dst - dstarray);
if (NullTerm && ret > 0 && *(dst - 1) != 0)
{
*dst = 0;
++ret;
}
return ret;
}
/// <summary>
/// Pretty format the hashtable contents to a single line.
/// </summary>
/// <remarks>
/// Used for debugging output.
/// </remarks>
/// <param name='ht'></param>
public static string PrettyFormatToSingleLine(Hashtable ht)
{
StringBuilder sb = new StringBuilder();
int i = 0;
foreach (string key in ht.Keys)
{
sb.AppendFormat("{0}:{1}", key, ht[key]);
if (++i < ht.Count)
sb.AppendFormat(", ");
}
return sb.ToString();
}
public static bool TryParseHttpRange(string header, out int start, out int end)
{
start = end = 0;
if(string.IsNullOrWhiteSpace(header))
return false;
if (header.StartsWith("bytes="))
{
string[] rangeValues = header.Substring(6).Split('-');
if (rangeValues.Length == 2)
{
string rawStart = rangeValues[0].Trim();
if (rawStart != "" && !Int32.TryParse(rawStart, out start))
return false;
if (start < 0)
return false;
string rawEnd = rangeValues[1].Trim();
if (rawEnd == "")
{
end = -1;
return true;
}
else if (Int32.TryParse(rawEnd, out end))
return end > 0;
}
}
start = end = 0;
return false;
}
/// <summary>
/// Used to trigger an early library load on Windows systems.
/// </summary>
/// <remarks>
/// Required to get 32-bit and 64-bit processes to automatically use the
/// appropriate native library.
/// </remarks>
/// <param name="dllToLoad"></param>
/// <returns></returns>
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
/// <summary>
/// Determine whether the current process is 64 bit
/// </summary>
/// <returns>true if so, false if not</returns>
#region FireAndForget Threading Pattern
public static void InitThreadPool(int minThreads, int maxThreads)
{
if (maxThreads < 2)
throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
if (minThreads > maxThreads || minThreads < 2)
throw new ArgumentOutOfRangeException("minThreads", "minThreads must be greater than 2 and less than or equal to maxThreads");
if (m_ThreadPool != null)
{
m_log.Warn("SmartThreadPool is already initialized. Ignoring request.");
return;
}
STPStartInfo startInfo = new STPStartInfo();
startInfo.ThreadPoolName = "Util";
startInfo.IdleTimeout = 20000;
startInfo.MaxWorkerThreads = maxThreads;
startInfo.MinWorkerThreads = minThreads;
m_ThreadPool = new SmartThreadPool(startInfo);
m_threadPoolWatchdog = new Timer(ThreadPoolWatchdog, null, 0, 1000);
}
public static int FireAndForgetCount()
{
const int MAX_SYSTEM_THREADS = 200;
switch (FireAndForgetMethod)
{
case FireAndForgetMethod.QueueUserWorkItem:
int workerThreads, iocpThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
return workerThreads;
case FireAndForgetMethod.SmartThreadPool:
return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
case FireAndForgetMethod.Thread:
{
using(Process p = System.Diagnostics.Process.GetCurrentProcess())
return MAX_SYSTEM_THREADS - p.Threads.Count;
}
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Additional information about threads in the main thread pool. Used to time how long the
/// thread has been running, and abort it if it has timed-out.
/// </summary>
private class ThreadInfo
{
public long ThreadFuncNum { get; set; }
public string StackTrace { get; set; }
private string context;
public bool LogThread { get; set; }
public IWorkItemResult WorkItem { get; set; }
public Thread Thread { get; set; }
public bool Running { get; set; }
public bool Aborted { get; set; }
private int started;
public bool DoTimeout;
public ThreadInfo(long threadFuncNum, string context, bool dotimeout = true)
{
ThreadFuncNum = threadFuncNum;
this.context = context;
LogThread = false;
Thread = null;
Running = false;
Aborted = false;
DoTimeout = dotimeout;
}
public void Started()
{
Thread = Thread.CurrentThread;
started = EnvironmentTickCount();
Running = true;
}
public void Ended()
{
Running = false;
}
public int Elapsed()
{
return EnvironmentTickCountSubtract(started);
}
public void Abort()
{
Aborted = true;
WorkItem.Cancel(true);
}
/// <summary>
/// Returns the thread's stack trace.
/// </summary>
/// <remarks>
/// May return one of two stack traces. First, tries to get the thread's active stack
/// trace. But this can fail, so as a fallback this method will return the stack
/// trace that was active when the task was queued.
/// </remarks>
public string GetStackTrace()
{
string ret = (context == null) ? "" : ("(" + context + ") ");
StackTrace activeStackTrace = Util.GetStackTrace(Thread);
if (activeStackTrace != null)
ret += activeStackTrace.ToString();
else if (StackTrace != null)
ret += "(Stack trace when queued) " + StackTrace;
// else, no stack trace available
return ret;
}
}
private static long nextThreadFuncNum = 0;
private static long numQueuedThreadFuncs = 0;
private static long numRunningThreadFuncs = 0;
private static long numTotalThreadFuncsCalled = 0;
private static Int32 threadFuncOverloadMode = 0;
public static long TotalQueuedFireAndForgetCalls { get { return numQueuedThreadFuncs; } }
public static long TotalRunningFireAndForgetCalls { get { return numRunningThreadFuncs; } }
// Maps (ThreadFunc number -> Thread)
private static ConcurrentDictionary<long, ThreadInfo> activeThreads = new ConcurrentDictionary<long, ThreadInfo>();
private static readonly int THREAD_TIMEOUT = 10 * 60 * 1000; // 10 minutes
/// <summary>
/// Finds threads in the main thread pool that have timed-out, and aborts them.
/// </summary>
private static void ThreadPoolWatchdog(object state)
{
foreach (KeyValuePair<long, ThreadInfo> entry in activeThreads)
{
ThreadInfo t = entry.Value;
if (t.DoTimeout && t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
{
m_log.WarnFormat("Timeout in threadfunc {0} ({1}) {2}", t.ThreadFuncNum, t.Thread.Name, t.GetStackTrace());
t.Abort();
ThreadInfo dummy;
activeThreads.TryRemove(entry.Key, out dummy);
// It's possible that the thread won't abort. To make sure the thread pool isn't
// depleted, increase the pool size.
// m_ThreadPool.MaxThreads++;
}
}
}
public static long TotalFireAndForgetCallsMade { get { return numTotalThreadFuncsCalled; } }
public static Dictionary<string, int> GetFireAndForgetCallsMade()
{
return new Dictionary<string, int>(m_fireAndForgetCallsMade);
}
private static Dictionary<string, int> m_fireAndForgetCallsMade = new Dictionary<string, int>();
public static Dictionary<string, int> GetFireAndForgetCallsInProgress()
{
return new Dictionary<string, int>(m_fireAndForgetCallsInProgress);
}
private static Dictionary<string, int> m_fireAndForgetCallsInProgress = new Dictionary<string, int>();
public static void FireAndForget(System.Threading.WaitCallback callback)
{
FireAndForget(callback, null, null);
}
public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
{
FireAndForget(callback, obj, null);
}
public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context, bool dotimeout = true)
{
Interlocked.Increment(ref numTotalThreadFuncsCalled);
WaitCallback realCallback;
bool loggingEnabled = LogThreadPool > 0;
long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum);
ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context, dotimeout);
if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
{
// If we're running regression tests, then we want any exceptions to rise up to the test code.
realCallback =
o =>
{
Culture.SetCurrentCulture();
callback(o);
};
}
else
{
// When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
// so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
// for decimals places but is read by a culture that treats commas as number seperators.
realCallback = o =>
{
long numQueued1 = Interlocked.Decrement(ref numQueuedThreadFuncs);
long numRunning1 = Interlocked.Increment(ref numRunningThreadFuncs);
threadInfo.Started();
activeThreads[threadFuncNum] = threadInfo;
try
{
if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
m_log.DebugFormat("Run threadfunc {0} (Queued {1}, Running {2})", threadFuncNum, numQueued1, numRunning1);
Culture.SetCurrentCulture();
callback(o);
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
m_log.Error(string.Format("[UTIL]: Util STP threadfunc {0} terminated with error ", threadFuncNum), e);
}
finally
{
Interlocked.Decrement(ref numRunningThreadFuncs);
threadInfo.Ended();
ThreadInfo dummy;
activeThreads.TryRemove(threadFuncNum, out dummy);
if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
m_log.DebugFormat("Exit threadfunc {0} ({1})", threadFuncNum, FormatDuration(threadInfo.Elapsed()));
}
};
}
long numQueued = Interlocked.Increment(ref numQueuedThreadFuncs);
try
{
threadInfo.LogThread = false;
switch (FireAndForgetMethod)
{
case FireAndForgetMethod.RegressionTest:
case FireAndForgetMethod.None:
realCallback.Invoke(obj);
break;
case FireAndForgetMethod.QueueUserWorkItem:
ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
break;
case FireAndForgetMethod.SmartThreadPool:
if (m_ThreadPool == null)
InitThreadPool(2, 15);
threadInfo.WorkItem = m_ThreadPool.QueueWorkItem((cb, o) => cb(o), realCallback, obj);
break;
case FireAndForgetMethod.Thread:
Thread thread = new Thread(delegate(object o) { realCallback(o); });
thread.Start(obj);
break;
default:
throw new NotImplementedException();
}
}
catch (Exception)
{
Interlocked.Decrement(ref numQueuedThreadFuncs);
ThreadInfo dummy;
activeThreads.TryRemove(threadFuncNum, out dummy);
throw;
}
}
/// <summary>
/// Returns whether the thread should be logged. Some very common threads aren't logged,
/// to avoid filling up the log.
/// </summary>
/// <param name="stackTrace">A partial stack trace of where the thread was queued</param>
/// <returns>Whether to log this thread</returns>
private static bool ShouldLogThread(string stackTrace)
{
if (LogThreadPool < 3)
{
if (stackTrace.Contains("BeginFireQueueEmpty"))
return false;
}
return true;
}
/// <summary>
/// Returns a stack trace for a thread added using FireAndForget().
/// </summary>
/// <param name="full">Will contain the full stack trace</param>
/// <param name="partial">Will contain only the first frame of the stack trace</param>
private static void GetFireAndForgetStackTrace(out string full, out string partial)
{
string src = Environment.StackTrace;
string[] lines = src.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder dest = new StringBuilder(src.Length);
bool started = false;
bool first = true;
partial = "";
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (!started)
{
// Skip the initial stack frames, because they're of no interest for debugging
if (line.Contains("StackTrace") || line.Contains("FireAndForget"))
continue;
started = true;
}
if (first)
{
line = line.TrimStart();
first = false;
partial = line;
}
bool last = (i == lines.Length - 1);
if (last)
dest.Append(line);
else
dest.AppendLine(line);
}
full = dest.ToString();
}
#pragma warning disable 0618
/// <summary>
/// Return the stack trace of a different thread.
/// </summary>
/// <remarks>
/// This is complicated because the thread needs to be paused in order to get its stack
/// trace. And pausing another thread can cause a deadlock. This method attempts to
/// avoid deadlock by using a short timeout (200ms), after which it gives up and
/// returns 'null' instead of the stack trace.
///
/// Take from: http://stackoverflow.com/a/14935378
///
/// WARNING: this doesn't work in Mono. See https://bugzilla.novell.com/show_bug.cgi?id=571691
///
/// </remarks>
/// <returns>The stack trace, or null if failed to get it</returns>
private static StackTrace GetStackTrace(Thread targetThread)
{
return null;
/*
not only this does not work on mono but it is not longer recomended on windows.
can cause deadlocks etc.
if (IsPlatformMono)
{
// This doesn't work in Mono
return null;
}
ManualResetEventSlim fallbackThreadReady = new ManualResetEventSlim();
ManualResetEventSlim exitedSafely = new ManualResetEventSlim();
try
{
new Thread(delegate()
{
fallbackThreadReady.Set();
while (!exitedSafely.Wait(200))
{
try
{
targetThread.Resume();
}
catch (Exception)
{
// Whatever happens, do never stop to resume the main-thread regularly until the main-thread has exited safely.
}
}
}).Start();
fallbackThreadReady.Wait();
// From here, you have about 200ms to get the stack-trace
targetThread.Suspend();
StackTrace trace = null;
try
{
trace = new StackTrace(targetThread, true);
}
catch (ThreadStateException)
{
//failed to get stack trace, since the fallback-thread resumed the thread
//possible reasons:
//1.) This thread was just too slow
//2.) A deadlock ocurred
//Automatic retry seems too risky here, so just return null.
}
try
{
targetThread.Resume();
}
catch (ThreadStateException)
{
// Thread is running again already
}
return trace;
}
finally
{
// Signal the fallack-thread to stop
exitedSafely.Set();
}
*/
}
#pragma warning restore 0618
/// <summary>
/// Get information about the current state of the smart thread pool.
/// </summary>
/// <returns>
/// null if this isn't the pool being used for non-scriptengine threads.
/// </returns>
public static STPInfo GetSmartThreadPoolInfo()
{
if (m_ThreadPool == null)
return null;
STPInfo stpi = new STPInfo();
stpi.Name = m_ThreadPool.Name;
stpi.STPStartInfo = m_ThreadPool.STPStartInfo;
stpi.IsIdle = m_ThreadPool.IsIdle;
stpi.IsShuttingDown = m_ThreadPool.IsShuttingdown;
stpi.MaxThreads = m_ThreadPool.MaxThreads;
stpi.MinThreads = m_ThreadPool.MinThreads;
stpi.InUseThreads = m_ThreadPool.InUseThreads;
stpi.ActiveThreads = m_ThreadPool.ActiveThreads;
stpi.WaitingCallbacks = m_ThreadPool.WaitingCallbacks;
stpi.MaxConcurrentWorkItems = m_ThreadPool.Concurrency;
return stpi;
}
public static void StopThreadPool()
{
if (m_ThreadPool == null)
return;
SmartThreadPool pool = m_ThreadPool;
m_ThreadPool = null;
try { pool.Shutdown(); } catch {}
}
#endregion FireAndForget Threading Pattern
/// <summary>
/// Environment.TickCount is an int but it counts all 32 bits so it goes positive
/// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
/// for the callers.
/// This trims it to a 12 day interval so don't let your frame time get too long.
/// </summary>
/// <returns></returns>
public static Int32 EnvironmentTickCount()
{
return Environment.TickCount & EnvironmentTickCountMask;
}
const Int32 EnvironmentTickCountMask = 0x3fffffff;
/// <summary>
/// Environment.TickCount is an int but it counts all 32 bits so it goes positive
/// and negative every 24.9 days. Subtracts the passed value (previously fetched by
/// 'EnvironmentTickCount()') and accounts for any wrapping.
/// </summary>
/// <param name="newValue"></param>
/// <param name="prevValue"></param>
/// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
{
Int32 diff = newValue - prevValue;
return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
}
/// <summary>
/// Environment.TickCount is an int but it counts all 32 bits so it goes positive
/// and negative every 24.9 days. Subtracts the passed value (previously fetched by
/// 'EnvironmentTickCount()') and accounts for any wrapping.
/// </summary>
/// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
{
return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
}
// Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
// Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
// A positive return value indicates A occured later than B
public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
{
// A, B and TC are all between 0 and 0x3fffffff
int tc = EnvironmentTickCount();
if (tc - tcA >= 0)
tcA += EnvironmentTickCountMask + 1;
if (tc - tcB >= 0)
tcB += EnvironmentTickCountMask + 1;
return tcA - tcB;
}
public static long GetPhysicalMemUse()
{
using (Process p = System.Diagnostics.Process.GetCurrentProcess())
return p.WorkingSet64;
}
// returns a timestamp in ms as double
// using the time resolution avaiable to StopWatch
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static double GetTimeStamp()
{
return Stopwatch.GetTimestamp() * TimeStampClockPeriod;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static double GetTimeStampMS()
{
return Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
}
// doing math in ticks is usefull to avoid loss of resolution
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static long GetTimeStampTicks()
{
return Stopwatch.GetTimestamp();
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static double TimeStampTicksToMS(long ticks)
{
return ticks * TimeStampClockPeriodMS;
}
/// <summary>
/// Formats a duration (given in milliseconds).
/// </summary>
public static string FormatDuration(int ms)
{
TimeSpan span = new TimeSpan(ms * TimeSpan.TicksPerMillisecond);
string str = "";
string suffix = null;
int hours = (int)span.TotalHours;
if (hours > 0)
{
str += hours.ToString(str.Length == 0 ? "0" : "00");
suffix = "hours";
}
if ((hours > 0) || (span.Minutes > 0))
{
if (str.Length > 0)
str += ":";
str += span.Minutes.ToString(str.Length == 0 ? "0" : "00");
if (suffix == null)
suffix = "min";
}
if ((hours > 0) || (span.Minutes > 0) || (span.Seconds > 0))
{
if (str.Length > 0)
str += ":";
str += span.Seconds.ToString(str.Length == 0 ? "0" : "00");
if (suffix == null)
suffix = "sec";
}
if (suffix == null)
suffix = "ms";
if (span.TotalMinutes < 1)
{
int ms1 = span.Milliseconds;
if (str.Length > 0)
{
ms1 /= 100;
str += ".";
}
str += ms1.ToString("0");
}
str += " " + suffix;
return str;
}
/// <summary>
/// Prints the call stack at any given point. Useful for debugging.
/// </summary>
public static void PrintCallStack()
{
PrintCallStack(m_log.DebugFormat);
}
public delegate void DebugPrinter(string msg, params Object[] parm);
public static void PrintCallStack(DebugPrinter printer)
{
StackTrace stackTrace = new StackTrace(true); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
// write call stack method names
foreach (StackFrame stackFrame in stackFrames)
{
MethodBase mb = stackFrame.GetMethod();
printer("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
}
}
/// <summary>
/// Gets the client IP address
/// </summary>
/// <param name="xff"></param>
/// <returns></returns>
public static IPEndPoint GetClientIPFromXFF(string xff)
{
if (xff == string.Empty)
return null;
string[] parts = xff.Split(new char[] { ',' });
if (parts.Length > 0)
{
try
{
return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
}
catch (Exception e)
{
m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
}
}
return null;
}
public static string GetCallerIP(Hashtable req)
{
if (req.ContainsKey("headers"))
{
try
{
Hashtable headers = (Hashtable)req["headers"];
if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
return headers["remote_addr"].ToString();
}
catch (Exception e)
{
m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
}
}
return string.Empty;
}
#region Xml Serialization Utilities
public static bool ReadBoolean(XmlReader reader)
{
// AuroraSim uses "int" for some fields that are boolean in OpenSim, e.g. "PassCollisions". Don't fail because of this.
reader.ReadStartElement();
string val = reader.ReadContentAsString().ToLower();
bool result = val.Equals("true") || val.Equals("1");
reader.ReadEndElement();
return result;
}
public static UUID ReadUUID(XmlReader reader, string name)
{
UUID id;
string idStr;
reader.ReadStartElement(name);
if (reader.Name == "Guid")
idStr = reader.ReadElementString("Guid");
else if (reader.Name == "UUID")
idStr = reader.ReadElementString("UUID");
else // no leading tag
idStr = reader.ReadContentAsString();
UUID.TryParse(idStr, out id);
reader.ReadEndElement();
return id;
}
public static Vector3 ReadVector(XmlReader reader, string name)
{
Vector3 vec;
reader.ReadStartElement(name);
vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
reader.ReadEndElement();
return vec;
}
public static Quaternion ReadQuaternion(XmlReader reader, string name)
{
Quaternion quat = new Quaternion();
reader.ReadStartElement(name);
while (reader.NodeType != XmlNodeType.EndElement)
{
switch (reader.Name.ToLower())
{
case "x":
quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
case "y":
quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
case "z":
quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
case "w":
quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
}
}
reader.ReadEndElement();
return quat;
}
public static T ReadEnum<T>(XmlReader reader, string name)
{
string value = reader.ReadElementContentAsString(name, String.Empty);
// !!!!! to deal with flags without commas
if (value.Contains(" ") && !value.Contains(","))
value = value.Replace(" ", ", ");
return (T)Enum.Parse(typeof(T), value); ;
}
#endregion
#region Universal User Identifiers
/// <summary>
/// Attempts to parse a UUI into its components: UUID, name and URL.
/// </summary>
/// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
/// <param name="uuid">the uuid part</param>
/// <param name="url">the endpoint part (e.g. http://foo.com)</param>
/// <param name="firstname">the first name part (e.g. Test)</param>
/// <param name="lastname">the last name part (e.g User)</param>
/// <param name="secret">the secret part</param>
public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
{
uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "UserUPUUI"; secret = string.Empty;
string[] parts = value.Split(';');
if (parts.Length >= 1)
if (!UUID.TryParse(parts[0], out uuid))
return false;
if (parts.Length >= 2)
url = parts[1];
if (parts.Length >= 3)
{
string[] name = parts[2].Split();
if (name.Length == 2)
{
firstname = name[0];
lastname = name[1];
}
}
if (parts.Length >= 4)
secret = parts[3];
return true;
}
/// <summary>
/// For foreign avatars, extracts their original name and Server URL from their First Name and Last Name.
/// </summary>
public static bool ParseForeignAvatarName(string firstname, string lastname,
out string realFirstName, out string realLastName, out string serverURI)
{
realFirstName = realLastName = serverURI = string.Empty;
if (!lastname.Contains("@"))
return false;
if (!firstname.Contains("."))
return false;
realFirstName = firstname.Split('.')[0];
realLastName = firstname.Split('.')[1];
serverURI = new Uri("http://" + lastname.Replace("@", "")).ToString();
return true;
}
/// <summary>
/// Produces a universal (HG) system-facing identifier given the information
/// </summary>
/// <param name="acircuit"></param>
/// <returns>uuid[;homeURI[;first last]]</returns>
public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
{
if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, acircuit.ServiceURLs["HomeURI"].ToString());
else
return acircuit.AgentID.ToString();
}
/// <summary>
/// Produces a universal (HG) system-facing identifier given the information
/// </summary>
/// <param name="id">UUID of the user</param>
/// <param name="firstName">first name (e.g Test)</param>
/// <param name="lastName">last name (e.g. User)</param>
/// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
/// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
{
string agentsURI = homeURI;
if (!agentsURI.EndsWith("/"))
agentsURI += "/";
// This is ugly, but there's no other way, given that the name is changed
// in the agent circuit data for foreigners
if (lastName.Contains("@"))
{
string[] parts = firstName.Split(new char[] { '.' });
if (parts.Length == 2)
return CalcUniversalIdentifier(id, agentsURI, parts[0] + " " + parts[1]);
}
return CalcUniversalIdentifier(id, agentsURI, firstName + " " + lastName);
}
private static string CalcUniversalIdentifier(UUID id, string agentsURI, string name)
{
return id.ToString() + ";" + agentsURI + ";" + name;
}
/// <summary>
/// Produces a universal (HG) user-facing name given the information
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="homeURI"></param>
/// <returns>string of the form first.last @foo.com or first last</returns>
public static string UniversalName(String firstName, String lastName, String homeURI)
{
Uri uri = null;
try
{
uri = new Uri(homeURI);
}
catch (UriFormatException)
{
return firstName + " " + lastName;
}
return firstName + "." + lastName + " " + "@" + uri.Authority;
}
#endregion
/// <summary>
/// Escapes the special characters used in "LIKE".
/// </summary>
/// <remarks>
/// For example: EscapeForLike("foo_bar%baz") = "foo\_bar\%baz"
/// </remarks>
public static string EscapeForLike(string str)
{
return str.Replace("_", "\\_").Replace("%", "\\%");
}
/// <summary>
/// Returns the name of the user's viewer.
/// </summary>
/// <remarks>
/// This method handles two ways that viewers specify their name:
/// 1. Viewer = "Firestorm-Release 4.4.2.34167", Channel = "(don't care)" -> "Firestorm-Release 4.4.2.34167"
/// 2. Viewer = "4.5.1.38838", Channel = "Firestorm-Beta" -> "Firestorm-Beta 4.5.1.38838"
/// </remarks>
public static string GetViewerName(AgentCircuitData agent)
{
string name = agent.Viewer;
if (name == null)
name = "";
else
name = name.Trim();
// Check if 'Viewer' is just a version number. If it's *not*, then we
// assume that it contains the real viewer name, and we return it.
foreach (char c in name)
{
if (Char.IsLetter(c))
return name;
}
// The 'Viewer' string contains just a version number. If there's anything in
// 'Channel' then assume that it's the viewer name.
if ((agent.Channel != null) && (agent.Channel.Length > 0))
name = agent.Channel.Trim() + " " + name;
return name;
}
public static void LogFailedXML(string message, string xml)
{
int length = xml.Length;
if (length > 2000)
xml = xml.Substring(0, 2000) + "...";
for (int i = 0 ; i < xml.Length ; i++)
{
if (xml[i] < 0x20)
{
xml = "Unprintable binary data";
break;
}
}
m_log.ErrorFormat("{0} Failed XML ({1} bytes) = {2}", message, length, xml);
}
/// <summary>
/// Performs a high quality image resize
/// </summary>
/// <param name="image">Image to resize</param>
/// <param name="width">New width</param>
/// <param name="height">New height</param>
/// <returns>Resized image</returns>
public static Bitmap ResizeImageSolid(Image image, int width, int height)
{
Bitmap result = new Bitmap(width, height, PixelFormat.Format24bppRgb);
using (ImageAttributes atrib = new ImageAttributes())
using (Graphics graphics = Graphics.FromImage(result))
{
atrib.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
atrib.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
graphics.DrawImage(image,new Rectangle(0,0, result.Width, result.Height),
0, 0, image.Width, image.Height, GraphicsUnit.Pixel, atrib);
}
return result;
}
public static void SaveAssetToFile(string filename, byte[] data)
{
string assetPath = "UserAssets";
if (!Directory.Exists(assetPath))
{
Directory.CreateDirectory(assetPath);
}
FileStream fs = File.Create(Path.Combine(assetPath, filename));
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data);
bw.Close();
fs.Close();
}
}
/* don't like this code
public class DoubleQueue<T> where T:class
{
private Queue<T> m_lowQueue = new Queue<T>();
private Queue<T> m_highQueue = new Queue<T>();
private object m_syncRoot = new object();
private Semaphore m_s = new Semaphore(0, 1);
public DoubleQueue()
{
}
public virtual int Count
{
get
{
lock (m_syncRoot)
return m_highQueue.Count + m_lowQueue.Count;
}
}
public virtual void Enqueue(T data)
{
Enqueue(m_lowQueue, data);
}
public virtual void EnqueueLow(T data)
{
Enqueue(m_lowQueue, data);
}
public virtual void EnqueueHigh(T data)
{
Enqueue(m_highQueue, data);
}
private void Enqueue(Queue<T> q, T data)
{
lock (m_syncRoot)
{
q.Enqueue(data);
m_s.WaitOne(0);
m_s.Release();
}
}
public virtual T Dequeue()
{
return Dequeue(Timeout.Infinite);
}
public virtual T Dequeue(int tmo)
{
return Dequeue(TimeSpan.FromMilliseconds(tmo));
}
public virtual T Dequeue(TimeSpan wait)
{
T res = null;
if (!Dequeue(wait, ref res))
return null;
return res;
}
public bool Dequeue(int timeout, ref T res)
{
return Dequeue(TimeSpan.FromMilliseconds(timeout), ref res);
}
public bool Dequeue(TimeSpan wait, ref T res)
{
if (!m_s.WaitOne(wait))
return false;
lock (m_syncRoot)
{
if (m_highQueue.Count > 0)
res = m_highQueue.Dequeue();
else if (m_lowQueue.Count > 0)
res = m_lowQueue.Dequeue();
if (m_highQueue.Count == 0 && m_lowQueue.Count == 0)
return true;
try
{
m_s.Release();
}
catch
{
}
return true;
}
}
public virtual void Clear()
{
lock (m_syncRoot)
{
// Make sure sem count is 0
m_s.WaitOne(0);
m_lowQueue.Clear();
m_highQueue.Clear();
}
}
}
*/
public class BetterRandom
{
private const int BufferSize = 1024; // must be a multiple of 4
private byte[] RandomBuffer;
private int BufferOffset;
private RNGCryptoServiceProvider rng;
public BetterRandom()
{
RandomBuffer = new byte[BufferSize];
rng = new RNGCryptoServiceProvider();
BufferOffset = RandomBuffer.Length;
}
private void FillBuffer()
{
rng.GetBytes(RandomBuffer);
BufferOffset = 0;
}
public int Next()
{
if (BufferOffset >= RandomBuffer.Length)
{
FillBuffer();
}
int val = BitConverter.ToInt32(RandomBuffer, BufferOffset) & 0x7fffffff;
BufferOffset += sizeof(int);
return val;
}
public int Next(int maxValue)
{
return Next() % maxValue;
}
public int Next(int minValue, int maxValue)
{
if (maxValue < minValue)
{
throw new ArgumentOutOfRangeException("maxValue must be greater than or equal to minValue");
}
int range = maxValue - minValue;
return minValue + Next(range);
}
public double NextDouble()
{
int val = Next();
return (double)val / int.MaxValue;
}
public void GetBytes(byte[] buff)
{
rng.GetBytes(buff);
}
}
}
| 35.308564 | 167 | 0.50066 | [
"BSD-3-Clause"
] | joseenriquegomezrodriguez/opensim | OpenSim/Framework/Util.cs | 140,175 | C# |
using Platform.Network.ExtensibleServer;
using Platform.Network.ExtensibleServer.CommandServer;
namespace Platform.VirtualFileSystem.Network.Text.Server
{
[TextCommandSpecification("GETPOSITION", RandomAccessRunLevel.NAME)]
public class GetPositionCommandProcessor
: FileSystemTextCommandProcessorWithOptions
{
protected class CommandOptions
{
}
public GetPositionCommandProcessor(Connection connection)
: base(connection)
{
}
public override void Process(Command command)
{
var stream = ((RandomAccessRunLevel)Connection.RunLevel).Stream;
Connection.WriteOk("position", stream.Position.ToString());
Connection.Flush();
}
}
}
| 23.965517 | 70 | 0.752518 | [
"BSD-3-Clause"
] | MarcelRaschke/Platform.VirtualFileSystem | src/Platform.VirtualFileSystem.Network.Text.Server/GetPositionCommandProcessor.cs | 695 | C# |
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.Ubigia.Api.Functional.Antlr
{
using EtAlii.Ubigia.Api.Functional.Context;
public partial class UbigiaVisitor
{
public override object VisitSchema(UbigiaParser.SchemaContext context)
{
var text = context.GetText();
text = text
.Substring(0, text.Length - 5) // Remove the <EOF> at the end.
.Replace("\r\n","\n")
.TrimEnd('\n');
var fragmentContext = context.structure_fragment();
var namespaceContext = context.header_option_namespace();
var @namespace = namespaceContext != null
? (string)VisitHeader_option_namespace(namespaceContext)
: null;
return fragmentContext != null
? new Schema((StructureFragment)VisitStructure_fragment(fragmentContext), @namespace, null, text)
: null;
}
public override object VisitHeader_option_namespace(UbigiaParser.Header_option_namespaceContext context) => context.@namespace().GetText();
}
}
| 38.516129 | 147 | 0.630653 | [
"MIT"
] | vrenken/EtAlii.Ubigia | Source/Api/EtAlii.Ubigia.Api.Functional.Antlr/UbigiaVisitor.Schema.cs | 1,194 | C# |
using System;
namespace SubstituteUnitTests.Models
{
public interface IParameter
{
string Name { get; }
Type Type { get; }
object Value { get; set; }
}
} | 17.363636 | 36 | 0.581152 | [
"MIT"
] | RotemKir/SubstituteUnitTests | SubstituteUnitTests/Models/IParameter.cs | 193 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace XPump.Model
{
using System;
using System.Collections.Generic;
public partial class shiftsttak
{
public int id { get; set; }
public System.DateTime takdat { get; set; }
public decimal qty { get; set; }
public int shiftsales_id { get; set; }
public int section_id { get; set; }
public string creby { get; set; }
public System.DateTime cretime { get; set; }
public string chgby { get; set; }
public Nullable<System.DateTime> chgtime { get; set; }
public virtual section section { get; set; }
public virtual shiftsales shiftsales { get; set; }
}
}
| 35.354839 | 85 | 0.538321 | [
"MIT"
] | wee2tee/XPump | XPump/Model/shiftsttak.cs | 1,096 | C# |
using TradeProcessing.Configuration.Service;
namespace TradeProcessing.Configuration
{
public class AppConfig
{
public TradeProcessingServiceSettings TradeProcessingService { get; set; }
}
}
| 21.3 | 82 | 0.755869 | [
"Apache-2.0"
] | SC-Poc/Service.TradeProcessing | src/TradeProcessing/Configuration/AppConfig.cs | 215 | C# |
using FeatureSwitcher.Configuration;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace FeatureSwitcher.VstsConfiguration.Tests
{
[TestClass]
public class ConfigureVstsTests
{
[TestMethod]
public void ConfigureVsts_features_can_be_configured_by_VSTS()
{
var result = Features.Are.ConfiguredBy.VstsConfig();
result.Should().BeOfType<ConfigureVsts>();
}
[TestMethod]
public void ConfigureVsts_with_default_config()
{
var result = Features.Are.ConfiguredBy.VstsConfig();
var expected = new VstsSettings();
var actual = ((ConfigureVsts)result).Settings;
actual.Should().BeEquivalentTo(expected);
}
[TestMethod]
public void ConfigureVsts_with_custom_settings()
{
var settings = new VstsSettings { NameField = "CustomSettings" };
var result = Features.Are.ConfiguredBy.VstsConfig().WithSettings(settings);
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.NameField.Should().Be("CustomSettings");
}
[TestMethod]
public void ConfigureVsts_with_VSTS_Url()
{
var settings = new VstsSettings { Url = new Uri("http://settingshost") };
var expected = new Uri("http://explicithost");
var result = Features.Are.ConfiguredBy
.VstsConfig()
.WithSettings(settings)
.WithVSTSUrl(expected);
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.Url.Should().Be(expected);
}
[TestMethod]
public void ConfigureVsts_with_PrivateAccessToken()
{
var settings = new VstsSettings { PrivateAccessToken = "settingspat" };
var expected = "explicit pat";
var result = Features.Are.ConfiguredBy
.VstsConfig()
.WithSettings(settings)
.WithPrivateAccessToken(expected);
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.PrivateAccessToken.Should().Be(expected);
}
[TestMethod]
public void ConfigureVsts_with_CacheTimeout()
{
var settings = new VstsSettings { CacheTimeout = TimeSpan.FromDays(1) };
var expected = TimeSpan.FromMilliseconds(1);
var result = Features.Are.ConfiguredBy
.VstsConfig()
.WithSettings(settings)
.WithCacheTimeout(expected);
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.CacheTimeout.Should().Be(expected);
}
[TestMethod]
public void ConfigureVsts_with_Environment()
{
var settings = new VstsSettings();
var result = Features.Are.ConfiguredBy
.VstsConfig()
.WithSettings(settings)
.WithEnvironment("XXX");
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.AdditionalQueryFilter.Should().Contain("XXX");
}
[TestMethod]
public void ConfigureVsts_with_WorkItemType()
{
var settings = new VstsSettings() { WorkItemType = "Old" };
var result = Features.Are.ConfiguredBy
.VstsConfig()
.WithSettings(settings)
.WithWorkItemType("New");
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.WorkItemType.Should().Be("New");
}
[TestMethod]
public void ConfigureVsts_with_NameField()
{
var settings = new VstsSettings() { NameField = "Old" };
var result = Features.Are.ConfiguredBy
.VstsConfig()
.WithSettings(settings)
.WithNameField("New");
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.NameField.Should().Be("New");
}
[TestMethod]
public void ConfigureVsts_with_ValueField()
{
var settings = new VstsSettings() { ValueField = "Old" };
var result = Features.Are.ConfiguredBy
.VstsConfig()
.WithSettings(settings)
.WithValueField("New");
result.Should().NotBeNull();
((ConfigureVsts)result).Settings.ValueField.Should().Be("New");
}
}
} | 31.157534 | 91 | 0.575291 | [
"MIT"
] | 6heads/FeatureSwitcher.VstsConfiguration | test/FeatureSwitcher.VstsConfiguration.Tests/ConfigureVstsTests.cs | 4,551 | 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("LogicOperators")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LogicOperators")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("40281d8c-b600-4b26-aab3-2d14ea35b7cd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.72973 | 84 | 0.748567 | [
"MIT"
] | VanHakobyan/ISTC_Coding_School | ISTC.FirtStage/ISTC.FirtsStage.LogicOperators/Properties/AssemblyInfo.cs | 1,399 | C# |
using AssetsTools.NET;
public class Constants
{
public static readonly uint[] editDifferScriptNEHash = new uint[] { 0x6eb46069, 0x5eda7d6c, 0xbfd0ce46, 0xadf887b5 };
public static readonly uint[] sceneMetadataScriptNEHash = new uint[] { 0x993f3608, 0x2cc0f87e, 0xca6371c5, 0x4ed77624 };
//315b6d2463669124586f57520d2ce601
public static readonly long editDifferMsEditorScriptHash = 0x4219663642d6b513;
public static readonly long editDifferLsEditorScriptHash = 0x106ec2d02575f685;
//9ac32aa6b7be9a74f9ba4bef659fcb97
public static readonly long sceneMetadataMsEditorScriptHash = 0x47a9eb7b6aa23ca9;
public static readonly long sceneMetadataLsEditorScriptHash = 0x79bcf956feb4ab9f;
}
public enum Flags
{
None = 0x0,
HideInEditorMask = 0x1,
NotEditableMask = 0x10,
StrongPPtrMask = 0x40,
TreatIntegerValueAsBoolean = 0x100,
DebugPropertyMask = 0x1000,
AlignBytesFlag = 0x4000,
AnyChildUsesAlignBytesFlag = 0x8000,
IgnoreInMetaFiles = 0x80000,
TransferAsArrayEntryNameInMetaFiles = 0x100000,
TransferUsingFlowMappingStyle = 0x200000,
GenerateBitwiseDifferences = 0x400000,
DontAnimate = 0x800000,
TransferHex64 = 0x1000000,
CharPropertyMask = 0x2000000,
DontValidateUTF8 = 0x4000000
} | 39.90625 | 124 | 0.776038 | [
"MIT"
] | asyncrun/HKWorldEdit2 | Assets/Editor/Bundler/Constants.cs | 1,279 | C# |
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using ReserveBlockCore.Data;
using ReserveBlockCore.Models;
using ReserveBlockCore.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace ReserveBlockCore.P2P
{
public class P2PServer : Hub
{
private static Dictionary<string, string> PeerList = new Dictionary<string, string>();
public static Dictionary<string, int> TxRebroadcastDict = new Dictionary<string, int>();
#region Broadcast methods
public override async Task OnConnectedAsync()
{
var peerIP = GetIP(Context);
var blockHeight = BlockchainData.GetHeight();
PeerList.Add(Context.ConnectionId, peerIP);
await SendMessage("IP", peerIP);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? ex)
{
string connectionId = Context.ConnectionId;
var check = PeerList.ContainsKey(connectionId);
if (check == true)
{
var peer = PeerList.FirstOrDefault(x => x.Key == connectionId);
var ip = peer.Value;
//await SendMessageAllPeers(ip);
//do some logic
}
}
public async Task SendMessage(string message, string data)
{
await Clients.Caller.SendAsync("GetMessage", message, data);
}
public async Task SendMessageAllPeers(string message, string data)
{
await Clients.All.SendAsync("GetMessage", message, data);
}
public async Task SendMessageAllValidators(string ip)
{
await Clients.All.SendAsync("GetMessage", "NewBlock");
}
#endregion
#region Receive Block
public async Task ReceiveBlock(Block nextBlock)
{
if(Program.BlocksDownloading == false)
{
Console.WriteLine("Found Block: " + nextBlock.Height.ToString());
await BlockQueueService.ProcessBlockQueue();
var nextHeight = BlockchainData.GetHeight() + 1;
var currentHeight = nextBlock.Height;
if (nextHeight == currentHeight)
{
//var result = await BlockValidatorService.ValidateBlock(nextBlock);
var broadcast = await BlockQueueService.AddBlock(nextBlock);
if (broadcast == true)
{
string data = "";
data = JsonConvert.SerializeObject(nextBlock);
await SendMessageAllPeers("blk", data);
}
}
if(nextHeight < currentHeight)
{
// means we need to download some blocks
Program.BlocksDownloading = true;
var setDownload = await BlockDownloadService.GetAllBlocks(currentHeight);
Program.BlocksDownloading = setDownload;
}
}
}
#endregion
#region Send list of Validators to peer
public async Task<List<Validators>?> SendValidators()
{
var validators = Validators.Validator.GetAll();
var validatorList = validators.FindAll().ToList();
if (validatorList.Count() == 0)
return null;
//Only send 10 as that will be plenty.
if (validatorList.Count() > 10)
return validatorList.Take(10).ToList();
return validatorList;
}
#endregion
#region Get Validator Count
public async Task<long?> SendValidatorCount()
{
var validators = Validators.Validator.GetAll();
var validatorList = validators.FindAll().ToList();
if (validatorList.Count() == 0)
return null;
return (long)validatorList.Count();
}
#endregion
#region Connect Peers
//Send hello status to connecting peers from p2p server
public async Task ConnectPeers(string node, string message, string time)
{
long ticks = Convert.ToInt64(time);
DateTime timeTicks = new DateTime(ticks);
var feature = Context.Features.Get<IHttpConnectionFeature>();
var peerIP = feature.RemoteIpAddress.MapToIPv4().ToString();
if (message == "Hello")
{
var oNode = "Origin Node";
var oMessage = "Connected to IP: " + peerIP;
var endTime = DateTime.UtcNow;
var totalTime = (endTime - timeTicks).TotalMilliseconds;
await Clients.Caller.SendAsync("PeerConnected", oNode, oMessage, totalTime.ToString("0"), BlockchainData.ChainRef);
}
}
#endregion
#region Ping Peers
public async Task<string> PingPeers()
{
var peerIP = GetIP(Context);
var peerDB = Peers.GetAll();
var peer = peerDB.FindOne(x => x.PeerIP == peerIP);
if(peer == null)
{
//this does a ping back on the peer to see if it can also be an outgoing node.
var result = await P2PClient.PingBackPeer(peerIP);
Peers nPeer = new Peers {
FailCount = 0,
IsIncoming = true,
IsOutgoing = result,
PeerIP = peerIP,
};
peerDB.Insert(nPeer);
}
return "HelloPeer";
}
public async Task<string> PingBackPeer()
{
return "HelloBackPeer";
}
#endregion
#region Send Block Height
public async Task<long> SendBlockHeight()
{
var blocks = BlockchainData.GetBlocks();
if (blocks.FindAll().Count() != 0)
{
var blockHeight = BlockchainData.GetHeight();
return blockHeight;
}
return -1;
}
#endregion
#region Send Block
//Send Block to client from p2p server
public async Task<Block?> SendBlock(long currentBlock)
{
var peerIP = GetIP(Context);
var message = "";
var nextBlockHeight = currentBlock + 1;
var nextBlock = BlockchainData.GetBlockByHeight(nextBlockHeight);
if (nextBlock != null)
{
return nextBlock;
}
else
{
return null;
}
}
#endregion
#region Send to Mempool
public async Task<string> SendTxToMempool(Transaction txReceived)
{
var result = "";
var data = JsonConvert.SerializeObject(txReceived);
var mempool = TransactionData.GetPool();
if (mempool.Count() != 0)
{
var txFound = mempool.FindOne(x => x.Hash == txReceived.Hash);
if (txFound == null)
{
var isTxStale = await TransactionData.IsTxTimestampStale(txReceived);
if(!isTxStale)
{
var txResult = await TransactionValidatorService.VerifyTX(txReceived); //sends tx to connected peers
if (txResult == false)
{
try
{
mempool.DeleteMany(x => x.Hash == txReceived.Hash);// tx has been crafted into block. Remove.
}
catch (Exception ex)
{
//delete failed
}
return "TFVP";
}
var dblspndChk = await TransactionData.DoubleSpendCheck(txReceived);
var isCraftedIntoBlock = await TransactionData.HasTxBeenCraftedIntoBlock(txReceived);
if (txResult == true && dblspndChk == false && isCraftedIntoBlock == false)
{
mempool.Insert(txReceived);
await SendMessageAllPeers("tx", data);
P2PClient.SendTXMempool(txReceived);
return "ATMP";//added to mempool
}
else
{
try
{
mempool.DeleteMany(x => x.Hash == txReceived.Hash);// tx has been crafted into block. Remove.
}
catch (Exception ex)
{
//delete failed
}
return "TFVP"; //transaction failed verification process
}
}
}
else
{
var isTxStale = await TransactionData.IsTxTimestampStale(txReceived);
if (!isTxStale)
{
var isCraftedIntoBlock = await TransactionData.HasTxBeenCraftedIntoBlock(txReceived);
if (!isCraftedIntoBlock)
{
//await SendMessageAllPeers("tx", data); // send to everyone connected to me (In connects)
//P2PClient.SendTXMempool(txReceived); // send to everyone I am connected too (out connects)
}
else
{
try
{
mempool.DeleteMany(x => x.Hash == txReceived.Hash);// tx has been crafted into block. Remove.
}
catch (Exception ex)
{
//delete failed
}
}
return "AIMP"; //already in mempool
}
else
{
try
{
mempool.DeleteMany(x => x.Hash == txReceived.Hash);// tx has been crafted into block. Remove.
}
catch (Exception ex)
{
//delete failed
}
}
}
}
else
{
var isTxStale = await TransactionData.IsTxTimestampStale(txReceived);
if (!isTxStale)
{
var txResult = await TransactionValidatorService.VerifyTX(txReceived);
if (txResult == false)
{
try
{
mempool.DeleteMany(x => x.Hash == txReceived.Hash);// tx has been crafted into block. Remove.
}
catch (Exception ex)
{
//delete failed
}
return "TFVP";
}
var dblspndChk = await TransactionData.DoubleSpendCheck(txReceived);
var isCraftedIntoBlock = await TransactionData.HasTxBeenCraftedIntoBlock(txReceived);
if (txResult == true && dblspndChk == false && isCraftedIntoBlock == false)
{
mempool.Insert(txReceived);
await SendMessageAllPeers("tx", data); //sends tx to connected peers
return "ATMP";//added to mempool
}
else
{
try
{
mempool.DeleteMany(x => x.Hash == txReceived.Hash);// tx has been crafted into block. Remove.
}
catch (Exception ex)
{
//delete failed
}
return "TFVP"; //transaction failed verification process
}
}
}
return "";
}
#endregion
#region Get Masternodes
public async Task<List<Validators>?> GetMasternodes(int valCount)
{
var validatorList = Validators.Validator.GetAll();
var validatorListCount = validatorList.Count();
if(validatorListCount == 0)
{
return null;
}
else
{
if(valCount == 0)
{
return validatorList.FindAll().ToList();
}
else
{
if(valCount < validatorListCount)
{
return validatorList.FindAll().ToList();
}
}
}
return null;
}
#endregion
#region Send Validator - Receives the new validator
public async Task<string> SendValidator(Validators validator)
{
var peerIP = GetIP(Context);
validator.NodeIP = peerIP;
string data = "";
if(validator.NodeReferenceId == null)
{
return "FTAV";
}
if(validator.NodeReferenceId != BlockchainData.ChainRef)
{
return "FTAV";
}
var updateMasternodes = await P2PClient.GetMasternodes();
var validatorList = Validators.Validator.GetAll();
if (validatorList.Count() != 0)
{
var valFound = validatorList.FindOne(x => x.Address == validator.Address); // basically if a validator stays offline the address because blacklisted
if (valFound == null)
{
var result = ValidatorService.ValidateTheValidator(validator);
if (result == true)
{
var valPosFound = validatorList.FindOne(x => x.Position == validator.Position);
if(valPosFound != null)
{
validator.Position = validatorList.FindAll().Count() + 1; //adding just in case positions are off.
}
validatorList.Insert(validator);
data = JsonConvert.SerializeObject(validator);
await SendMessageAllPeers("val", data);
return "VATN";//added to validator list
}
else
{
return "FTAV"; //validator failed verification process
}
}
else
{
//Update found record with new information
var result = ValidatorService.ValidateTheValidator(validator);
if (result == true)
{
var valPosFound = validatorList.FindOne(x => x.Position == validator.Position);
if (valPosFound != null)
{
validator.Position = validatorList.FindAll().Count() + 1; //adding just in case positions are off.
}
valFound.Amount = validator.Amount;
valFound.Signature = validator.Signature;
valFound.Address = validator.Address;
valFound.IsActive = validator.IsActive;
valFound.EligibleBlockStart = validator.EligibleBlockStart;
valFound.UniqueName = validator.UniqueName;
valFound.FailCount = validator.FailCount;
valFound.Position = validator.Position;
valFound.NodeReferenceId = validator.NodeReferenceId;
validatorList.Update(valFound);
data = JsonConvert.SerializeObject(valFound);
await SendMessageAllPeers("val", data);
}
return "AIVL"; //already in validator list
}
}
else
{
var result = ValidatorService.ValidateTheValidator(validator);
if (result == true)
{
validatorList.Insert(validator);
Validators.Validator.Initialize();
return "VATN";//added to validator list
}
else
{
return "FTAV"; //validator failed verification process
}
}
}
#endregion
#region Ping Next Validator
public async Task<bool> PingNextValidator()
{
return true;
}
#endregion
#region Call Crafter
public async Task<bool> CallCrafter()
{
return true;
}
#endregion
#region Seed node check
public async Task<string> SeedNodeCheck()
{
//do check for validator. if yes return val otherwise return Hello.
var validators = Validators.Validator.GetAll();
var hasValidators = validators.FindAll().Where(x => x.NodeIP == "SELF").Count(); //revise this to use local account and IsValidating
if(hasValidators > 0)
return "HelloVal";
return "Hello";
}
#endregion
#region Get IP
private static string GetIP(HubCallerContext context)
{
var feature = context.Features.Get<IHttpConnectionFeature>();
var peerIP = feature.RemoteIpAddress.MapToIPv4().ToString();
return peerIP;
}
#endregion
}
}
| 34.433579 | 164 | 0.467717 | [
"MIT"
] | treyhicks236/ReserveBlockCore | ReserveBlockCore/P2P/P2PServer.cs | 18,665 | C# |
/// <summary>
/// Author: Krzysztof Dobrzyński
/// Project: Chemistry.NET
/// Source: https://github.com/Sejoslaw/Chemistry.NET
/// </summary>
namespace Chemistry.NET.Particles.Models
{
public partial class Fermion : Particle
{
public int Generation { get; }
public Fermion(string name, string symbol, double mass, double charge, double spin, int generation)
: base(name, symbol, mass, charge, spin)
{
Generation = generation;
}
}
}
| 25 | 107 | 0.634 | [
"MIT"
] | Sejoslaw/Chemistry.NET | Chemistry.NET/Particles/Models/Fermion.cs | 501 | 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("NCR.Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NCR.Library")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7304f5a6-8d3c-4d22-ab11-9d962cffe4a9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.702703 | 84 | 0.743369 | [
"Apache-2.0"
] | elyor0529/NCR | NCR.Library/Properties/AssemblyInfo.cs | 1,398 | C# |
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.Rendering.Universal.PostProcessing;
using UnityEngine.Scripting;
// Mercilessly cannibalised from the tutorial on https://github.com/yahiaetman/URPCustomPostProcessingStack
// lowkey kinda bullshit how I have to use a package to do what's natively supported in HDRP for like 2 years now thanks unity
[System.Serializable, VolumeComponentMenu("CustomPostProcess/Damage")]
public class DamageEffect : VolumeComponent
{
[Tooltip("Intensity of the effect.")]
public ClampedFloatParameter intensity = new ClampedFloatParameter(0, 0, 1);
[Tooltip("Hue shift of the effect.")]
public ClampedFloatParameter shift = new ClampedFloatParameter(0, -360, 360);
}
[CustomPostProcess("Damage", CustomPostProcessInjectionPoint.BeforePostProcess), Preserve]
public class DamageEffectRenderer : CustomPostProcessRenderer
{
private DamageEffect m_VolumeComponent;
private Material m_Material;
static class ShaderIDs
{
internal readonly static int Input = Shader.PropertyToID("_MainTex");
internal readonly static int Intensity = Shader.PropertyToID("_Intensity");
internal readonly static int Shift = Shader.PropertyToID("_Shift");
}
public override bool visibleInSceneView => true;
public override ScriptableRenderPassInput input => ScriptableRenderPassInput.Color;
[Preserve]
public override void Initialize()
{
m_Material = CoreUtils.CreateEngineMaterial("Custom/DamageShader");
}
[Preserve]
public override bool Setup(ref RenderingData renderingData, CustomPostProcessInjectionPoint injectionPoint)
{
var stack = VolumeManager.instance.stack;
m_VolumeComponent = stack.GetComponent<DamageEffect>();
return m_VolumeComponent.intensity.value > 0;
}
[Preserve]
public override void Render(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, ref RenderingData renderingData, CustomPostProcessInjectionPoint injectionPoint)
{
if (m_Material != null)
{
m_Material.SetFloat(ShaderIDs.Intensity, m_VolumeComponent.intensity.value);
m_Material.SetFloat(ShaderIDs.Shift, m_VolumeComponent.shift.value);
}
cmd.SetGlobalTexture(ShaderIDs.Input, source);
CoreUtils.DrawFullScreen(cmd, m_Material, destination);
}
} | 36.903226 | 195 | 0.806381 | [
"MIT"
] | Phanty133/VITC2021 | Assets/Scripts/Post Processing/DamageEffect.cs | 2,288 | C# |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.42.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Cloud Billing API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/billing/'>Cloud Billing API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20191111 (1775)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/billing/'>
* https://cloud.google.com/billing/</a>
* <tr><th>Discovery Name<td>cloudbilling
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Cloud Billing API can be found at
* <a href='https://cloud.google.com/billing/'>https://cloud.google.com/billing/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Cloudbilling.v1
{
/// <summary>The Cloudbilling Service.</summary>
public class CloudbillingService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudbillingService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudbillingService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
billingAccounts = new BillingAccountsResource(this);
projects = new ProjectsResource(this);
services = new ServicesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "cloudbilling"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
get { return BaseUriOverride ?? "https://cloudbilling.googleapis.com/"; }
#else
get { return "https://cloudbilling.googleapis.com/"; }
#endif
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://cloudbilling.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Cloud Billing API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Cloud Billing API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
}
private readonly BillingAccountsResource billingAccounts;
/// <summary>Gets the BillingAccounts resource.</summary>
public virtual BillingAccountsResource BillingAccounts
{
get { return billingAccounts; }
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
private readonly ServicesResource services;
/// <summary>Gets the Services resource.</summary>
public virtual ServicesResource Services
{
get { return services; }
}
}
///<summary>A base abstract class for Cloudbilling requests.</summary>
public abstract class CloudbillingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudbillingBaseServiceRequest instance.</summary>
protected CloudbillingBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Cloudbilling parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "billingAccounts" collection of methods.</summary>
public class BillingAccountsResource
{
private const string Resource = "billingAccounts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public BillingAccountsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
projects = new ProjectsResource(service);
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists the projects associated with a billing account. The current authenticated user must have
/// the `billing.resourceAssociations.list` IAM permission, which is often given to billing account
/// [viewers](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
/// <param name="name">The resource name of the billing account associated with the projects that you want to list. For
/// example, `billingAccounts/012345-567890-ABCDEF`.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists the projects associated with a billing account. The current authenticated user must have
/// the `billing.resourceAssociations.list` IAM permission, which is often given to billing account
/// [viewers](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListProjectBillingInfoResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource name of the billing account associated with the projects that you want to
/// list. For example, `billingAccounts/012345-567890-ABCDEF`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>A token identifying a page of results to be returned. This should be a `next_page_token`
/// value returned from a previous `ListProjectBillingInfo` call. If unspecified, the first page of
/// results is returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Requested page size. The maximum page size is 100; this is also the default.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}/projects"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Creates a billing account. This method can only be used to create [billing
/// subaccounts](https://cloud.google.com/billing/docs/concepts) by GCP resellers. When creating a subaccount,
/// the current authenticated user must have the `billing.accounts.update` IAM permission on the master account,
/// which is typically given to billing account [administrators](https://cloud.google.com/billing/docs/how-to
/// /billing-access). This method will return an error if the master account has not been provisioned as a
/// reseller account.</summary>
/// <param name="body">The body of the request.</param>
public virtual CreateRequest Create(Google.Apis.Cloudbilling.v1.Data.BillingAccount body)
{
return new CreateRequest(service, body);
}
/// <summary>Creates a billing account. This method can only be used to create [billing
/// subaccounts](https://cloud.google.com/billing/docs/concepts) by GCP resellers. When creating a subaccount,
/// the current authenticated user must have the `billing.accounts.update` IAM permission on the master account,
/// which is typically given to billing account [administrators](https://cloud.google.com/billing/docs/how-to
/// /billing-access). This method will return an error if the master account has not been provisioned as a
/// reseller account.</summary>
public class CreateRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.BillingAccount>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.Cloudbilling.v1.Data.BillingAccount body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Cloudbilling.v1.Data.BillingAccount Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "create"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/billingAccounts"; }
}
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Gets information about a billing account. The current authenticated user must be a [viewer of the
/// billing account](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
/// <param name="name">The resource name of the billing account to retrieve. For example,
/// `billingAccounts/012345-567890-ABCDEF`.</param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets information about a billing account. The current authenticated user must be a [viewer of the
/// billing account](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
public class GetRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.BillingAccount>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource name of the billing account to retrieve. For example,
/// `billingAccounts/012345-567890-ABCDEF`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]+$",
});
}
}
/// <summary>Gets the access control policy for a billing account. The caller must have the
/// `billing.accounts.getIamPolicy` permission on the account, which is often given to billing account
/// [viewers](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
/// <param name="resource">REQUIRED: The resource for which the policy is being requested. See the operation
/// documentation for the appropriate value for this field.</param>
public virtual GetIamPolicyRequest GetIamPolicy(string resource)
{
return new GetIamPolicyRequest(service, resource);
}
/// <summary>Gets the access control policy for a billing account. The caller must have the
/// `billing.accounts.getIamPolicy` permission on the account, which is often given to billing account
/// [viewers](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
public class GetIamPolicyRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.Policy>
{
/// <summary>Constructs a new GetIamPolicy request.</summary>
public GetIamPolicyRequest(Google.Apis.Services.IClientService service, string resource)
: base(service)
{
Resource = resource;
InitParameters();
}
/// <summary>REQUIRED: The resource for which the policy is being requested. See the operation documentation
/// for the appropriate value for this field.</summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Optional. The policy format version to be returned.
///
/// Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected.
///
/// Requests for policies with any conditional bindings must specify version 3. Policies without any
/// conditional bindings may specify any valid value or leave the field unset.</summary>
[Google.Apis.Util.RequestParameterAttribute("options.requestedPolicyVersion", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> OptionsRequestedPolicyVersion { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getIamPolicy"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+resource}:getIamPolicy"; }
}
/// <summary>Initializes GetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]+$",
});
RequestParameters.Add(
"options.requestedPolicyVersion", new Google.Apis.Discovery.Parameter
{
Name = "options.requestedPolicyVersion",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists the billing accounts that the current authenticated user has permission to
/// [view](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists the billing accounts that the current authenticated user has permission to
/// [view](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListBillingAccountsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>A token identifying a page of results to return. This should be a `next_page_token` value
/// returned from a previous `ListBillingAccounts` call. If unspecified, the first page of results is
/// returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Requested page size. The maximum page size is 100; this is also the default.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>Options for how to filter the returned billing accounts. Currently this only supports filtering
/// for [subaccounts](https://cloud.google.com/billing/docs/concepts) under a single provided reseller
/// billing account. (e.g. "master_billing_account=billingAccounts/012345-678901-ABCDEF"). Boolean algebra
/// and other fields are not currently supported.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/billingAccounts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Updates a billing account's fields. Currently the only field that can be edited is `display_name`.
/// The current authenticated user must have the `billing.accounts.update` IAM permission, which is typically
/// given to the [administrator](https://cloud.google.com/billing/docs/how-to/billing-access) of the billing
/// account.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the billing account resource to be updated.</param>
public virtual PatchRequest Patch(Google.Apis.Cloudbilling.v1.Data.BillingAccount body, string name)
{
return new PatchRequest(service, body, name);
}
/// <summary>Updates a billing account's fields. Currently the only field that can be edited is `display_name`.
/// The current authenticated user must have the `billing.accounts.update` IAM permission, which is typically
/// given to the [administrator](https://cloud.google.com/billing/docs/how-to/billing-access) of the billing
/// account.</summary>
public class PatchRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.BillingAccount>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Cloudbilling.v1.Data.BillingAccount body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the billing account resource to be updated.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The update mask applied to the resource. Only "display_name" is currently supported.</summary>
[Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)]
public virtual object UpdateMask { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Cloudbilling.v1.Data.BillingAccount Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "patch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PATCH"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]+$",
});
RequestParameters.Add(
"updateMask", new Google.Apis.Discovery.Parameter
{
Name = "updateMask",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Sets the access control policy for a billing account. Replaces any existing policy. The caller must
/// have the `billing.accounts.setIamPolicy` permission on the account, which is often given to billing account
/// [administrators](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">REQUIRED: The resource for which the policy is being specified. See the operation
/// documentation for the appropriate value for this field.</param>
public virtual SetIamPolicyRequest SetIamPolicy(Google.Apis.Cloudbilling.v1.Data.SetIamPolicyRequest body, string resource)
{
return new SetIamPolicyRequest(service, body, resource);
}
/// <summary>Sets the access control policy for a billing account. Replaces any existing policy. The caller must
/// have the `billing.accounts.setIamPolicy` permission on the account, which is often given to billing account
/// [administrators](https://cloud.google.com/billing/docs/how-to/billing-access).</summary>
public class SetIamPolicyRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.Policy>
{
/// <summary>Constructs a new SetIamPolicy request.</summary>
public SetIamPolicyRequest(Google.Apis.Services.IClientService service, Google.Apis.Cloudbilling.v1.Data.SetIamPolicyRequest body, string resource)
: base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>REQUIRED: The resource for which the policy is being specified. See the operation documentation
/// for the appropriate value for this field.</summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Cloudbilling.v1.Data.SetIamPolicyRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "setIamPolicy"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+resource}:setIamPolicy"; }
}
/// <summary>Initializes SetIamPolicy parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]+$",
});
}
}
/// <summary>Tests the access control policy for a billing account. This method takes the resource and a set of
/// permissions as input and returns the subset of the input permissions that the caller is allowed for that
/// resource.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="resource">REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.</param>
public virtual TestIamPermissionsRequest TestIamPermissions(Google.Apis.Cloudbilling.v1.Data.TestIamPermissionsRequest body, string resource)
{
return new TestIamPermissionsRequest(service, body, resource);
}
/// <summary>Tests the access control policy for a billing account. This method takes the resource and a set of
/// permissions as input and returns the subset of the input permissions that the caller is allowed for that
/// resource.</summary>
public class TestIamPermissionsRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.TestIamPermissionsResponse>
{
/// <summary>Constructs a new TestIamPermissions request.</summary>
public TestIamPermissionsRequest(Google.Apis.Services.IClientService service, Google.Apis.Cloudbilling.v1.Data.TestIamPermissionsRequest body, string resource)
: base(service)
{
Resource = resource;
Body = body;
InitParameters();
}
/// <summary>REQUIRED: The resource for which the policy detail is being requested. See the operation
/// documentation for the appropriate value for this field.</summary>
[Google.Apis.Util.RequestParameterAttribute("resource", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Resource { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Cloudbilling.v1.Data.TestIamPermissionsRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "testIamPermissions"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+resource}:testIamPermissions"; }
}
/// <summary>Initializes TestIamPermissions parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"resource", new Google.Apis.Discovery.Parameter
{
Name = "resource",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^billingAccounts/[^/]+$",
});
}
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Gets the billing information for a project. The current authenticated user must have [permission to
/// view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ).</summary>
/// <param name="name">The resource name of the project for which billing information is retrieved. For example,
/// `projects/tokyo-rain-123`.</param>
public virtual GetBillingInfoRequest GetBillingInfo(string name)
{
return new GetBillingInfoRequest(service, name);
}
/// <summary>Gets the billing information for a project. The current authenticated user must have [permission to
/// view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ).</summary>
public class GetBillingInfoRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo>
{
/// <summary>Constructs a new GetBillingInfo request.</summary>
public GetBillingInfoRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The resource name of the project for which billing information is retrieved. For example,
/// `projects/tokyo-rain-123`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "getBillingInfo"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}/billingInfo"; }
}
/// <summary>Initializes GetBillingInfo parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
/// <summary>Sets or updates the billing account associated with a project. You specify the new billing account
/// by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing
/// account. Associating a project with an open billing account enables billing on the project and allows
/// charges for resource usage. If the project already had a billing account, this method changes the billing
/// account used for resource usage charges.
///
/// *Note:* Incurred charges that have not yet been reported in the transaction history of the GCP Console might
/// be billed to the new billing account, even if the charge occurred before the new billing account was
/// assigned to the project.
///
/// The current authenticated user must have ownership privileges for both the
/// [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ) and the [billing
/// account](https://cloud.google.com/billing/docs/how-to/billing-access).
///
/// You can disable billing on the project by setting the `billing_account_name` field to empty. This action
/// disassociates the current billing account from the project. Any billable activity of your in-use services
/// will stop, and your application could stop functioning as expected. Any unbilled charges to date will be
/// billed to the previously associated account. The current authenticated user must be either an owner of the
/// project or an owner of the billing account for the project.
///
/// Note that associating a project with a *closed* billing account will have much the same effect as disabling
/// billing on the project: any paid resources used by the project will be shut down. Thus, unless you wish to
/// disable billing, you should always call this method with the name of an *open* billing account.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The resource name of the project associated with the billing information that you want to update.
/// For example, `projects/tokyo-rain-123`.</param>
public virtual UpdateBillingInfoRequest UpdateBillingInfo(Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo body, string name)
{
return new UpdateBillingInfoRequest(service, body, name);
}
/// <summary>Sets or updates the billing account associated with a project. You specify the new billing account
/// by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing
/// account. Associating a project with an open billing account enables billing on the project and allows
/// charges for resource usage. If the project already had a billing account, this method changes the billing
/// account used for resource usage charges.
///
/// *Note:* Incurred charges that have not yet been reported in the transaction history of the GCP Console might
/// be billed to the new billing account, even if the charge occurred before the new billing account was
/// assigned to the project.
///
/// The current authenticated user must have ownership privileges for both the
/// [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ) and the [billing
/// account](https://cloud.google.com/billing/docs/how-to/billing-access).
///
/// You can disable billing on the project by setting the `billing_account_name` field to empty. This action
/// disassociates the current billing account from the project. Any billable activity of your in-use services
/// will stop, and your application could stop functioning as expected. Any unbilled charges to date will be
/// billed to the previously associated account. The current authenticated user must be either an owner of the
/// project or an owner of the billing account for the project.
///
/// Note that associating a project with a *closed* billing account will have much the same effect as disabling
/// billing on the project: any paid resources used by the project will be shut down. Thus, unless you wish to
/// disable billing, you should always call this method with the name of an *open* billing account.</summary>
public class UpdateBillingInfoRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo>
{
/// <summary>Constructs a new UpdateBillingInfo request.</summary>
public UpdateBillingInfoRequest(Google.Apis.Services.IClientService service, Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The resource name of the project associated with the billing information that you want to
/// update. For example, `projects/tokyo-rain-123`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "updateBillingInfo"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "PUT"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}/billingInfo"; }
}
/// <summary>Initializes UpdateBillingInfo parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
}
/// <summary>The "services" collection of methods.</summary>
public class ServicesResource
{
private const string Resource = "services";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ServicesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
skus = new SkusResource(service);
}
private readonly SkusResource skus;
/// <summary>Gets the Skus resource.</summary>
public virtual SkusResource Skus
{
get { return skus; }
}
/// <summary>The "skus" collection of methods.</summary>
public class SkusResource
{
private const string Resource = "skus";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SkusResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Lists all publicly available SKUs for a given cloud service.</summary>
/// <param name="parent">The name of the service. Example: "services/DA34-426B-A397"</param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>Lists all publicly available SKUs for a given cloud service.</summary>
public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListSkusResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent)
: base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>The name of the service. Example: "services/DA34-426B-A397"</summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>A token identifying a page of results to return. This should be a `next_page_token` value
/// returned from a previous `ListSkus` call. If unspecified, the first page of results is
/// returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Optional inclusive start time of the time range for which the pricing versions will be
/// returned. Timestamps in the future are not allowed. The time range has to be within a single
/// calendar month in America/Los_Angeles timezone. Time range as a whole is optional. If not specified,
/// the latest pricing will be returned (up to 12 hours old at most).</summary>
[Google.Apis.Util.RequestParameterAttribute("startTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object StartTime { get; set; }
/// <summary>Requested page size. Defaults to 5000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The ISO 4217 currency code for the pricing info in the response proto. Will use the
/// conversion rate as of start_time. Optional. If not specified USD will be used.</summary>
[Google.Apis.Util.RequestParameterAttribute("currencyCode", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CurrencyCode { get; set; }
/// <summary>Optional exclusive end time of the time range for which the pricing versions will be
/// returned. Timestamps in the future are not allowed. The time range has to be within a single
/// calendar month in America/Los_Angeles timezone. Time range as a whole is optional. If not specified,
/// the latest pricing will be returned (up to 12 hours old at most).</summary>
[Google.Apis.Util.RequestParameterAttribute("endTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual object EndTime { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+parent}/skus"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^services/[^/]+$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"startTime", new Google.Apis.Discovery.Parameter
{
Name = "startTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"currencyCode", new Google.Apis.Discovery.Parameter
{
Name = "currencyCode",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"endTime", new Google.Apis.Discovery.Parameter
{
Name = "endTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>Lists all public cloud services.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists all public cloud services.</summary>
public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListServicesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>A token identifying a page of results to return. This should be a `next_page_token` value
/// returned from a previous `ListServices` call. If unspecified, the first page of results is
/// returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Requested page size. Defaults to 5000.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/services"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Cloudbilling.v1.Data
{
/// <summary>Represents the aggregation level and interval for pricing of a single SKU.</summary>
public class AggregationInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of intervals to aggregate over. Example: If aggregation_level is "DAILY" and
/// aggregation_count is 14, aggregation will be over 14 days.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("aggregationCount")]
public virtual System.Nullable<int> AggregationCount { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("aggregationInterval")]
public virtual string AggregationInterval { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("aggregationLevel")]
public virtual string AggregationLevel { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Specifies the audit configuration for a service. The configuration determines which permission types
/// are logged, and what identities, if any, are exempted from logging. An AuditConfig must have one or more
/// AuditLogConfigs.
///
/// If there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is
/// used for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each
/// AuditLogConfig are exempted.
///
/// Example Policy with multiple AuditConfigs:
///
/// { "audit_configs": [ { "service": "allServices" "audit_log_configs": [ { "log_type": "DATA_READ",
/// "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE", }, { "log_type": "ADMIN_READ", }
/// ] }, { "service": "sampleservice.googleapis.com" "audit_log_configs": [ { "log_type": "DATA_READ", }, {
/// "log_type": "DATA_WRITE", "exempted_members": [ "user:aliya@example.com" ] } ] } ] }
///
/// For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ logging. It also exempts
/// jose@example.com from DATA_READ logging, and aliya@example.com from DATA_WRITE logging.</summary>
public class AuditConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The configuration for logging of each type of permission.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditLogConfigs")]
public virtual System.Collections.Generic.IList<AuditLogConfig> AuditLogConfigs { get; set; }
/// <summary>Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`,
/// `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("service")]
public virtual string Service { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Provides the configuration for logging a type of permissions. Example:
///
/// { "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, {
/// "log_type": "DATA_WRITE", } ] }
///
/// This enables 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose@example.com from DATA_READ
/// logging.</summary>
public class AuditLogConfig : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Specifies the identities that do not cause logging for this type of permission. Follows the same
/// format of Binding.members.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")]
public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; }
/// <summary>The log type that this config enables.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("logType")]
public virtual string LogType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A billing account in [GCP Console](https://console.cloud.google.com/). You can assign a billing account
/// to one or more projects.</summary>
public class BillingAccount : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The display name given to the billing account, such as `My Billing Account`. This name is displayed
/// in the GCP Console.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>If this account is a [subaccount](https://cloud.google.com/billing/docs/concepts), then this will
/// be the resource name of the master billing account that it is being resold through. Otherwise this will be
/// empty.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("masterBillingAccount")]
public virtual string MasterBillingAccount { get; set; }
/// <summary>The resource name of the billing account. The resource name has the form
/// `billingAccounts/{billing_account_id}`. For example, `billingAccounts/012345-567890-ABCDEF` would be the
/// resource name for billing account `012345-567890-ABCDEF`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>True if the billing account is open, and will therefore be charged for any usage on associated
/// projects. False if the billing account is closed, and therefore projects associated with it will be unable
/// to use paid services.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("open")]
public virtual System.Nullable<bool> Open { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Associates `members` with a `role`.</summary>
public class Binding : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The condition that is associated with this binding. NOTE: An unsatisfied condition will not allow
/// user access via current binding. Different bindings, including their conditions, are examined
/// independently.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("condition")]
public virtual Expr Condition { get; set; }
/// <summary>Specifies the identities requesting access for a Cloud Platform resource. `members` can have the
/// following values:
///
/// * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google
/// account.
///
/// * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google
/// account or a service account.
///
/// * `user:{emailid}`: An email address that represents a specific Google account. For example,
/// `alice@example.com` .
///
/// * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-
/// app@appspot.gserviceaccount.com`.
///
/// * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`.
///
/// * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user
/// that has been recently deleted. For example,`alice@example.com?uid=123456789012345678901`. If the user is
/// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding.
///
/// * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing
/// a service account that has been recently deleted. For example, `my-other-
/// app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, this value
/// reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the binding.
///
/// * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a Google
/// group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. If the
/// group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role in the
/// binding.
///
/// * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that domain. For example,
/// `google.com` or `example.com`.
///
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("members")]
public virtual System.Collections.Generic.IList<string> Members { get; set; }
/// <summary>Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or
/// `roles/owner`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("role")]
public virtual string Role { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the category hierarchy of a SKU.</summary>
public class Category : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The type of product the SKU refers to. Example: "Compute", "Storage", "Network",
/// "ApplicationServices" etc.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceFamily")]
public virtual string ResourceFamily { get; set; }
/// <summary>A group classification for related SKUs. Example: "RAM", "GPU", "Prediction", "Ops", "GoogleEgress"
/// etc.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceGroup")]
public virtual string ResourceGroup { get; set; }
/// <summary>The display name of the service this SKU belongs to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("serviceDisplayName")]
public virtual string ServiceDisplayName { get; set; }
/// <summary>Represents how the SKU is consumed. Example: "OnDemand", "Preemptible", "Commit1Mo", "Commit1Yr"
/// etc.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("usageType")]
public virtual string UsageType { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an expression text. Example:
///
/// title: "User account presence" description: "Determines whether the request has a user account" expression:
/// "size(request.user) > 0"</summary>
public class Expr : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>An optional description of the expression. This is a longer text which describes the expression,
/// e.g. when hovered over it in a UI.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>Textual representation of an expression in Common Expression Language syntax.
///
/// The application context of the containing message determines which well-known feature set of CEL is
/// supported.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expression")]
public virtual string Expression { get; set; }
/// <summary>An optional string indicating the location of the expression for error reporting, e.g. a file name
/// and a position in the file.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("location")]
public virtual string Location { get; set; }
/// <summary>An optional title for the expression, i.e. a short string describing its purpose. This can be used
/// e.g. in UIs which allow to enter the expression.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("title")]
public virtual string Title { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `ListBillingAccounts`.</summary>
public class ListBillingAccountsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A list of billing accounts.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("billingAccounts")]
public virtual System.Collections.Generic.IList<BillingAccount> BillingAccounts { get; set; }
/// <summary>A token to retrieve the next page of results. To retrieve the next page, call `ListBillingAccounts`
/// again with the `page_token` field set to this value. This field is empty if there are no more results to
/// retrieve.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `ListProjectBillingInfoResponse`.</summary>
public class ListProjectBillingInfoResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A token to retrieve the next page of results. To retrieve the next page, call
/// `ListProjectBillingInfo` again with the `page_token` field set to this value. This field is empty if there
/// are no more results to retrieve.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of `ProjectBillingInfo` resources representing the projects associated with the billing
/// account.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("projectBillingInfo")]
public virtual System.Collections.Generic.IList<ProjectBillingInfo> ProjectBillingInfo { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `ListServices`.</summary>
public class ListServicesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A token to retrieve the next page of results. To retrieve the next page, call `ListServices` again
/// with the `page_token` field set to this value. This field is empty if there are no more results to
/// retrieve.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of services.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("services")]
public virtual System.Collections.Generic.IList<Service> Services { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `ListSkus`.</summary>
public class ListSkusResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A token to retrieve the next page of results. To retrieve the next page, call `ListSkus` again with
/// the `page_token` field set to this value. This field is empty if there are no more results to
/// retrieve.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The list of public SKUs of the given service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("skus")]
public virtual System.Collections.Generic.IList<Sku> Skus { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents an amount of money with its currency type.</summary>
public class Money : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The 3-letter currency code defined in ISO 4217.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("currencyCode")]
public virtual string CurrencyCode { get; set; }
/// <summary>Number of nano (10^-9) units of the amount. The value must be between -999,999,999 and +999,999,999
/// inclusive. If `units` is positive, `nanos` must be positive or zero. If `units` is zero, `nanos` can be
/// positive, zero, or negative. If `units` is negative, `nanos` must be negative or zero. For example $-1.75 is
/// represented as `units`=-1 and `nanos`=-750,000,000.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nanos")]
public virtual System.Nullable<int> Nanos { get; set; }
/// <summary>The whole units of the amount. For example if `currencyCode` is `"USD"`, then 1 unit is one US
/// dollar.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("units")]
public virtual System.Nullable<long> Units { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies
/// for Cloud Platform resources.
///
/// A `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members
/// can be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list
/// of permissions (defined by IAM or configured by users). A `binding` can optionally specify a `condition`, which
/// is a logic expression that further constrains the role binding based on attributes about the request and/or
/// target resource.
///
/// **JSON Example**
///
/// { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com",
/// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] },
/// { "role": "roles/resourcemanager.organizationViewer", "members": ["user:eve@example.com"], "condition": {
/// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time
/// < timestamp('2020-10-01T00:00:00.000Z')", } } ] }
///
/// **YAML Example**
///
/// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-
/// project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: -
/// user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access
/// description: Does not grant access after Sep 2020 expression: request.time <
/// timestamp('2020-10-01T00:00:00.000Z')
///
/// For a description of IAM and its features, see the [IAM developer's
/// guide](https://cloud.google.com/iam/docs).</summary>
public class Policy : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Specifies cloud audit logging configuration for this policy.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("auditConfigs")]
public virtual System.Collections.Generic.IList<AuditConfig> AuditConfigs { get; set; }
/// <summary>Associates a list of `members` to a `role`. Optionally may specify a `condition` that determines
/// when binding is in effect. `bindings` with no members will result in an error.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("bindings")]
public virtual System.Collections.Generic.IList<Binding> Bindings { get; set; }
/// <summary>`etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of
/// a policy from overwriting each other. It is strongly suggested that systems make use of the `etag` in the
/// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned
/// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to
/// `setIamPolicy` to ensure that their change will be applied to the same version of the policy.
///
/// If no `etag` is provided in the call to `setIamPolicy`, then the existing policy is overwritten. Due to
/// blind-set semantics of an etag-less policy, 'setIamPolicy' will not fail even if either of incoming or
/// stored policy does not meet the version requirements.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>Specifies the format of the policy.
///
/// Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected.
///
/// Operations affecting conditional bindings must specify version 3. This can be either setting a conditional
/// policy, modifying a conditional binding, or removing a conditional binding from the stored conditional
/// policy. Operations on non-conditional policies may specify any valid value or leave the field unset.
///
/// If no etag is provided in the call to `setIamPolicy`, any version compliance checks on the incoming and/or
/// stored policy is skipped.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual System.Nullable<int> Version { get; set; }
}
/// <summary>Expresses a mathematical pricing formula. For Example:-
///
/// `usage_unit: GBy` `tiered_rates:` `[start_usage_amount: 20, unit_price: $10]` `[start_usage_amount: 100,
/// unit_price: $5]`
///
/// The above expresses a pricing formula where the first 20GB is free, the next 80GB is priced at $10 per GB
/// followed by $5 per GB for additional usage.</summary>
public class PricingExpression : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The base unit for the SKU which is the unit used in usage exports. Example: "By"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("baseUnit")]
public virtual string BaseUnit { get; set; }
/// <summary>Conversion factor for converting from price per usage_unit to price per base_unit, and
/// start_usage_amount to start_usage_amount in base_unit. unit_price / base_unit_conversion_factor = price per
/// base_unit. start_usage_amount * base_unit_conversion_factor = start_usage_amount in base_unit.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("baseUnitConversionFactor")]
public virtual System.Nullable<double> BaseUnitConversionFactor { get; set; }
/// <summary>The base unit in human readable form. Example: "byte".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("baseUnitDescription")]
public virtual string BaseUnitDescription { get; set; }
/// <summary>The recommended quantity of units for displaying pricing info. When displaying pricing info it is
/// recommended to display: (unit_price * display_quantity) per display_quantity usage_unit. This field does not
/// affect the pricing formula and is for display purposes only. Example: If the unit_price is "0.0001 USD", the
/// usage_unit is "GB" and the display_quantity is "1000" then the recommended way of displaying the pricing
/// info is "0.10 USD per 1000 GB"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayQuantity")]
public virtual System.Nullable<double> DisplayQuantity { get; set; }
/// <summary>The list of tiered rates for this pricing. The total cost is computed by applying each of the
/// tiered rates on usage. This repeated list is sorted by ascending order of start_usage_amount.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("tieredRates")]
public virtual System.Collections.Generic.IList<TierRate> TieredRates { get; set; }
/// <summary>The short hand for unit of usage this pricing is specified in. Example: usage_unit of "GiBy" means
/// that usage is specified in "Gibi Byte".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("usageUnit")]
public virtual string UsageUnit { get; set; }
/// <summary>The unit of usage in human readable form. Example: "gibi byte".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("usageUnitDescription")]
public virtual string UsageUnitDescription { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents the pricing information for a SKU at a single point of time.</summary>
public class PricingInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Aggregation Info. This can be left unspecified if the pricing expression doesn't require
/// aggregation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("aggregationInfo")]
public virtual AggregationInfo AggregationInfo { get; set; }
/// <summary>Conversion rate used for currency conversion, from USD to the currency specified in the request.
/// This includes any surcharge collected for billing in non USD currency. If a currency is not specified in the
/// request this defaults to 1.0. Example: USD * currency_conversion_rate = JPY</summary>
[Newtonsoft.Json.JsonPropertyAttribute("currencyConversionRate")]
public virtual System.Nullable<double> CurrencyConversionRate { get; set; }
/// <summary>The timestamp from which this pricing was effective within the requested time range. This is
/// guaranteed to be greater than or equal to the start_time field in the request and less than the end_time
/// field in the request. If a time range was not specified in the request this field will be equivalent to a
/// time within the last 12 hours, indicating the latest pricing info.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("effectiveTime")]
public virtual object EffectiveTime { get; set; }
/// <summary>Expresses the pricing formula. See `PricingExpression` for an example.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pricingExpression")]
public virtual PricingExpression PricingExpression { get; set; }
/// <summary>An optional human readable summary of the pricing information, has a maximum length of 256
/// characters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("summary")]
public virtual string Summary { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Encapsulation of billing information for a GCP Console project. A project has at most one associated
/// billing account at a time (but a billing account can be assigned to multiple projects).</summary>
public class ProjectBillingInfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The resource name of the billing account associated with the project, if any. For example,
/// `billingAccounts/012345-567890-ABCDEF`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("billingAccountName")]
public virtual string BillingAccountName { get; set; }
/// <summary>True if the project is associated with an open billing account, to which usage on the project is
/// charged. False if the project is associated with a closed billing account, or no billing account at all, and
/// therefore cannot use paid services. This field is read-only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("billingEnabled")]
public virtual System.Nullable<bool> BillingEnabled { get; set; }
/// <summary>The resource name for the `ProjectBillingInfo`; has the form `projects/{project_id}/billingInfo`.
/// For example, the resource name for the billing information for project `tokyo-rain-123` would be `projects
/// /tokyo-rain-123/billingInfo`. This field is read-only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The ID of the project that this `ProjectBillingInfo` represents, such as `tokyo-rain-123`. This is
/// a convenience field so that you don't need to parse the `name` field to obtain a project ID. This field is
/// read-only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("projectId")]
public virtual string ProjectId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Encapsulates a single service in Google Cloud Platform.</summary>
public class Service : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The business under which the service is offered. Ex. "businessEntities/GCP",
/// "businessEntities/Maps"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("businessEntityName")]
public virtual string BusinessEntityName { get; set; }
/// <summary>A human readable display name for this service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual string DisplayName { get; set; }
/// <summary>The resource name for the service. Example: "services/DA34-426B-A397"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The identifier for the service. Example: "DA34-426B-A397"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("serviceId")]
public virtual string ServiceId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `SetIamPolicy` method.</summary>
public class SetIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to
/// a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects)
/// might reject them.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("policy")]
public virtual Policy Policy { get; set; }
/// <summary>OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only the fields in the mask
/// will be modified. If no mask is provided, the following default mask is used: paths: "bindings, etag" This
/// field is only used by Cloud IAM.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("updateMask")]
public virtual object UpdateMask { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Encapsulates a single SKU in Google Cloud Platform</summary>
public class Sku : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The category hierarchy of this SKU, purely for organizational purpose.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("category")]
public virtual Category Category { get; set; }
/// <summary>A human readable description of the SKU, has a maximum length of 256 characters.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual string Description { get; set; }
/// <summary>The resource name for the SKU. Example: "services/DA34-426B-A397/skus/AA95-CD31-42FE"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>A timeline of pricing info for this SKU in chronological order.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("pricingInfo")]
public virtual System.Collections.Generic.IList<PricingInfo> PricingInfo { get; set; }
/// <summary>Identifies the service provider. This is 'Google' for first party services in Google Cloud
/// Platform.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("serviceProviderName")]
public virtual string ServiceProviderName { get; set; }
/// <summary>List of service regions this SKU is offered at. Example: "asia-east1" Service regions can be found
/// at https://cloud.google.com/about/locations/</summary>
[Newtonsoft.Json.JsonPropertyAttribute("serviceRegions")]
public virtual System.Collections.Generic.IList<string> ServiceRegions { get; set; }
/// <summary>The identifier for the SKU. Example: "AA95-CD31-42FE"</summary>
[Newtonsoft.Json.JsonPropertyAttribute("skuId")]
public virtual string SkuId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Request message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or
/// 'storage.*') are not allowed. For more information see [IAM
/// Overview](https://cloud.google.com/iam/docs/overview#permissions).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response message for `TestIamPermissions` method.</summary>
public class TestIamPermissionsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A subset of `TestPermissionsRequest.permissions` that the caller is allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("permissions")]
public virtual System.Collections.Generic.IList<string> Permissions { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The price rate indicating starting usage and its corresponding price.</summary>
public class TierRate : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Usage is priced at this rate only after this amount. Example: start_usage_amount of 10 indicates
/// that the usage will be priced at the unit_price after the first 10 usage_units.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startUsageAmount")]
public virtual System.Nullable<double> StartUsageAmount { get; set; }
/// <summary>The price per unit of usage. Example: unit_price of amount $10 indicates that each unit will cost
/// $10.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("unitPrice")]
public virtual Money UnitPrice { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 48.484586 | 171 | 0.604705 | [
"Apache-2.0"
] | HamidMosalla/google-api-dotnet-client | Src/Generated/Google.Apis.Cloudbilling.v1/Google.Apis.Cloudbilling.v1.cs | 100,654 | C# |
namespace DriveManip
{
public class MetaCharacterdisplay
{
public Google.Apis.Drive.v3.Data.File MetaFile { get; set; }
public string CharacterName { get; set; }
}
} | 24.25 | 68 | 0.649485 | [
"Unlicense"
] | Angelsinhbfs/googleDocsDownload | DriveManip/DriveManip/MetaCharacterdisplay.cs | 196 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator})
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Commvault.Powershell.Models
{
using Commvault.Powershell.Runtime.PowerShell;
/// <summary>
/// Applicable only for credentials with Cloud Account and Vendor Type as Microsoft Azure
/// </summary>
[System.ComponentModel.TypeConverter(typeof(AzureCredentialContentWithTenantIdTypeConverter))]
public partial class AzureCredentialContentWithTenantId
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Commvault.Powershell.Models.AzureCredentialContentWithTenantId"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal AzureCredentialContentWithTenantId(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Endpoints = (Commvault.Powershell.Models.IAzureEndpoints) content.GetValueForProperty("Endpoints",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Endpoints, Commvault.Powershell.Models.AzureEndpointsTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Security = (Commvault.Powershell.Models.ICredentialSecurity) content.GetValueForProperty("Security",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Security, Commvault.Powershell.Models.CredentialSecurityTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewName = (string) content.GetValueForProperty("NewName",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewName, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).TenantId, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).ApplicationId, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewApplicationSecret = (string) content.GetValueForProperty("NewApplicationSecret",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewApplicationSecret, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Environment = (string) content.GetValueForProperty("Environment",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Environment, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Description = (string) content.GetValueForProperty("Description",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Description, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointActiveDirectory = (string) content.GetValueForProperty("EndpointActiveDirectory",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointActiveDirectory, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointStorage = (string) content.GetValueForProperty("EndpointStorage",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointStorage, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointResourceManager = (string) content.GetValueForProperty("EndpointResourceManager",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointResourceManager, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityOwner = (Commvault.Powershell.Models.ICredentialOwner) content.GetValueForProperty("SecurityOwner",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityOwner, Commvault.Powershell.Models.CredentialOwnerTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityAssociations = (Commvault.Powershell.Models.ICredentialSecurityAssociations[]) content.GetValueForProperty("SecurityAssociations",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityAssociations, __y => TypeConverterExtensions.SelectToArray<Commvault.Powershell.Models.ICredentialSecurityAssociations>(__y, Commvault.Powershell.Models.CredentialSecurityAssociationsTypeConverter.ConvertFrom));
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUser = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("OwnerUser",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUser, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUserGroup = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("OwnerUserGroup",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUserGroup, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserId = (int?) content.GetValueForProperty("UserId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserName = (string) content.GetValueForProperty("UserName",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserName, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupId = (int?) content.GetValueForProperty("UserGroupId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupName = (string) content.GetValueForProperty("UserGroupName",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupName, global::System.Convert.ToString);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Commvault.Powershell.Models.AzureCredentialContentWithTenantId"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal AzureCredentialContentWithTenantId(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Endpoints = (Commvault.Powershell.Models.IAzureEndpoints) content.GetValueForProperty("Endpoints",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Endpoints, Commvault.Powershell.Models.AzureEndpointsTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Security = (Commvault.Powershell.Models.ICredentialSecurity) content.GetValueForProperty("Security",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Security, Commvault.Powershell.Models.CredentialSecurityTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewName = (string) content.GetValueForProperty("NewName",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewName, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).TenantId, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).ApplicationId, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewApplicationSecret = (string) content.GetValueForProperty("NewApplicationSecret",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).NewApplicationSecret, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Environment = (string) content.GetValueForProperty("Environment",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Environment, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Description = (string) content.GetValueForProperty("Description",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).Description, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointActiveDirectory = (string) content.GetValueForProperty("EndpointActiveDirectory",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointActiveDirectory, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointStorage = (string) content.GetValueForProperty("EndpointStorage",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointStorage, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointResourceManager = (string) content.GetValueForProperty("EndpointResourceManager",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).EndpointResourceManager, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityOwner = (Commvault.Powershell.Models.ICredentialOwner) content.GetValueForProperty("SecurityOwner",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityOwner, Commvault.Powershell.Models.CredentialOwnerTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityAssociations = (Commvault.Powershell.Models.ICredentialSecurityAssociations[]) content.GetValueForProperty("SecurityAssociations",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).SecurityAssociations, __y => TypeConverterExtensions.SelectToArray<Commvault.Powershell.Models.ICredentialSecurityAssociations>(__y, Commvault.Powershell.Models.CredentialSecurityAssociationsTypeConverter.ConvertFrom));
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUser = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("OwnerUser",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUser, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUserGroup = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("OwnerUserGroup",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).OwnerUserGroup, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserId = (int?) content.GetValueForProperty("UserId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserName = (string) content.GetValueForProperty("UserName",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserName, global::System.Convert.ToString);
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupId = (int?) content.GetValueForProperty("UserGroupId",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupName = (string) content.GetValueForProperty("UserGroupName",((Commvault.Powershell.Models.IAzureCredentialContentWithTenantIdInternal)this).UserGroupName, global::System.Convert.ToString);
AfterDeserializePSObject(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Commvault.Powershell.Models.AzureCredentialContentWithTenantId"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Commvault.Powershell.Models.IAzureCredentialContentWithTenantId" />.
/// </returns>
public static Commvault.Powershell.Models.IAzureCredentialContentWithTenantId DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new AzureCredentialContentWithTenantId(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Commvault.Powershell.Models.AzureCredentialContentWithTenantId"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Commvault.Powershell.Models.IAzureCredentialContentWithTenantId" />.
/// </returns>
public static Commvault.Powershell.Models.IAzureCredentialContentWithTenantId DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new AzureCredentialContentWithTenantId(content);
}
/// <summary>
/// Creates a new instance of <see cref="AzureCredentialContentWithTenantId" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Commvault.Powershell.Models.IAzureCredentialContentWithTenantId FromJsonString(string jsonText) => FromJson(Commvault.Powershell.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Commvault.Powershell.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Applicable only for credentials with Cloud Account and Vendor Type as Microsoft Azure
[System.ComponentModel.TypeConverter(typeof(AzureCredentialContentWithTenantIdTypeConverter))]
public partial interface IAzureCredentialContentWithTenantId
{
}
} | 114.523256 | 529 | 0.782668 | [
"MIT"
] | Commvault/CVPowershellSDKV2 | generated/api/Models/AzureCredentialContentWithTenantId.PowerShell.cs | 19,698 | C# |
using System;
namespace Mondop.Templates.Model
{
public class InputElement : TemplateElement
{
public InputElement(TemplateElement parent) : base(parent)
{
}
public string Type { get; set; }
public string Alias { get; set; }
public Type ToType()
{
return System.Type.GetType(Type);
}
}
}
| 18.142857 | 66 | 0.564304 | [
"Apache-2.0"
] | MondopDotCom/Mondop.Templates | src/Mondop.Templates/Mondop.Templates/Model/InputElement.cs | 383 | C# |
// Copyright Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using UnityEngine;
public class GazeSelection : MonoBehaviour
{
[HeaderAttribute("Gaze Search")]
[Tooltip("Distance along the gaze vector to search for valid targets to select.")]
public float GazeDistance = 30.0f;
[HeaderAttribute("Spherical Cone Search")]
public bool UseSphericalConeSearch = true;
[Tooltip("If no objects are found along the gaze vector, the average position of objects found within this angle of the gaze vector are selected.")]
public float GazeSpreadDegrees = 30.0f;
// ordered from closest to gaze to farthest
private SortedList<float, RaycastHit> selectedTargets;
public IList<RaycastHit> SelectedTargets
{
get { return selectedTargets != null ? selectedTargets.Values : null; }
}
private float targetSpreadMinValue;
private PlacementControl placementControl;
private void Start()
{
if (Camera.main == null)
{
Debug.LogError(" GazeSelection:No main camera exists in the scene, unable to use GazeSelection.", this);
GameObject.Destroy(this);
return;
}
if (Cursor.Instance == null)
{
Debug.LogError("GazeSelection: no target layer masks can be used because the Cursor was not found.", this);
GameObject.Destroy(this);
return;
}
if (TransitionManager.Instance == null)
{
Debug.LogWarning("GazeSelection: No TransitionManager found, so input is not disabled during transitions.");
}
else if (TransitionManager.Instance.ViewVolume != null)
{
placementControl = TransitionManager.Instance.ViewVolume.GetComponentInChildren<PlacementControl>();
}
selectedTargets = new SortedList<float, RaycastHit>();
targetSpreadMinValue = Mathf.Cos(Mathf.Deg2Rad * GazeSpreadDegrees);
}
public void Update()
{
selectedTargets.Clear();
if ((TransitionManager.Instance == null || (!TransitionManager.Instance.InTransition && !TransitionManager.Instance.IsIntro)) && // in the middle of a scene transition or if it is the intro, prevent gaze selection
(placementControl == null || !placementControl.IsHolding)) // the cube is being placed, prevent gaze selection
{
Vector3 gazeStart = Camera.main.transform.position + (Camera.main.nearClipPlane * Camera.main.transform.forward);
foreach (Cursor.PriorityLayerMask priorityMask in Cursor.Instance.prioritizedCursorMask)
{
switch (priorityMask.collisionType)
{
case Cursor.CursorCollisionSearch.RaycastSearch:
RaycastHit info;
if (Physics.Raycast(gazeStart, Camera.main.transform.forward, out info, GazeDistance, priorityMask.layers))
{
selectedTargets.Add(0.0f, info);
}
break;
case Cursor.CursorCollisionSearch.SphereCastSearch:
if (UseSphericalConeSearch)
{
// calculate radius of sphere to cast based on GazeSpreadDegrees at GazeDistance
float sphereRadius = GazeDistance * Mathf.Tan(Mathf.Deg2Rad * (GazeSpreadDegrees / 2.0f));
// get all target objects in a sphere from the camera
RaycastHit[] hitTargets = Physics.SphereCastAll(gazeStart, sphereRadius, Camera.main.transform.forward, 0.0f, priorityMask.layers);
// only consider target objects that are within the target spread angle specified on start
foreach (RaycastHit target in hitTargets)
{
Vector3 toTarget = Vector3.Normalize(target.transform.position - Camera.main.transform.position);
float dotProduct = Vector3.Dot(Camera.main.transform.forward, toTarget);
// The dotProduct of our two vectors is equivalent to the cosine
// of the angle between them. If it is larger than the targetSpreadValue
// established in Start(), that means the hit occurred within the
// cone and the hitTarget should be added to our list of selectedTargets.
if (dotProduct >= targetSpreadMinValue)
{
selectedTargets[-dotProduct] = target;
}
}
}
break;
}
if (selectedTargets.Count > 0)
{
break;
}
}
}
}
}
| 46.185841 | 225 | 0.571757 | [
"MIT"
] | Heron11/Heron | Assets/Scripts/Input/GazeSelection.cs | 5,221 | C# |
using Matrix.Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Matrix.Application.TodoLists.Commands.UpdateTodoList
{
public class UpdateTodoListCommandValidator : AbstractValidator<UpdateTodoListCommand>
{
private readonly IApplicationDbContext _context;
public UpdateTodoListCommandValidator(IApplicationDbContext context)
{
_context = context;
RuleFor(v => v.Title)
.NotEmpty().WithMessage("Title is required.")
.MaximumLength(200).WithMessage("Title must not exceed 200 characters.")
.MustAsync(BeUniqueTitle).WithMessage("The specified title already exists.");
}
public async Task<bool> BeUniqueTitle(UpdateTodoListCommand model, string title, CancellationToken cancellationToken)
{
return await _context.TodoLists
.Where(l => l.Id != model.Id)
.AllAsync(l => l.Title != title);
}
}
}
| 34.5 | 125 | 0.67663 | [
"MIT"
] | zuyuz/Matrix | src/Application/TodoLists/Commands/UpdateTodoList/UpdateTodoListCommandValidator.cs | 1,106 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml;
namespace System.ServiceModel.Syndication
{
[DataContract]
public abstract class ServiceDocumentFormatter
{
private ServiceDocument _document;
protected ServiceDocumentFormatter()
{
}
protected ServiceDocumentFormatter(ServiceDocument documentToWrite)
{
_document = documentToWrite ?? throw new ArgumentNullException(nameof(documentToWrite));
}
public ServiceDocument Document => _document;
public abstract string Version { get; }
public abstract bool CanRead(XmlReader reader);
public abstract void ReadFrom(XmlReader reader);
public abstract void WriteTo(XmlWriter writer);
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, CategoriesDocument categories)
{
Debug.Assert(categories != null);
SyndicationFeedFormatter.CloseBuffer(buffer, writer);
categories.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ResourceCollectionInfo collection)
{
Debug.Assert(collection != null);
SyndicationFeedFormatter.CloseBuffer(buffer, writer);
collection.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, Workspace workspace)
{
Debug.Assert(workspace != null);
SyndicationFeedFormatter.CloseBuffer(buffer, writer);
workspace.LoadElementExtensions(buffer);
}
internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
SyndicationFeedFormatter.CloseBuffer(buffer, writer);
document.LoadElementExtensions(buffer);
}
protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories)
{
if (inlineCategories == null)
{
throw new ArgumentNullException(nameof(inlineCategories));
}
return inlineCategories.CreateCategory();
}
protected static ResourceCollectionInfo CreateCollection(Workspace workspace)
{
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
return workspace.CreateResourceCollection();
}
protected static InlineCategoriesDocument CreateInlineCategories(ResourceCollectionInfo collection)
{
return collection.CreateInlineCategoriesDocument();
}
protected static ReferencedCategoriesDocument CreateReferencedCategories(ResourceCollectionInfo collection)
{
return collection.CreateReferencedCategoriesDocument();
}
protected static Workspace CreateWorkspace(ServiceDocument document)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
return document.CreateWorkspace();
}
protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories, int maxExtensionSize)
{
if (categories == null)
{
throw new ArgumentNullException(nameof(categories));
}
categories.LoadElementExtensions(reader, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection, int maxExtensionSize)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
collection.LoadElementExtensions(reader, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, Workspace workspace, int maxExtensionSize)
{
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
workspace.LoadElementExtensions(reader, maxExtensionSize);
}
protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document, int maxExtensionSize)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
document.LoadElementExtensions(reader, maxExtensionSize);
}
protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document, string version)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
return document.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
return collection.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw new ArgumentNullException(nameof(categories));
}
return categories.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace, string version)
{
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
return workspace.TryParseAttribute(name, ns, value, version);
}
protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
return collection.TryParseElement(reader, version);
}
protected static bool TryParseElement(XmlReader reader, ServiceDocument document, string version)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
return document.TryParseElement(reader, version);
}
protected static bool TryParseElement(XmlReader reader, Workspace workspace, string version)
{
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
return workspace.TryParseElement(reader, version);
}
protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw new ArgumentNullException(nameof(categories));
}
return categories.TryParseElement(reader, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document, string version)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
document.WriteAttributeExtensions(writer, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace, string version)
{
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
workspace.WriteAttributeExtensions(writer, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
collection.WriteAttributeExtensions(writer, version);
}
protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw new ArgumentNullException(nameof(categories));
}
categories.WriteAttributeExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument document, string version)
{
if (document == null)
{
throw new ArgumentNullException(nameof(document));
}
document.WriteElementExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, Workspace workspace, string version)
{
if (workspace == null)
{
throw new ArgumentNullException(nameof(workspace));
}
workspace.WriteElementExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
collection.WriteElementExtensions(writer, version);
}
protected static void WriteElementExtensions(XmlWriter writer, CategoriesDocument categories, string version)
{
if (categories == null)
{
throw new ArgumentNullException(nameof(categories));
}
categories.WriteElementExtensions(writer, version);
}
protected virtual ServiceDocument CreateDocumentInstance() => new ServiceDocument();
protected virtual void SetDocument(ServiceDocument document) => _document = document;
}
}
| 33.737179 | 136 | 0.621129 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs | 10,526 | C# |
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: methodTemplate.tt
// Build date: 2017-10-08
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Dfareporting v2.7 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Manages your DoubleClick Campaign Manager ad campaigns and reports.
// API Documentation Link https://developers.google.com/doubleclick-advertisers/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Dfareporting/v2_7/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Dfareporting.v2_7/
// Install Command: PM> Install-Package Google.Apis.Dfareporting.v2_7
//
//------------------------------------------------------------------------------
using Google.Apis.Dfareporting.v2_7;
using Google.Apis.Dfareporting.v2_7.Data;
using System;
namespace GoogleSamplecSharpSample.Dfareportingv2_7.Methods
{
public static class ContentCategoriesSample
{
/// <summary>
/// Deletes an existing content category.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/delete
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Content category ID.</param>
public static void Delete(DfareportingService service, string profileId, string id)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
service.ContentCategories.Delete(profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Delete failed.", ex);
}
}
/// <summary>
/// Gets one content category by ID.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/get
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Content category ID.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Get(DfareportingService service, string profileId, string id)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
return service.ContentCategories.Get(profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Get failed.", ex);
}
}
/// <summary>
/// Inserts a new content category.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/insert
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="body">A valid Dfareporting v2.7 body.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Insert(DfareportingService service, string profileId, ContentCategory body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Make the request.
return service.ContentCategories.Insert(body, profileId).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Insert failed.", ex);
}
}
public class ContentCategoriesListOptionalParms
{
/// Select only content categories with these IDs.
public string Ids { get; set; }
/// Maximum number of results to return.
public int? MaxResults { get; set; }
/// Value of the nextPageToken from the previous result page.
public string PageToken { get; set; }
/// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "contentcategory*2015" will return objects with names like "contentcategory June 2015", "contentcategory April 2015", or simply "contentcategory 2015". Most of the searches also add wildcards implicitly at the start and the end of the search string. For example, a search string of "contentcategory" will match objects with name "my contentcategory", "contentcategory 2015", or simply "contentcategory".
public string SearchString { get; set; }
/// Field by which to sort the list.
public string SortField { get; set; }
/// Order of sorted results.
public string SortOrder { get; set; }
}
/// <summary>
/// Retrieves a list of content categories, possibly filtered. This method supports paging.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/list
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="optional">Optional paramaters.</param>
/// <returns>ContentCategoriesListResponseResponse</returns>
public static ContentCategoriesListResponse List(DfareportingService service, string profileId, ContentCategoriesListOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Building the initial request.
var request = service.ContentCategories.List(profileId);
// Applying optional parameters to the request.
request = (ContentCategoriesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
// Requesting data.
return request.Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.List failed.", ex);
}
}
/// <summary>
/// Updates an existing content category. This method supports patch semantics.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/patch
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="id">Content category ID.</param>
/// <param name="body">A valid Dfareporting v2.7 body.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Patch(DfareportingService service, string profileId, string id, ContentCategory body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
if (id == null)
throw new ArgumentNullException(id);
// Make the request.
return service.ContentCategories.Patch(body, profileId, id).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Patch failed.", ex);
}
}
/// <summary>
/// Updates an existing content category.
/// Documentation https://developers.google.com/dfareporting/v2.7/reference/contentCategories/update
/// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
/// </summary>
/// <param name="service">Authenticated Dfareporting service.</param>
/// <param name="profileId">User profile ID associated with this request.</param>
/// <param name="body">A valid Dfareporting v2.7 body.</param>
/// <returns>ContentCategoryResponse</returns>
public static ContentCategory Update(DfareportingService service, string profileId, ContentCategory body)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
if (body == null)
throw new ArgumentNullException("body");
if (profileId == null)
throw new ArgumentNullException(profileId);
// Make the request.
return service.ContentCategories.Update(body, profileId).Execute();
}
catch (Exception ex)
{
throw new Exception("Request ContentCategories.Update failed.", ex);
}
}
}
public static class SampleHelpers
{
/// <summary>
/// Using reflection to apply optional parameters to the request.
///
/// If the optonal parameters are null then we will just return the request as is.
/// </summary>
/// <param name="request">The request. </param>
/// <param name="optional">The optional parameters. </param>
/// <returns></returns>
public static object ApplyOptionalParms(object request, object optional)
{
if (optional == null)
return request;
System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();
foreach (System.Reflection.PropertyInfo property in optionalProperties)
{
// Copy value from optional parms to the request. They should have the same names and datatypes.
System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
piShared.SetValue(request, property.GetValue(optional, null), null);
}
return request;
}
}
} | 47.686411 | 503 | 0.596741 | [
"Apache-2.0"
] | AhmerRaza/Google-Dotnet-Samples | Samples/DCM/DFA Reporting And Trafficking API/v2.7/ContentCategoriesSample.cs | 13,688 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
using Xunit.Abstractions;
namespace Commands.Network.Test.ScenarioTests
{
public class NetworkWatcherAPITests : Microsoft.WindowsAzure.Commands.Test.Utilities.Common.RMTestBase
{
public NetworkWatcherAPITests(ITestOutputHelper output)
{
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetTopology()
{
NetworkResourcesController.NewInstance.RunPsTest("Test-GetTopology");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetSecurityGroupView()
{
NetworkResourcesController.NewInstance.RunPsTest("Test-GetSecurityGroupView");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetNextHop()
{
NetworkResourcesController.NewInstance.RunPsTest("Test-GetNextHop");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestVerifyIPFlow()
{
NetworkResourcesController.NewInstance.RunPsTest("Test-VerifyIPFlow");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestPacketCapture()
{
NetworkResourcesController.NewInstance.RunPsTest("Test-PacketCapture");
}
[Fact(Skip = "Rerecord tests")]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestTroubleshoot()
{
NetworkResourcesController.NewInstance.RunPsTest("Test-Troubleshoot");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestFlowLog()
{
NetworkResourcesController.NewInstance.RunPsTest("Test-FlowLog");
}
}
}
| 36.316456 | 107 | 0.620077 | [
"MIT"
] | FosterMichelle/azure-powershell | src/ResourceManager/Network/Commands.Network.Test/ScenarioTests/NetworkWatcherAPITests.cs | 2,793 | 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 macie2-2020-01-01.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.Macie2.Model
{
/// <summary>
/// This is the response object from the DescribeClassificationJob operation.
/// </summary>
public partial class DescribeClassificationJobResponse : AmazonWebServiceResponse
{
private string _clientToken;
private DateTime? _createdAt;
private List<string> _customDataIdentifierIds = new List<string>();
private string _description;
private bool? _initialRun;
private string _jobArn;
private string _jobId;
private JobStatus _jobStatus;
private JobType _jobType;
private DateTime? _lastRunTime;
private string _name;
private S3JobDefinition _s3JobDefinition;
private int? _samplingPercentage;
private JobScheduleFrequency _scheduleFrequency;
private Statistics _statistics;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// The token that was provided to ensure the idempotency of the request to create the
/// job.
/// </para>
/// </summary>
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property CreatedAt.
/// <para>
/// The date and time, in UTC and extended ISO 8601 format, when the job was created.
/// </para>
/// </summary>
public DateTime CreatedAt
{
get { return this._createdAt.GetValueOrDefault(); }
set { this._createdAt = value; }
}
// Check to see if CreatedAt property is set
internal bool IsSetCreatedAt()
{
return this._createdAt.HasValue;
}
/// <summary>
/// Gets and sets the property CustomDataIdentifierIds.
/// <para>
/// The custom data identifiers that the job uses to analyze data.
/// </para>
/// </summary>
public List<string> CustomDataIdentifierIds
{
get { return this._customDataIdentifierIds; }
set { this._customDataIdentifierIds = value; }
}
// Check to see if CustomDataIdentifierIds property is set
internal bool IsSetCustomDataIdentifierIds()
{
return this._customDataIdentifierIds != null && this._customDataIdentifierIds.Count > 0;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The custom description of the job.
/// </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 InitialRun.
/// <para>
/// Specifies whether the job has run for the first time.
/// </para>
/// </summary>
public bool InitialRun
{
get { return this._initialRun.GetValueOrDefault(); }
set { this._initialRun = value; }
}
// Check to see if InitialRun property is set
internal bool IsSetInitialRun()
{
return this._initialRun.HasValue;
}
/// <summary>
/// Gets and sets the property JobArn.
/// <para>
/// The Amazon Resource Name (ARN) of the job.
/// </para>
/// </summary>
public string JobArn
{
get { return this._jobArn; }
set { this._jobArn = value; }
}
// Check to see if JobArn property is set
internal bool IsSetJobArn()
{
return this._jobArn != null;
}
/// <summary>
/// Gets and sets the property JobId.
/// <para>
/// The unique identifier for the job.
/// </para>
/// </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>
/// Gets and sets the property JobStatus.
/// <para>
/// The current status of the job. Possible value are:
/// </para>
/// <ul><li>
/// <para>
/// CANCELLED - The job was cancelled by you or a user of the master account for your
/// organization. A job might also be cancelled if ownership of an S3 bucket changed while
/// the job was running, and that change affected the job's access to the bucket.
/// </para>
/// </li> <li>
/// <para>
/// COMPLETE - Amazon Macie finished processing all the data specified for the job.
/// </para>
/// </li> <li>
/// <para>
/// IDLE - For a recurring job, the previous scheduled run is complete and the next scheduled
/// run is pending. This value doesn't apply to jobs that occur only once.
/// </para>
/// </li> <li>
/// <para>
/// PAUSED - Amazon Macie started the job, but completion of the job would exceed one
/// or more quotas for your account.
/// </para>
/// </li> <li>
/// <para>
/// RUNNING - The job is in progress.
/// </para>
/// </li></ul>
/// </summary>
public JobStatus JobStatus
{
get { return this._jobStatus; }
set { this._jobStatus = value; }
}
// Check to see if JobStatus property is set
internal bool IsSetJobStatus()
{
return this._jobStatus != null;
}
/// <summary>
/// Gets and sets the property JobType.
/// <para>
/// The schedule for running the job. Possible value are:
/// </para>
/// <ul><li>
/// <para>
/// ONE_TIME - The job ran or will run only once.
/// </para>
/// </li> <li>
/// <para>
/// SCHEDULED - The job runs on a daily, weekly, or monthly basis. The scheduleFrequency
/// property indicates the recurrence pattern for the job.
/// </para>
/// </li></ul>
/// </summary>
public JobType JobType
{
get { return this._jobType; }
set { this._jobType = value; }
}
// Check to see if JobType property is set
internal bool IsSetJobType()
{
return this._jobType != null;
}
/// <summary>
/// Gets and sets the property LastRunTime.
/// <para>
/// The date and time, in UTC and extended ISO 8601 format, when the job last ran.
/// </para>
/// </summary>
public DateTime LastRunTime
{
get { return this._lastRunTime.GetValueOrDefault(); }
set { this._lastRunTime = value; }
}
// Check to see if LastRunTime property is set
internal bool IsSetLastRunTime()
{
return this._lastRunTime.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The custom name of the job.
/// </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 S3JobDefinition.
/// <para>
/// The S3 buckets that the job is configured to analyze, and the scope of that analysis.
/// </para>
/// </summary>
public S3JobDefinition S3JobDefinition
{
get { return this._s3JobDefinition; }
set { this._s3JobDefinition = value; }
}
// Check to see if S3JobDefinition property is set
internal bool IsSetS3JobDefinition()
{
return this._s3JobDefinition != null;
}
/// <summary>
/// Gets and sets the property SamplingPercentage.
/// <para>
/// The sampling depth, as a percentage, that the job applies when it processes objects.
/// </para>
/// </summary>
public int SamplingPercentage
{
get { return this._samplingPercentage.GetValueOrDefault(); }
set { this._samplingPercentage = value; }
}
// Check to see if SamplingPercentage property is set
internal bool IsSetSamplingPercentage()
{
return this._samplingPercentage.HasValue;
}
/// <summary>
/// Gets and sets the property ScheduleFrequency.
/// <para>
/// The recurrence pattern for running the job. If the job is configured to run every
/// day, this value is an empty dailySchedule object. If the job is configured to run
/// only once, this value is null.
/// </para>
/// </summary>
public JobScheduleFrequency ScheduleFrequency
{
get { return this._scheduleFrequency; }
set { this._scheduleFrequency = value; }
}
// Check to see if ScheduleFrequency property is set
internal bool IsSetScheduleFrequency()
{
return this._scheduleFrequency != null;
}
/// <summary>
/// Gets and sets the property Statistics.
/// <para>
/// The number of times that the job has run and processing statistics for the job's most
/// recent run.
/// </para>
/// </summary>
public Statistics Statistics
{
get { return this._statistics; }
set { this._statistics = value; }
}
// Check to see if Statistics property is set
internal bool IsSetStatistics()
{
return this._statistics != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// A map of key-value pairs that identifies the tags (keys and values) that are associated
/// with the classification job.
/// </para>
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 31.637795 | 104 | 0.5482 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/Macie2/Generated/Model/DescribeClassificationJobResponse.cs | 12,054 | C# |
using System;
using EifelMono.Fluent.IO;
using EifelMono.Fluent.NuGet;
using EifelMono.Fluent.Test.XunitTests;
using Xunit;
using Xunit.Abstractions;
namespace EifelMono.Fluent.Test.DotNetTests
{
#pragma warning disable IDE1006 // Naming Styles
public class NugetTests : XunitCore
{
public NugetTests(ITestOutputHelper output) : base(output) { }
[Fact(Skip = "Does not work at this time")]
public async void GetPackageVersionsTest()
{
{
var (Ok, Value) = await nuget.org.GetPackageVersionsAsync("EifelMono.Fluent", false);
Assert.True(Ok);
Dump(Value, "Versions for EifelMono.Fluent");
Assert.NotEmpty(Value);
}
{
var (Ok, Value) = await nuget.org.GetPackageVersionsAsync("EifelMono.Fluent", true);
Assert.True(Ok);
Dump(Value, "Versions for EifelMono.Fluent");
Assert.NotEmpty(Value);
}
}
[Fact(Skip = "Does not work at this time")]
public async void GetPackageDownloadTest()
{
{
WriteLine($"EifelMono.Fluent Download Folder {DirectoryPath.OS.Temp} ");
var result = await nuget.org.DownloadLatestPackageAsync("EifelMono.Fluent", DirectoryPath.OS.Temp);
Assert.True(result.Ok);
Dump(result, "nuget.DownloadLatestPackageAsync");
}
{
WriteLine($"EifelMono.Fluent Download Folder {DirectoryPath.OS.Temp}");
var result = await nuget.org.DownloadLatestPreReleasePackageAsync("EifelMono.Fluent", DirectoryPath.OS.Temp);
Assert.True(result.Ok);
Dump(result, "nuget.DownloadLatestPreReleasePackageAsync");
}
}
}
#pragma warning restore IDE1006 // Naming Styles
}
| 36.461538 | 125 | 0.596519 | [
"MIT"
] | EifelMono/EifelMono.Fluent | src/EifelMono.Fluent.Test/DotNetTests/NugetTests.cs | 1,898 | C# |
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace FMODUnity
{
[CustomEditor(typeof(StudioParameterTrigger))]
public class StudioParameterTriggerEditor : Editor
{
StudioEventEmitter targetEmitter;
SerializedProperty emitters;
SerializedProperty trigger;
SerializedProperty tag;
bool[] expanded;
void OnEnable()
{
emitters = serializedObject.FindProperty("Emitters");
trigger = serializedObject.FindProperty("TriggerEvent");
tag = serializedObject.FindProperty("CollisionTag");
targetEmitter = null;
for (int i = 0; i < emitters.arraySize; i++)
{
targetEmitter = emitters.GetArrayElementAtIndex(i).FindPropertyRelative("Target").objectReferenceValue as StudioEventEmitter;
if (targetEmitter != null)
{
expanded = new bool[targetEmitter.GetComponents<StudioEventEmitter>().Length];
break;
}
}
}
public override void OnInspectorGUI()
{
var newTargetEmitter = EditorGUILayout.ObjectField("Target", targetEmitter, typeof(StudioEventEmitter), true) as StudioEventEmitter;
if (newTargetEmitter != targetEmitter)
{
emitters.ClearArray();
targetEmitter = newTargetEmitter;
if (targetEmitter == null)
{
serializedObject.ApplyModifiedProperties();
return;
}
List<StudioEventEmitter> newEmitters = new List<StudioEventEmitter>();
targetEmitter.GetComponents(newEmitters);
expanded = new bool[newEmitters.Count];
foreach (var emitter in newEmitters)
{
emitters.InsertArrayElementAtIndex(0);
emitters.GetArrayElementAtIndex(0).FindPropertyRelative("Target").objectReferenceValue = emitter;
}
}
if (targetEmitter == null)
{
return;
}
EditorGUILayout.PropertyField(trigger, new GUIContent("Trigger"));
if (trigger.enumValueIndex >= (int)EmitterGameEvent.TriggerEnter && trigger.enumValueIndex <= (int)EmitterGameEvent.TriggerExit2D)
{
tag.stringValue = EditorGUILayout.TagField("Collision Tag", tag.stringValue);
}
var localEmitters = new List<StudioEventEmitter>();
targetEmitter.GetComponents(localEmitters);
int emitterIndex = 0;
foreach (var emitter in localEmitters)
{
SerializedProperty emitterProperty = null;
for(int i = 0; i < emitters.arraySize; i++)
{
if (emitters.GetArrayElementAtIndex(i).FindPropertyRelative("Target").objectReferenceValue == emitter)
{
emitterProperty = emitters.GetArrayElementAtIndex(i);
break;
}
}
// New emitter component added to game object since we last looked
if (emitterProperty == null)
{
emitters.InsertArrayElementAtIndex(0);
emitterProperty = emitters.GetArrayElementAtIndex(0);
emitterProperty.FindPropertyRelative("Target").objectReferenceValue = emitter;
}
if (!string.IsNullOrEmpty(emitter.Event))
{
expanded[emitterIndex] = EditorGUILayout.Foldout(expanded[emitterIndex], emitter.Event);
if (expanded[emitterIndex])
{
var eventRef = EventManager.EventFromPath(emitter.Event);
if (emitter.Event.StartsWith("{"))
{
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.TextField("Path:", eventRef.Path);
EditorGUI.EndDisabledGroup();
}
foreach (var paramRef in eventRef.Parameters)
{
bool set = false;
int index = -1;
for (int i = 0; i < emitterProperty.FindPropertyRelative("Params").arraySize; i++)
{
if (emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(i).FindPropertyRelative("Name").stringValue == paramRef.Name)
{
index = i;
set = true;
break;
}
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(paramRef.Name);
bool newSet = GUILayout.Toggle(set, "");
if (!set && newSet)
{
index = 0;
emitterProperty.FindPropertyRelative("Params").InsertArrayElementAtIndex(0);
emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(0).FindPropertyRelative("Name").stringValue = paramRef.Name;
emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(0).FindPropertyRelative("Value").floatValue = 0;
}
if (set && !newSet)
{
emitterProperty.FindPropertyRelative("Params").DeleteArrayElementAtIndex(index);
}
set = newSet;
EditorGUI.BeginDisabledGroup(!set);
if (set)
{
var valueProperty = emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(index).FindPropertyRelative("Value");
valueProperty.floatValue = EditorGUILayout.Slider(valueProperty.floatValue, paramRef.Min, paramRef.Max);
}
else
{
EditorGUILayout.Slider(0, paramRef.Min, paramRef.Max);
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
}
}
}
emitterIndex++;
}
serializedObject.ApplyModifiedProperties();
}
}
} | 45.149351 | 167 | 0.495182 | [
"MIT"
] | 631-Infection-Team/infection | Assets/Plugins/FMOD/src/Editor/StudioParameterTriggerEditor.cs | 6,955 | C# |
using CXUtils.Components;
using UnityEditor;
[CustomEditor( typeof( CharacterController2D ) )]
public class CharacterController2DInspectorWindow : Editor
{
public override void OnInspectorGUI()
{
var charControl2D = (CharacterController2D)target;
base.OnInspectorGUI();
if ( charControl2D.Perspec != CharacterController2D.PerspectiveMode.Platformer ) return;
EditorGUILayout.LabelField( "Platformer Extra Content" );
charControl2D.CharacterGroundCheck =
(CharacterGroundCheck2D)
EditorGUILayout.ObjectField( "Ground Check 2D", charControl2D.CharacterGroundCheck, typeof( CharacterGroundCheck2D ), true );
charControl2D.PlayerCurrentJumpStrength =
EditorGUILayout.FloatField( "Jump Strength", charControl2D.PlayerCurrentJumpStrength );
}
}
| 32.423077 | 137 | 0.730724 | [
"MIT"
] | AMAIOLAMO/CXUtils-Unity | Scripts/Editor/PlayerMovements/2D/Controller/CharacterController2DInspectorWindow.cs | 845 | 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 Microsoft.CodeAnalysis.PooledObjects;
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 data structure.
// 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 bool AnyValidResult<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results)
where TMember : Symbol
{
foreach (var result in results)
{
if (result.IsValid)
{
return true;
}
}
return false;
}
private static bool SingleValidResult<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results)
where TMember : Symbol
{
bool oneValid = false;
foreach (var result in results)
{
if (result.IsValid)
{
if (oneValid)
{
return false;
}
oneValid = true;
}
}
return oneValid;
}
// 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;
}
return SingleValidResult(results);
}
// 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 (!AnyValidResult(results))
{
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, completeResults, ref useSiteDiagnostics);
var result = normalResult;
if (!normalResult.IsValid)
{
if (IsValidParams(constructor))
{
var expandedResult = IsConstructorApplicableInExpandedForm(constructor, arguments, completeResults, 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,
bool completeResults,
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,
completeResults: completeResults,
useSiteDiagnostics: ref useSiteDiagnostics);
}
private MemberAnalysisResult IsConstructorApplicableInExpandedForm(
MethodSymbol constructor,
AnalyzedArguments arguments,
bool completeResults,
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,
completeResults: completeResults,
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, TypeCompareKind.ConsiderEverything, 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: isMethodGroupConversion,
allowRefOmittedArguments: allowRefOmittedArguments,
inferWithDynamic: inferWithDynamic,
completeResults: completeResults,
useSiteDiagnostics: 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: allowRefOmittedArguments,
completeResults: completeResults,
useSiteDiagnostics: 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 Goo<T>(params T[]) and a call
// Goo(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:
case MemberResolutionKind.UseSiteError:
case MemberResolutionKind.BadNonTrailingNamedArgument:
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.IsSZArray();
}
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, TypeCompareKind.ConsiderEverything, 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, TypeCompareKind.ConsiderEverything, useSiteDiagnostics: ref useSiteDiagnostics))
{
return true;
}
}
return false;
}
private static void RemoveAllInterfaceMembers<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results)
where TMember : Symbol
{
// Consider the following case:
//
// interface IGoo { string ToString(); }
// class C { public override string ToString() { whatever } }
// class D : C, IGoo
// {
// public override string ToString() { whatever }
// string IGoo.ToString() { whatever }
// }
// ...
// void M<U>(U u) where U : C, IGoo { u.ToString(); } // ???
// ...
// M(new D());
//
// What should overload resolution do on the call to u.ToString()?
//
// We will have IGoo.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 int GetTheBestCandidateIndex<TMember>(ArrayBuilder<MemberResolutionResult<TMember>> results, AnalyzedArguments arguments, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
where TMember : Symbol
{
int currentBestIndex = -1;
for (int index = 0; index < results.Count; index++)
{
if (!results[index].IsValid)
{
continue;
}
// Assume that the current candidate is the best if we don't have any
if (currentBestIndex == -1)
{
currentBestIndex = index;
}
else if (results[currentBestIndex].Member == results[index].Member)
{
currentBestIndex = -1;
}
else
{
var better = BetterFunctionMember(results[currentBestIndex], results[index], arguments.Arguments, ref useSiteDiagnostics);
if (better == BetterResult.Right)
{
// The current best is worse
currentBestIndex = index;
}
else if (better != BetterResult.Left)
{
// The current best is not better
currentBestIndex = -1;
}
}
}
// Make sure that every candidate up to the current best is worse
for (int index = 0; index < currentBestIndex; index++)
{
if (!results[index].IsValid)
{
continue;
}
if (results[currentBestIndex].Member == results[index].Member)
{
return -1;
}
var better = BetterFunctionMember(results[currentBestIndex], results[index], arguments.Arguments, ref useSiteDiagnostics);
if (better != BetterResult.Left)
{
// The current best is not better
return -1;
}
}
return currentBestIndex;
}
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.
if (SingleValidResult(results))
{
return;
}
// See if we have a winner, otherwise we might need to perform additional analysis
// in order to improve diagnostics
int bestIndex = GetTheBestCandidateIndex(results, arguments, ref useSiteDiagnostics);
if (bestIndex != -1)
{
// Mark all other candidates as worse
for (int index = 0; index < results.Count; index++)
{
if (results[index].IsValid && index != bestIndex)
{
results[index] = results[index].Worse();
}
}
return;
}
const int unknown = 0;
const int worseThanSomething = 1;
const int notBetterThanEverything = 2;
var worse = ArrayBuilder<int>.GetInstance(results.Count, unknown);
int countOfNotBestCandidates = 0;
int notBestIdx = -1;
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.IsValid || worse[c1Idx] == worseThanSomething)
{
continue;
}
for (int c2Idx = 0; c2Idx < results.Count; c2Idx++)
{
var c2Result = results[c2Idx];
if (!c2Result.IsValid || c1Idx == c2Idx || c1Result.Member == c2Result.Member)
{
continue;
}
var better = BetterFunctionMember(c1Result, c2Result, arguments.Arguments, ref useSiteDiagnostics);
if (better == BetterResult.Left)
{
worse[c2Idx] = worseThanSomething;
}
else if (better == BetterResult.Right)
{
worse[c1Idx] = worseThanSomething;
break;
}
}
if (worse[c1Idx] == unknown)
{
// c1 was not worse than anything
worse[c1Idx] = notBetterThanEverything;
countOfNotBestCandidates++;
notBestIdx = c1Idx;
}
}
if (countOfNotBestCandidates == 0)
{
for (int i = 0; i < worse.Count; ++i)
{
Debug.Assert(!results[i].IsValid || worse[i] != unknown);
if (worse[i] == worseThanSomething)
{
results[i] = results[i].Worse();
}
}
}
else if (countOfNotBestCandidates == 1)
{
for (int i = 0; i < worse.Count; ++i)
{
Debug.Assert(!results[i].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.
results[i] = BetterResult.Left == BetterFunctionMember(results[notBestIdx], results[i], arguments.Arguments, ref useSiteDiagnostics)
? results[i].Worst() : results[i].Worse();
}
else
{
Debug.Assert(worse[i] != notBetterThanEverything || i == notBestIdx);
}
}
Debug.Assert(worse[notBestIdx] == notBetterThanEverything);
results[notBestIdx] = results[notBestIdx].Worse();
}
else
{
Debug.Assert(countOfNotBestCandidates > 1);
for (int i = 0; i < worse.Count; ++i)
{
Debug.Assert(!results[i].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] = results[i].Worst();
}
else if (worse[i] == notBetterThanEverything)
{
results[i] = results[i].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.IsSZArray())
{
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, ignoring Task-like differences?
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;
BetterResult r;
r = BetterConversionFromExpression(arguments[i],
type1,
m1.Result.ConversionForArg(i),
refKind1,
type2,
m2.Result.ConversionForArg(i),
refKind2,
considerRefKinds,
ref useSiteDiagnostics,
out okToDowngradeToNeither);
var type1Normalized = type1.NormalizeTaskTypes(Compilation);
var type2Normalized = type2.NormalizeTaskTypes(Compilation);
if (r == BetterResult.Neither)
{
if (allSame && Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteDiagnostics).Kind != ConversionKind.Identity)
{
allSame = false;
}
// We learned nothing from this one. Keep going.
continue;
}
if (Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, ref useSiteDiagnostics).Kind != ConversionKind.Identity)
{
allSame = false;
}
// One of them was better, even if identical up to Task-likeness. 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 if 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 ignoring Task-like differences (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);
var type1Normalized = type1.NormalizeTaskTypes(Compilation);
var type2Normalized = type2.NormalizeTaskTypes(Compilation);
if (Conversions.ClassifyImplicitConversionFromType(type1Normalized, type2Normalized, 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)
{
// 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 (arguments[i].Kind == BoundKind.ArgListOperator)
{
Debug.Assert(i == arguments.Count - 1);
Debug.Assert(m1.Member.GetIsVararg() && m2.Member.GetIsVararg());
continue;
}
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)
{
ImmutableArray<int> argsToParamsOpt = m.Result.ArgsToParamsOpt;
if (argsToParamsOpt.IsDefaultOrEmpty || !argsToParamsOpt.Contains(declaredParameterCount - 1))
{
// params parameter isn't used (see ExpressionBinder::TryGetExpandedParams in the native compiler)
parametersUsedIncludingExpansionAndOptional = declaredParameterCount - 1;
}
else
{
// params parameter is used by a named argument
parametersUsedIncludingExpansionAndOptional = declaredParameterCount;
}
}
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.HasSameShapeAs(arr2));
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.TupleUnderlyingTypeOrSelf() as NamedTypeSymbol;
var n2 = t2.TupleUnderlyingTypeOrSelf() 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, or they are different Task-likes. Ideally we'd assert that the two types (or
// Task equivalents) have the same OriginalDefinition but we don't have a Compilation
// here for NormalizeTaskTypes.
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;
var nodeKind = node.Kind;
if (nodeKind == BoundKind.OutVariablePendingInference ||
nodeKind == BoundKind.OutDeconstructVarPendingInference ||
(nodeKind == BoundKind.DiscardExpression && !node.HasExpressionType()))
{
// Neither conversion from expression is better when the argument is an implicitly-typed out variable declaration.
okToDowngradeToNeither = false;
return BetterResult.Neither;
}
// 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)
{
// - 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 T2
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(node, t1, conv1, t2, conv2, 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;
}
if (node.Kind == BoundKind.TupleLiteral)
{
// Recurse into tuple constituent arguments.
// Even if the tuple literal has a natural type and conversion
// from that type is not identity, we still have to do this
// because we might be converting to a tuple type backed by
// different definition of ValueTuple type.
return ExpressionMatchExactly((BoundTupleLiteral)node, t, ref useSiteDiagnostics);
}
// - 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.IsGenericTaskType(Compilation))
{
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;
}
// check every argument of a tuple vs corresponding type in destination tuple type
private bool ExpressionMatchExactly(BoundTupleLiteral tupleSource, TypeSymbol targetType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
if (targetType.Kind != SymbolKind.NamedType)
{
// tuples can only match to tuples or tuple underlying types and either is a named type
return false;
}
var destination = (NamedTypeSymbol)targetType;
var sourceArguments = tupleSource.Arguments;
// check if the type is actually compatible type for a tuple of given cardinality
if (!destination.IsTupleOrCompatibleWithTupleOfCardinality(sourceArguments.Length))
{
return false;
}
var destTypes = destination.GetElementTypesOfTupleOrCompatible();
Debug.Assert(sourceArguments.Length == destTypes.Length);
for (int i = 0; i < sourceArguments.Length; i++)
{
if (!ExpressionMatchExactly(sourceArguments[i], destTypes[i], ref useSiteDiagnostics))
{
return false;
}
}
return true;
}
private class ReturnStatements : BoundTreeWalker
{
private readonly ArrayBuilder<BoundReturnStatement> _returns;
public ReturnStatements(ArrayBuilder<BoundReturnStatement> returns)
{
_returns = returns;
}
public override BoundNode Visit(BoundNode node)
{
if (!(node is BoundExpression))
{
return base.Visit(node);
}
return null;
}
protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
// Do not recurse into nested local functions; we don't want their returns.
return null;
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
_returns.Add(node);
return null;
}
}
private const int BetterConversionTargetRecursionLimit = 100;
private BetterResult BetterConversionTarget(
TypeSymbol type1,
TypeSymbol type2,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
bool okToDowngradeToNeither;
return BetterConversionTargetCore(null, type1, default(Conversion), type2, default(Conversion), ref useSiteDiagnostics, out okToDowngradeToNeither, BetterConversionTargetRecursionLimit);
}
private BetterResult BetterConversionTargetCore(
TypeSymbol type1,
TypeSymbol type2,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
int betterConversionTargetRecursionLimit)
{
if (betterConversionTargetRecursionLimit < 0)
{
return BetterResult.Neither;
}
bool okToDowngradeToNeither;
return BetterConversionTargetCore(null, type1, default(Conversion), type2, default(Conversion), ref useSiteDiagnostics, out okToDowngradeToNeither, betterConversionTargetRecursionLimit - 1);
}
private BetterResult BetterConversionTarget(
BoundExpression node,
TypeSymbol type1,
Conversion conv1,
TypeSymbol type2,
Conversion conv2,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
out bool okToDowngradeToNeither)
{
return BetterConversionTargetCore(node, type1, conv1, type2, conv2, ref useSiteDiagnostics, out okToDowngradeToNeither, BetterConversionTargetRecursionLimit);
}
private BetterResult BetterConversionTargetCore(
BoundExpression node,
TypeSymbol type1,
Conversion conv1,
TypeSymbol type2,
Conversion conv2,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
out bool okToDowngradeToNeither,
int betterConversionTargetRecursionLimit)
{
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.ClassifyImplicitConversionFromType(type1, type2, ref useSiteDiagnostics).IsImplicit;
bool type2ToType1 = Conversions.ClassifyImplicitConversionFromType(type2, type1, ref useSiteDiagnostics).IsImplicit;
UnboundLambda lambdaOpt = node as UnboundLambda;
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 type1IsGenericTask = type1.OriginalDefinition.IsGenericTaskType(Compilation);
bool type2IsGenericTask = type2.OriginalDefinition.IsGenericTaskType(Compilation);
if (type1IsGenericTask)
{
if (type2IsGenericTask)
{
// - T1 is Task<S1>, T2 is Task<S2>, and S1 is a better conversion target than S2
return BetterConversionTargetCore(((NamedTypeSymbol)type1).TypeArgumentsNoUseSiteDiagnostics[0],
((NamedTypeSymbol)type2).TypeArgumentsNoUseSiteDiagnostics[0],
ref useSiteDiagnostics, betterConversionTargetRecursionLimit);
}
// A shortcut, Task<T> type cannot satisfy other rules.
return BetterResult.Neither;
}
else if (type2IsGenericTask)
{
// 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;
BetterResult delegateResult = BetterResult.Neither;
if (r1.SpecialType != SpecialType.System_Void)
{
if (r2.SpecialType == SpecialType.System_Void)
{
// - D2 is void returning
delegateResult = BetterResult.Left;
}
}
else if (r2.SpecialType != SpecialType.System_Void)
{
// - D2 is void returning
delegateResult = BetterResult.Right;
}
if (delegateResult == BetterResult.Neither)
{
// - D2 has a return type S2, and S1 is a better conversion target than S2
delegateResult = BetterConversionTargetCore(r1, r2, ref useSiteDiagnostics, betterConversionTargetRecursionLimit);
}
// Downgrade result to Neither if conversion used by the winner isn't actually valid method group conversion.
// This is necessary to preserve compatibility, otherwise we might dismiss "worse", but trully applicable candidate
// based on a "better", but, in reality, erroneous one.
if (node?.Kind == BoundKind.MethodGroup)
{
var group = (BoundMethodGroup)node;
if (delegateResult == BetterResult.Left)
{
if (IsMethodGroupConversionIncompatibleWithDelegate(group, d1, conv1))
{
return BetterResult.Neither;
}
}
else if (delegateResult == BetterResult.Right && IsMethodGroupConversionIncompatibleWithDelegate(group, d2, conv2))
{
return BetterResult.Neither;
}
}
return delegateResult;
}
}
// 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 IsMethodGroupConversionIncompatibleWithDelegate(BoundMethodGroup node, NamedTypeSymbol delegateType, Conversion conv)
{
if (conv.IsMethodGroup)
{
DiagnosticBag ignore = DiagnosticBag.GetInstance();
bool result = !_binder.MethodGroupIsCompatibleWithDelegate(node.ReceiverOpt, conv.IsExtensionMethod, conv.Method, delegateType, Location.None, ignore);
ignore.Free();
return result;
}
return false;
}
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)
{
// 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(r1, r2, ref useSiteDiagnostics));
}
#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)
{
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, or an extra argument in error situations, 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;
// 'None' argument is allowed to match 'In' parameter and should behave like 'None' for the purpose of overload resolution
if (argRefKind == RefKind.None && paramRefKind == RefKind.In)
{
return RefKind.None;
}
// 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);
}
private 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,
bool completeResults,
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)
{
switch (argumentAnalysis.Kind)
{
case ArgumentAnalysisResultKind.RequiredParameterMissing:
case ArgumentAnalysisResultKind.NoCorrespondingParameter:
if (!completeResults) goto default;
// When we are producing more complete results, and we have the wrong number of arguments, we push on
// through type inference so that lambda arguments can be bound to their delegate-typed parameters,
// thus improving the API and intellisense experience.
break;
default:
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.
var applicableResult = IsApplicable(
member, leastOverriddenMember,
typeArguments, arguments, originalEffectiveParameters, constructedEffectiveParameters,
argumentAnalysis.ArgsToParamsOpt,
hasAnyRefOmittedArgument: hasAnyRefOmittedArgument,
inferWithDynamic: inferWithDynamic,
completeResults: completeResults,
useSiteDiagnostics: ref useSiteDiagnostics);
// If we were producing complete results and had missing arguments, we pushed on in order to call IsApplicable for
// type inference and lambda binding. In that case we still need to return the argument mismatch failure here.
if (completeResults && !argumentAnalysis.IsValid)
{
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, MemberAnalysisResult.ArgumentParameterMismatch(argumentAnalysis));
}
return applicableResult;
}
private MemberResolutionResult<TMember> IsMemberApplicableInExpandedForm<TMember>(
TMember member, // method or property
TMember leastOverriddenMember, // method or property
ArrayBuilder<TypeSymbol> typeArguments,
AnalyzedArguments arguments,
bool allowRefOmittedArguments,
bool completeResults,
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: hasAnyRefOmittedArgument,
inferWithDynamic: false,
completeResults: completeResults,
useSiteDiagnostics: 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,
bool inferWithDynamic,
bool completeResults,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
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.SelectAsArray(TypeMap.TypeSymbolAsTypeWithModifiers), allowAlpha: true);
effectiveParameters = new EffectiveParameters(
map.SubstituteTypesWithoutModifiers(constructedEffectiveParameters.ParameterTypes),
constructedEffectiveParameters.ParameterRefKinds);
ignoreOpenTypes = false;
}
}
else
{
effectiveParameters = constructedEffectiveParameters;
ignoreOpenTypes = false;
}
var applicableResult = IsApplicable(
member,
effectiveParameters,
arguments,
argsToParamsMap,
isVararg: member.GetIsVararg(),
hasAnyRefOmittedArgument: hasAnyRefOmittedArgument,
ignoreOpenTypes: ignoreOpenTypes,
completeResults: completeResults,
useSiteDiagnostics: ref useSiteDiagnostics);
return new MemberResolutionResult<TMember>(member, leastOverriddenMember, applicableResult);
}
private ImmutableArray<TypeSymbol> InferMethodTypeArguments(
MethodSymbol method,
ImmutableArray<TypeParameterSymbol> originalTypeParameters,
AnalyzedArguments arguments,
EffectiveParameters originalEffectiveParameters,
out MemberAnalysisResult error,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
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,
args,
ref useSiteDiagnostics);
if (inferenceResult.Success)
{
error = default(MemberAnalysisResult);
return inferenceResult.InferredTypeArguments;
}
if (arguments.IsExtensionMethodInvocation)
{
var inferredFromFirstArgument = MethodTypeInferrer.InferTypeArgumentsFromFirstArgument(_binder.Conversions, method, 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,
bool completeResults,
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);
if (arguments.Arguments.Count < paramCount)
{
// For improved error recovery, we perform type inference even when the argument
// list is of the wrong length. The caller is expected to detect and handle that,
// treating the method as inapplicable.
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);
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 argumentRefKind = arguments.RefKind(argumentPosition);
RefKind parameterRefKind = parameters.ParameterRefKinds.IsDefault ? RefKind.None : parameters.ParameterRefKinds[argumentPosition];
bool forExtensionMethodThisArg = arguments.IsExtensionMethodThisArgument(argumentPosition);
if (forExtensionMethodThisArg)
{
Debug.Assert(argumentRefKind == RefKind.None);
if (parameterRefKind == RefKind.Ref)
{
// For ref extension methods, we omit the "ref" modifier on the receiver arguments
// Passing the parameter RefKind for finding the correct conversion.
// For ref-readonly extension methods, argumentRefKind is always None.
argumentRefKind = parameterRefKind;
}
}
conversion = CheckArgumentForApplicability(
candidate,
argument,
argumentRefKind,
parameters.ParameterTypes[argumentPosition],
parameterRefKind,
ignoreOpenTypes,
ref useSiteDiagnostics,
forExtensionMethodThisArg);
if (forExtensionMethodThisArg && !Conversions.IsValidExtensionMethodThisArgConversion(conversion))
{
// Return early, without checking conversions of subsequent arguments,
// if the instance argument is not convertible to the 'this' parameter,
// even when 'completeResults' is requested. This avoids unnecessary
// lambda binding in particular, for instance, with LINQ expressions.
// Note that BuildArgumentsForErrorRecovery will still bind some number
// of overloads for the semantic model.
Debug.Assert(badArguments == null);
Debug.Assert(conversions == null);
return MemberAnalysisResult.BadArgumentConversions(argsToParameters, ImmutableArray.Create(argumentPosition), ImmutableArray.Create(conversion));
}
if (!conversion.Exists)
{
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);
}
if (badArguments != null && !completeResults)
{
break;
}
}
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,
bool forExtensionMethodThisArg)
{
// 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 either:
// 1) parameter is an 'In' or
// 2) 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 && (parRefKind == RefKind.In || 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;
}
var argType = argument.Type;
if (argument.Kind == BoundKind.OutVariablePendingInference ||
argument.Kind == BoundKind.OutDeconstructVarPendingInference ||
(argument.Kind == BoundKind.DiscardExpression && (object)argType == null))
{
Debug.Assert(argRefKind != RefKind.None);
// Any parameter type is good, we'll use it for the var local.
return Conversion.Identity;
}
if (argRefKind == RefKind.None)
{
var conversion = forExtensionMethodThisArg ?
Conversions.ClassifyImplicitExtensionMethodThisArgConversion(argument, argument.Type, parameterType, ref useSiteDiagnostics) :
Conversions.ClassifyImplicitConversionFromExpression(argument, parameterType, ref useSiteDiagnostics);
Debug.Assert((!conversion.Exists) || conversion.IsImplicit, "ClassifyImplicitConversion should only return implicit conversions");
return conversion;
}
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);
}
}
}
}
| 47.50675 | 239 | 0.567884 | [
"Apache-2.0"
] | iseneirik/roslyn-pt | src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolution.cs | 151,334 | C# |
using System.Drawing;
namespace BezierDrawControlTest
{
public class SquareGrid
{
public SquareGrid()
{
Width = 5;
Height = 5;
OffsetX = 0;
OffsetY = 0;
GridColor = ColorTranslator.FromHtml("#FFFFFF");
}
public int Width
{
get;
set;
}
public int Height
{
get;
set;
}
public int OffsetX
{
get;
set;
}
public int OffsetY
{
get;
set;
}
public Color GridColor
{
get;
set;
}
public int NormalizedOffsetX
{
get
{
return Normalize(OffsetX, Width);
}
}
public int NormalizedOffsetY
{
get
{
return Normalize(OffsetY, Height);
}
}
private int Normalize(int num, int basenum)
{
int val = num % basenum;
if (val < 0) val += basenum;
return val;
}
}
}
| 19.177419 | 60 | 0.380151 | [
"Apache-2.0"
] | KHCmaster/PPD | Win/BezierDrawControlTest/SquareGrid.cs | 1,191 | C# |
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Routing.Core.Query.Builtins
{
using System;
using System.Linq;
using Microsoft.Azure.Devices.Routing.Core.Query.Types;
using Microsoft.Azure.Devices.Routing.Core.Util;
/// <summary>
/// This adds support for variable sized argument lists. The object takes a list
/// of types, like Args, but repeats the last type indefinitely when matching.
/// For instance to encode the c# parameter list `func(int, string, params string[])`
/// you would define a VarArgs as `new VarArgs(typeof(int), typeof(string), typeof(string))`.
/// </summary>
public class VarArgs : IArgs
{
public VarArgs(params Type[] args)
{
this.Types = Preconditions.CheckNotNull(args);
}
public Type[] Types { get; }
public int Arity => this.Types.Length;
public bool Match(Type[] args, bool matchQueryValue)
{
int n = this.Types.Length - 1;
return args.Length >= n &&
args.Take(n).Zip(this.Types, (a, t) => a == t || (matchQueryValue && a == typeof(QueryValue))).Aggregate(true, (acc, item) => acc && item) &&
args.Skip(n).Select(a => a == this.Types[n] || (matchQueryValue && a == typeof(QueryValue))).Aggregate(true, (acc, item) => acc && item);
}
}
}
| 39.942857 | 160 | 0.610157 | [
"MIT"
] | CIPop/iotedge | edge-hub/src/Microsoft.Azure.Devices.Routing.Core/query/builtins/VarArgs.cs | 1,398 | C# |
using System.ComponentModel;
namespace Harmony.Models.Player
{
public class Resume : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public long Id { get; set; }
public string CurrentVolume { get; set; }
public double CurrentPosition { get; set; }
public bool IsPlayingAlbum { get; set; }
public bool PlayingAlbumId { get; set; }
public bool IsPlayingPlaylist { get; set; }
public bool PlayingPlaylistId { get; set; }
public bool IsPlayingDailyMix { get; set; }
public bool PlayingDailyMixId { get; set; }
public bool IsPlayingTrack { get; set; }
public bool PlayingTrackId { get; set; }
}
} | 29.64 | 65 | 0.646424 | [
"MIT"
] | EgoistDeveloper/Harmony | Harmony/Harmony/Models/Player/Entities/Resume.cs | 743 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using FileManagement.Common;
using Microsoft.AspNetCore.Identity;
namespace FileManagement.Entities
{
public class AppUser : IdentityUser
{
public AppUser()
{
this.Folder = Guid.NewGuid();
}
[Required]
[MinLength(GlobalConstants.MinNameLength)]
[MaxLength(GlobalConstants.MaxNameLength)]
public string FirstName { get; set; }
[Required]
[MinLength(GlobalConstants.MinNameLength)]
[MaxLength(GlobalConstants.MaxNameLength)]
public string LastName { get; set; }
public Guid Folder { get; set; }
}
}
| 23.517241 | 50 | 0.648094 | [
"MIT"
] | KaloyanSimitchiyski/aws-s3-management | FileManagement/Entities/AppUser.cs | 684 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("silkveil.net.ContentSources.File.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("silkveil.net.ContentSources.File.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("0328a11f-7edb-4e5f-995e-8e0ef6c91b7a")]
// 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")]
| 40.621622 | 85 | 0.733866 | [
"Unlicense",
"MIT"
] | peterbucher/silkveil | silkveil.net EBC Prototype by Golo/silkveil.net.ContentSources.File.Tests/Properties/AssemblyInfo.cs | 1,506 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
namespace Moq.AutoMock.Tests
{
[TestClass]
public class DescribeCreateInstance
{
[TestMethod]
public void It_creates_object_with_no_constructor()
{
var mocker = new AutoMocker();
var instance = mocker.CreateInstance<Empty>();
Assert.IsNotNull(instance);
}
[TestMethod]
public void It_creates_objects_for_ctor_parameters()
{
var mocker = new AutoMocker();
var instance = mocker.CreateInstance<OneConstructor>();
Assert.IsNotNull(instance.Empty);
}
[TestMethod]
public void It_creates_mock_objects_for_ctor_parameters()
{
var mocker = new AutoMocker();
var instance = mocker.CreateInstance<OneConstructor>();
Assert.IsNotNull(Mock.Get(instance.Empty));
}
[TestMethod]
public void It_creates_mock_objects_for_internal_ctor_parameters()
{
var mocker = new AutoMocker();
var instance = mocker.CreateInstance<WithServiceInternal>(true);
Assert.IsNotNull(Mock.Get(instance.Service));
}
[TestMethod]
public void It_creates_mock_objects_for_ctor_parameters_with_supplied_behavior()
{
var strictMocker = new AutoMocker(MockBehavior.Strict);
var instance = strictMocker.CreateInstance<OneConstructor>();
var mock = Mock.Get(instance.Empty);
Assert.IsNotNull(mock);
Assert.AreEqual(MockBehavior.Strict, mock.Behavior);
}
[TestMethod]
public void It_creates_mock_objects_for_ctor_sealed_parameters_when_instances_provided()
{
var mocker = new AutoMocker();
mocker.Use("Hello World");
WithSealedParams instance = mocker.CreateInstance<WithSealedParams>();
Assert.AreEqual("Hello World", instance.Sealed);
}
[TestMethod]
public void It_creates_mock_objects_for_ctor_array_parameters()
{
var mocker = new AutoMocker();
WithServiceArray instance = mocker.CreateInstance<WithServiceArray>();
IService2[] services = instance.Services;
Assert.IsNotNull(services);
Assert.IsFalse(services.Any());
}
[TestMethod]
public void It_creates_mock_objects_for_ctor_array_parameters_with_elements()
{
var mocker = new AutoMocker();
mocker.Use(new Mock<IService2>());
WithServiceArray instance = mocker.CreateInstance<WithServiceArray>();
IService2[] services = instance.Services;
Assert.IsNotNull(services);
Assert.IsTrue(services.Any());
}
[TestMethod]
public void It_throws_original_exception_caught_whilst_creating_object()
{
var mocker = new AutoMocker();
Assert.ThrowsException<ArgumentException>(mocker.CreateInstance<ConstructorThrows>);
}
[TestMethod]
public void It_throws_original_exception_caught_whilst_creating_object_with_original_stack_trace()
{
var mocker = new AutoMocker();
ArgumentException exception = Assert.ThrowsException<ArgumentException>(() => mocker.CreateInstance<ConstructorThrows>());
StringAssert.Contains(exception.StackTrace, typeof(ConstructorThrows).Name);
}
}
}
| 35.808081 | 134 | 0.635825 | [
"MIT"
] | blankenshipmq10k/Moq.AutoMocker | Moq.AutoMock.Tests/DescribeCreateInstance.cs | 3,547 | 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("h3t4")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("h3t4")]
[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("127f09d5-9fa8-4267-a2fc-41513a0f13a3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.324324 | 84 | 0.742216 | [
"Apache-2.0"
] | AskoVaananen/Csharp-ohjelmointi | h3t1/h3t1/h3t4/Properties/AssemblyInfo.cs | 1,384 | C# |
// This file is part of Dipol-3 Camera Manager.
// MIT License
//
// Copyright(c) 2018-2019 Ilia Kosenkov
//
// 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 NONINFINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Globalization;
using System.Windows.Data;
using DIPOL_UF.Properties;
namespace DIPOL_UF.Converters
{
internal class ValidationErrorsToStringValueConverter :IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ConverterImplementations.ValidationErrorsToStringConversion(value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException(
string.Format(Localization.General_OperationNotSupported,
$"{nameof(ValidationErrorsToStringValueConverter)}.{nameof(ConvertBack)}"));
}
}
| 45.954545 | 103 | 0.71365 | [
"MIT"
] | Ilia-Kosenkov/DIPOL-UF | src/DIPOL-UF/Converters/ValidationErrorsToStringValueConverter.cs | 2,024 | C# |
using System;
namespace Pulse.Sensor
{
/// <summary>
/// A sensor which forwards a signal to a given action.
/// </summary>
public sealed class SnsAct : ISensor
{
private readonly Action<ISignal> act;
private readonly Func<bool> isAlive;
private readonly Func<bool> isActive;
/// <summary>
/// A sensor which forwards a signal to a given action.
/// </summary>
public SnsAct(Action<ISignal> act) : this(act, () => true, () => true)
{ }
/// <summary>
/// A sensor which forwards a signal to a given action.
/// </summary>
public SnsAct(Action<ISignal> act, Func<bool> isAlive) : this(act, isAlive, isAlive)
{ }
/// <summary>
/// A sensor which forwards a signal to a given action.
/// </summary>
public SnsAct(Action<ISignal> act, Func<bool> isAlive, Func<bool> isActive)
{
this.act = act;
this.isAlive = isAlive;
this.isActive = isActive;
}
public bool IsActive()
{
return this.isActive();
}
public bool IsDead()
{
return !this.isAlive();
}
public void Trigger(ISignal signal)
{
this.act(signal);
}
}
}
| 25.596154 | 92 | 0.525169 | [
"MIT"
] | g00fy88/Poof | src/Pulse/Sensor/SnsAct.cs | 1,333 | C# |
//-----------------------------------------------------------------------
// <copyright file="TestKit.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.Configuration;
namespace Akka.TestKit.Xunit
{
/// <summary>
/// TestKit for xUnit.
/// </summary>
public class TestKit : TestKitBase , IDisposable
{
private static readonly XunitAssertions _assertions=new XunitAssertions();
private bool _isDisposed; //Automatically initialized to false;
/// <summary>
/// Create a new instance of the <see cref="TestKit"/> for xUnit class.
/// If no <paramref name="system"/> is passed in, a new system
/// with <see cref="DefaultConfig"/> will be created.
/// </summary>
/// <param name="system">Optional: The actor system.</param>
public TestKit(ActorSystem system = null)
: base(_assertions, system)
{
//Intentionally left blank
}
/// <summary>
/// Create a new instance of the <see cref="TestKit"/> for xUnit class.
/// A new system with the specified configuration will be created.
/// </summary>
/// <param name="config">The configuration to use for the system.</param>
/// <param name="actorSystemName">Optional: the name of the system. Default: "test"</param>
public TestKit(Config config, string actorSystemName=null)
: base(_assertions, config, actorSystemName)
{
//Intentionally left blank
}
/// <summary>
/// Create a new instance of the <see cref="TestKit"/> for xUnit class.
/// A new system with the specified configuration will be created.
/// </summary>
/// <param name="config">The configuration to use for the system.</param>
public TestKit(string config): base(_assertions, ConfigurationFactory.ParseString(config))
{
//Intentionally left blank
}
/// <summary>
/// TBD
/// </summary>
public new static Config DefaultConfig { get { return TestKitBase.DefaultConfig; } }
/// <summary>
/// TBD
/// </summary>
public new static Config FullDebugConfig { get { return TestKitBase.FullDebugConfig; } }
/// <summary>
/// TBD
/// </summary>
protected static XunitAssertions Assertions { get { return _assertions; } }
/// <summary>
/// This method is called when a test ends.
/// <remarks>If you override this, make sure you either call
/// base.AfterTest() or <see cref="TestKitBase.Shutdown(System.Nullable{System.TimeSpan},bool)">TestKitBase.Shutdown</see> to shut down
/// the system. Otherwise you'll leak memory.
/// </remarks>
/// </summary>
protected virtual void AfterAll()
{
Shutdown();
}
// Dispose ------------------------------------------------------------
//Destructor:
//~TestKit()
//{
// // Finalizer calls Dispose(false)
// Dispose(false);
//}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
Dispose(true);
//Take this object off the finalization queue and prevent finalization code for this object
//from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
/// <param name="disposing">if set to <c>true</c> the method has been called directly or indirectly by a
/// user's code. Managed and unmanaged resources will be disposed.<br />
/// if set to <c>false</c> the method has been called by the runtime from inside the finalizer and only
/// unmanaged resources can be disposed.</param>
protected virtual void Dispose(bool disposing)
{
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
try
{
//Make sure Dispose does not get called more than once, by checking the disposed field
if(!_isDisposed)
{
if(disposing)
{
AfterAll();
}
}
_isDisposed = true;
}
finally
{
// base.dispose(disposing);
}
}
}
} | 38.360902 | 143 | 0.551352 | [
"Apache-2.0"
] | uQr/akka.net | src/contrib/testkits/Akka.TestKit.Xunit/TestKit.cs | 5,104 | C# |
using Khooversoft.Toolbox.Configuration;
using Khooversoft.Toolbox.Standard;
namespace MessageHub.NameServer
{
public class BlobRepositoryDetails
{
public string ContainerName { get; set; } = null!;
public string Connection { get; set; } = null!;
public void Verify()
{
ContainerName!.Verify(nameof(ContainerName)).IsNotEmpty();
Connection!.Verify(nameof(Connection)).IsNotEmpty();
}
}
}
| 24.631579 | 70 | 0.643162 | [
"MIT"
] | khooversoft/Toolbox.Core | Src/Dev/MessageNet/MessageNet.NameServer/Application/BlobRepository.cs | 470 | 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 waf-regional-2016-11-28.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.WAFRegional.Model
{
/// <summary>
/// Container for the parameters to the CreateIPSet operation.
/// Creates an <a>IPSet</a>, which you use to specify which web requests that you want
/// to allow or block based on the IP addresses that the requests originate from. For
/// example, if you're receiving a lot of requests from one or more individual IP addresses
/// or one or more ranges of IP addresses and you want to block the requests, you can
/// create an <code>IPSet</code> that contains those IP addresses and then configure AWS
/// WAF to block the requests.
///
///
/// <para>
/// To create and configure an <code>IPSet</code>, perform the following steps:
/// </para>
/// <ol> <li>
/// <para>
/// Use <a>GetChangeToken</a> to get the change token that you provide in the <code>ChangeToken</code>
/// parameter of a <code>CreateIPSet</code> request.
/// </para>
/// </li> <li>
/// <para>
/// Submit a <code>CreateIPSet</code> request.
/// </para>
/// </li> <li>
/// <para>
/// Use <code>GetChangeToken</code> to get the change token that you provide in the <code>ChangeToken</code>
/// parameter of an <a>UpdateIPSet</a> request.
/// </para>
/// </li> <li>
/// <para>
/// Submit an <code>UpdateIPSet</code> request to specify the IP addresses that you want
/// AWS WAF to watch for.
/// </para>
/// </li> </ol>
/// <para>
/// For more information about how to use the AWS WAF API to allow or block HTTP requests,
/// see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/">AWS WAF Developer
/// Guide</a>.
/// </para>
/// </summary>
public partial class CreateIPSetRequest : AmazonWAFRegionalRequest
{
private string _changeToken;
private string _name;
/// <summary>
/// Gets and sets the property ChangeToken.
/// <para>
/// The value returned by the most recent call to <a>GetChangeToken</a>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1)]
public string ChangeToken
{
get { return this._changeToken; }
set { this._changeToken = value; }
}
// Check to see if ChangeToken property is set
internal bool IsSetChangeToken()
{
return this._changeToken != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// A friendly name or description of the <a>IPSet</a>. You can't change <code>Name</code>
/// after you create the <code>IPSet</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=128)]
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.684211 | 112 | 0.610521 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/WAFRegional/Generated/Model/CreateIPSetRequest.cs | 3,954 | C# |
using UnityEngine;
namespace Game
{
public class TouchMovement : ScreenMovement
{
protected override bool TryGetInput(out Vector2 input)
{
if (Input.touchCount > 0)
{
input = Input.touches[0].position;
return true;
}
input = default;
return false;
}
}
}
| 19.25 | 62 | 0.496104 | [
"CC0-1.0"
] | DesDeaDer/GameLikeAsArchHero | Assets/Scripts/MovementInputs/TouchMovement.cs | 387 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PostCalendarWindows.ViewModel;
namespace PostCalendarWindows.Setting
{
/// <summary>
/// UserControlSettingItem.xaml 的交互逻辑
/// </summary>
public partial class UserControlSettingItem : UserControl
{
public ItemMenu _item;
public UserControlSettingItem(ItemMenu item)
{
InitializeComponent();
_item = item;
this.DataContext = _item;
}
}
}
| 24.117647 | 61 | 0.715854 | [
"MIT"
] | jackfiled/PostCalendarWindows | PostCalendarWindows/Setting/UserControlSettingItem.xaml.cs | 832 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.Management.Storage.Models
{
public partial class ChangeFeed : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Enabled != null)
{
writer.WritePropertyName("enabled");
writer.WriteBooleanValue(Enabled.Value);
}
writer.WriteEndObject();
}
internal static ChangeFeed DeserializeChangeFeed(JsonElement element)
{
bool? enabled = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("enabled"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
enabled = property.Value.GetBoolean();
continue;
}
}
return new ChangeFeed(enabled);
}
}
}
| 27.311111 | 77 | 0.531326 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/testcommon/Azure.Management.Storage.2019_06/src/Generated/Models/ChangeFeed.Serialization.cs | 1,229 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Razor.Internal;
using Microsoft.AspNetCore.Razor.Language;
namespace RazorPageExecutionInstrumentationWebSite
{
public class TestRazorProject : FileProviderRazorProject
{
public TestRazorProject(IRazorViewEngineFileProviderAccessor fileProviderAccessor, IHostingEnvironment hostingEnvironment)
: base(fileProviderAccessor, hostingEnvironment)
{
}
public override RazorProjectItem GetItem(string path)
{
var item = (FileProviderRazorProjectItem)base.GetItem(path);
return new TestRazorProjectItem(item);
}
private class TestRazorProjectItem : FileProviderRazorProjectItem
{
public TestRazorProjectItem(FileProviderRazorProjectItem projectItem)
: base(projectItem.FileInfo, projectItem.BasePath, projectItem.FilePath, projectItem.RelativePhysicalPath)
{
}
public override Stream Read()
{
// Normalize line endings to '\r\n' (CRLF). This removes core.autocrlf, core.eol, core.safecrlf, and
// .gitattributes from the equation and treats "\r\n" and "\n" as equivalent. Does not handle
// some line endings like "\r" but otherwise ensures checksums and line mappings are consistent.
string text;
using (var streamReader = new StreamReader(base.Read()))
{
text = streamReader.ReadToEnd().Replace("\r", "").Replace("\n", "\r\n");
}
var bytes = Encoding.UTF8.GetBytes(text);
return new MemoryStream(bytes);
}
}
}
} | 40.708333 | 130 | 0.646366 | [
"Apache-2.0"
] | aneequrrehman/Mvc | test/WebSites/RazorPageExecutionInstrumentationWebSite/TestRazorCompilationService.cs | 1,954 | 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 swf-2012-01-25.normal.json service model.
*/
using Amazon.Runtime.Internal;
namespace Amazon.SimpleWorkflow.Internal
{
/// <summary>
/// Service metadata for Amazon SimpleWorkflow service
/// </summary>
public partial class AmazonSimpleWorkflowMetadata : IServiceMetadata
{
/// <summary>
/// Gets the value of the Service Id.
/// </summary>
public string ServiceId
{
get
{
return "SWF";
}
}
/// <summary>
/// Gets the dictionary that gives mapping of renamed operations
/// </summary>
public System.Collections.Generic.IDictionary<string, string> OperationNameMapping
{
get
{
return new System.Collections.Generic.Dictionary<string, string>(0)
{
};
}
}
}
} | 28.563636 | 101 | 0.612349 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/SimpleWorkflow/Generated/Internal/AmazonSimpleWorkflowMetadata.cs | 1,571 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DEMO_WebAPI_NET
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| 23.6 | 62 | 0.583051 | [
"MIT"
] | StefanIordache/Laborator-DAW | solutions/DEMO-WebAPI-NET/App_Start/WebApiConfig.cs | 592 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
using System.Runtime.InteropServices;
namespace SharpVk.Khronos
{
/// <summary>
/// Structure describing an available display device.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DisplayProperties
{
/// <summary>
/// A handle that is used to refer to the display described here. This
/// handle will be valid for the lifetime of the Vulkan instance.
/// </summary>
public Display Display
{
get;
set;
}
/// <summary>
/// A string containing the name of the display. Generally, this will
/// be the name provided by the display's EDID. It can be Null if no
/// suitable name is available.
/// </summary>
public string DisplayName
{
get;
set;
}
/// <summary>
/// physicalDimensions describes the physical width and height of the
/// visible portion of the display, in millimeters.
/// </summary>
public Extent2D PhysicalDimensions
{
get;
set;
}
/// <summary>
/// physicalResolution describes the physical, native, or preferred
/// resolution of the display.
/// </summary>
public Extent2D PhysicalResolution
{
get;
set;
}
/// <summary>
/// </summary>
public SurfaceTransformFlags? SupportedTransforms
{
get;
set;
}
/// <summary>
/// </summary>
public bool PlaneReorderPossible
{
get;
set;
}
/// <summary>
/// </summary>
public bool PersistentContent
{
get;
set;
}
/// <summary>
/// </summary>
/// <param name="pointer">
/// </param>
internal static unsafe DisplayProperties MarshalFrom(SharpVk.Interop.Khronos.DisplayProperties* pointer)
{
DisplayProperties result = default;
result.Display = new Display(default, pointer->Display);
result.DisplayName = Interop.HeapUtil.MarshalStringFrom(pointer->DisplayName);
result.PhysicalDimensions = pointer->PhysicalDimensions;
result.PhysicalResolution = pointer->PhysicalResolution;
result.SupportedTransforms = pointer->SupportedTransforms;
result.PlaneReorderPossible = pointer->PlaneReorderPossible;
result.PersistentContent = pointer->PersistentContent;
return result;
}
}
}
| 33.567797 | 112 | 0.606665 | [
"MIT"
] | xuri02/SharpVk | src/SharpVk/Khronos/DisplayProperties.gen.cs | 3,961 | C# |
using System;
using System.Collections;
using System.ComponentModel;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using UWPApp = Windows.UI.Xaml.Application;
using UWPDataTemplate = Windows.UI.Xaml.DataTemplate;
using WScrollBarVisibility = Windows.UI.Xaml.Controls.ScrollBarVisibility;
using WScrollMode = Windows.UI.Xaml.Controls.ScrollMode;
using WSnapPointsAlignment = Windows.UI.Xaml.Controls.Primitives.SnapPointsAlignment;
using WSnapPointsType = Windows.UI.Xaml.Controls.SnapPointsType;
namespace Xamarin.Forms.Platform.UWP
{
public class CarouselViewRenderer : ItemsViewRenderer<CarouselView>
{
ScrollViewer _scrollViewer;
int _gotoPosition = -1;
bool _noNeedForScroll;
public CarouselViewRenderer()
{
CarouselView.VerifyCarouselViewFlagEnabled(nameof(CarouselView));
}
protected CarouselView Carousel => Element;
protected override IItemsLayout Layout => Carousel?.ItemsLayout;
LinearItemsLayout CarouselItemsLayout => Carousel?.ItemsLayout;
UWPDataTemplate CarouselItemsViewTemplate => (UWPDataTemplate)UWPApp.Current.Resources["CarouselItemsViewDefaultTemplate"];
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs changedProperty)
{
base.OnElementPropertyChanged(sender, changedProperty);
if (changedProperty.IsOneOf(CarouselView.ItemsSourceProperty, LinearItemsLayout.ItemSpacingProperty))
UpdateItemsSource();
else if (changedProperty.Is(CarouselView.ItemTemplateProperty))
UpdateItemTemplate();
else if (changedProperty.Is(CarouselView.PeekAreaInsetsProperty))
UpdatePeekAreaInsets();
else if (changedProperty.Is(CarouselView.IsSwipeEnabledProperty))
UpdateIsSwipeEnabled();
else if (changedProperty.Is(CarouselView.IsBounceEnabledProperty))
UpdateIsBounceEnabled();
else if (changedProperty.Is(CarouselView.PositionProperty))
UpdateFromPosition();
else if (changedProperty.Is(CarouselView.CurrentItemProperty))
UpdateFromCurrentItem();
}
protected override void HandleLayoutPropertyChanged(PropertyChangedEventArgs property)
{
if (property.Is(LinearItemsLayout.ItemSpacingProperty))
UpdateItemSpacing();
else if (property.Is(ItemsLayout.SnapPointsTypeProperty))
UpdateSnapPointsType();
else if (property.Is(ItemsLayout.SnapPointsAlignmentProperty))
UpdateSnapPointsAlignment();
}
protected override void SetUpNewElement(ItemsView newElement)
{
base.SetUpNewElement(newElement);
if (newElement != null)
{
ListViewBase.SizeChanged += OnListSizeChanged;
}
}
protected override void TearDownOldElement(ItemsView oldElement)
{
base.TearDownOldElement(oldElement);
if (oldElement == null)
return;
if (ListViewBase != null)
{
ListViewBase.SizeChanged -= OnListSizeChanged;
if (CollectionViewSource?.Source is ObservableItemTemplateCollection observableItemsSource)
observableItemsSource.CollectionChanged -= CollectionItemsSourceChanged;
}
if (_scrollViewer != null)
{
_scrollViewer.ViewChanging -= OnScrollViewChanging;
_scrollViewer.ViewChanged -= OnScrollViewChanged;
}
}
protected override void UpdateItemsSource()
{
var itemsSource = Element.ItemsSource;
if (itemsSource == null)
return;
var itemTemplate = Element.ItemTemplate;
if (itemTemplate == null)
return;
base.UpdateItemsSource();
}
protected override CollectionViewSource CreateCollectionViewSource()
{
var collectionViewSource = TemplatedItemSourceFactory.Create(Element.ItemsSource, Element.ItemTemplate, Element,
GetItemHeight(), GetItemWidth(), GetItemSpacing());
if (collectionViewSource is ObservableItemTemplateCollection observableItemsSource)
observableItemsSource.CollectionChanged += CollectionItemsSourceChanged;
return new CollectionViewSource
{
Source = collectionViewSource,
IsSourceGrouped = false
};
}
protected override ListViewBase SelectListViewBase()
{
ListViewBase listView = CreateCarouselListLayout(CarouselItemsLayout.Orientation);
FindScrollViewer(listView);
return listView;
}
protected override void UpdateItemTemplate()
{
if (Element == null || ListViewBase == null)
return;
ListViewBase.ItemTemplate = CarouselItemsViewTemplate;
}
void CollectionItemsSourceChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
var carouselPosition = Carousel.Position;
var currentItemPosition = FindCarouselItemIndex(Carousel.CurrentItem);
var count = (sender as IList).Count;
bool removingCurrentElement = currentItemPosition == -1;
bool removingLastElement = e.OldStartingIndex == count;
bool removingFirstElement = e.OldStartingIndex == 0;
bool removingCurrentElementButNotFirst = removingCurrentElement && removingLastElement && Carousel.Position > 0;
if (removingCurrentElementButNotFirst)
{
carouselPosition = Carousel.Position - 1;
}
else if (removingFirstElement && !removingCurrentElement)
{
carouselPosition = currentItemPosition;
_noNeedForScroll = true;
}
//If we are adding a new item make sure to maintain the CurrentItemPosition
else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add
&& currentItemPosition != -1)
{
carouselPosition = currentItemPosition;
}
_gotoPosition = -1;
SetCurrentItem(carouselPosition);
UpdatePosition(carouselPosition);
}
void OnListSizeChanged(object sender, Windows.UI.Xaml.SizeChangedEventArgs e)
{
UpdateItemsSource();
UpdateSnapPointsType();
UpdateSnapPointsAlignment();
UpdateInitialPosition();
}
void OnScrollViewChanging(object sender, ScrollViewerViewChangingEventArgs e)
{
Carousel.SetIsDragging(true);
Carousel.IsScrolling = true;
}
void OnScrollViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
Carousel.SetIsDragging(e.IsIntermediate);
Carousel.IsScrolling = e.IsIntermediate;
UpdatePositionFromScroll();
HandleScroll(_scrollViewer);
}
void UpdatePeekAreaInsets()
{
ListViewBase.Padding = new Windows.UI.Xaml.Thickness(Carousel.PeekAreaInsets.Left, Carousel.PeekAreaInsets.Top, Carousel.PeekAreaInsets.Right, Carousel.PeekAreaInsets.Bottom);
UpdateItemsSource();
}
void UpdateIsSwipeEnabled()
{
if (Carousel == null)
return;
ListViewBase.IsSwipeEnabled = Carousel.IsSwipeEnabled;
switch (CarouselItemsLayout.Orientation)
{
case ItemsLayoutOrientation.Horizontal:
ScrollViewer.SetHorizontalScrollMode(ListViewBase, Carousel.IsSwipeEnabled ? WScrollMode.Auto : WScrollMode.Disabled);
ScrollViewer.SetHorizontalScrollBarVisibility(ListViewBase, Carousel.IsSwipeEnabled ? WScrollBarVisibility.Auto : WScrollBarVisibility.Disabled);
break;
case ItemsLayoutOrientation.Vertical:
ScrollViewer.SetVerticalScrollMode(ListViewBase, Carousel.IsSwipeEnabled ? WScrollMode.Auto : WScrollMode.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(ListViewBase, Carousel.IsSwipeEnabled ? WScrollBarVisibility.Auto : WScrollBarVisibility.Disabled);
break;
}
}
void UpdateIsBounceEnabled()
{
if (_scrollViewer != null)
_scrollViewer.IsScrollInertiaEnabled = Carousel.IsBounceEnabled;
}
void UpdateItemSpacing()
{
UpdateItemsSource();
var itemSpacing = CarouselItemsLayout.ItemSpacing;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal)
_scrollViewer.Padding = new Windows.UI.Xaml.Thickness(0, 0, itemSpacing, 0);
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Vertical)
_scrollViewer.Padding = new Windows.UI.Xaml.Thickness(0, 0, 0, itemSpacing);
}
void UpdateSnapPointsType()
{
if (_scrollViewer == null)
return;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal)
_scrollViewer.HorizontalSnapPointsType = GetWindowsSnapPointsType(CarouselItemsLayout.SnapPointsType);
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Vertical)
_scrollViewer.VerticalSnapPointsType = GetWindowsSnapPointsType(CarouselItemsLayout.SnapPointsType);
}
void UpdateSnapPointsAlignment()
{
if (_scrollViewer == null)
return;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal)
_scrollViewer.HorizontalSnapPointsAlignment = GetWindowsSnapPointsAlignment(CarouselItemsLayout.SnapPointsAlignment);
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Vertical)
_scrollViewer.VerticalSnapPointsAlignment = GetWindowsSnapPointsAlignment(CarouselItemsLayout.SnapPointsAlignment);
}
void UpdateInitialPosition()
{
int position;
if (Carousel.CurrentItem != null)
{
position = FindCarouselItemIndex(Carousel.CurrentItem);
Carousel.Position = position;
}
else
{
position = Carousel.Position;
}
SetCurrentItem(position);
UpdatePosition(position);
//if (position > 0)
// UpdateFromPosition();
}
void UpdatePositionFromScroll()
{
if (_scrollViewer == null)
return;
int itemCount = CollectionViewSource.View.Count;
if (itemCount == 0)
return;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal && _scrollViewer.HorizontalOffset == _previousHorizontalOffset)
return;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Vertical && _scrollViewer.VerticalOffset == _previousVerticalOffset)
return;
bool goingNext = CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal ?
_scrollViewer.HorizontalOffset > _previousHorizontalOffset :
_scrollViewer.VerticalOffset > _previousVerticalOffset;
var position = ListViewBase.GetVisibleIndexes(CarouselItemsLayout.Orientation, goingNext).centerItemIndex;
if (position == -1)
return;
UpdatePosition(position);
}
void UpdateFromCurrentItem()
{
var currentItemPosition = FindCarouselItemIndex(Carousel.CurrentItem);
var carouselPosition = Carousel.Position;
if (_gotoPosition == -1 && currentItemPosition != carouselPosition)
{
_gotoPosition = currentItemPosition;
Carousel.ScrollTo(currentItemPosition, position: ScrollToPosition.Center, animate: Carousel.AnimateCurrentItemChanges);
}
}
void UpdateFromPosition()
{
var itemCount = CollectionViewSource.View.Count;
var carouselPosition = Carousel.Position;
if (carouselPosition >= itemCount || carouselPosition < 0)
throw new IndexOutOfRangeException($"Can't set CarouselView to position {carouselPosition}. ItemsSource has {itemCount} items.");
if (carouselPosition == _gotoPosition)
_gotoPosition = -1;
if (_noNeedForScroll)
{
_noNeedForScroll = false;
return;
}
if (_gotoPosition == -1 && !Carousel.IsDragging && !Carousel.IsScrolling)
{
_gotoPosition = carouselPosition;
Carousel.ScrollTo(carouselPosition, position: ScrollToPosition.Center, animate: Carousel.AnimatePositionChanges);
}
SetCurrentItem(carouselPosition);
}
void UpdatePosition(int position)
{
if (!ValidatePosition(position))
return;
var carouselPosition = Carousel.Position;
//we arrived center
if (position == _gotoPosition)
_gotoPosition = -1;
if (_gotoPosition == -1 && carouselPosition != position)
Carousel.SetValueFromRenderer(CarouselView.PositionProperty, position);
}
void SetCurrentItem(int carouselPosition)
{
if (ListViewBase.Items.Count == 0)
return;
if (!ValidatePosition(carouselPosition))
return;
if (!(ListViewBase.Items[carouselPosition] is ItemTemplateContext itemTemplateContext))
throw new InvalidOperationException("Visible item not found");
var item = itemTemplateContext.Item;
Carousel.SetValueFromRenderer(CarouselView.CurrentItemProperty, item);
}
bool ValidatePosition(int position)
{
if (ListViewBase.Items.Count == 0)
return false;
if (position < 0 || position >= ListViewBase.Items.Count)
return false;
return true;
}
ListViewBase CreateCarouselListLayout(ItemsLayoutOrientation layoutOrientation)
{
Windows.UI.Xaml.Controls.ListView listView;
if (layoutOrientation == ItemsLayoutOrientation.Horizontal)
{
listView = new FormsListView()
{
Style = (Windows.UI.Xaml.Style)UWPApp.Current.Resources["HorizontalCarouselListStyle"],
ItemsPanel = (ItemsPanelTemplate)UWPApp.Current.Resources["HorizontalListItemsPanel"]
};
ScrollViewer.SetHorizontalScrollBarVisibility(listView, WScrollBarVisibility.Auto);
ScrollViewer.SetVerticalScrollBarVisibility(listView, WScrollBarVisibility.Disabled);
}
else
{
listView = new FormsListView()
{
Style = (Windows.UI.Xaml.Style)UWPApp.Current.Resources["VerticalCarouselListStyle"]
};
ScrollViewer.SetHorizontalScrollBarVisibility(listView, WScrollBarVisibility.Disabled);
ScrollViewer.SetVerticalScrollBarVisibility(listView, WScrollBarVisibility.Auto);
}
listView.Padding = new Windows.UI.Xaml.Thickness(Carousel.PeekAreaInsets.Left, Carousel.PeekAreaInsets.Top, Carousel.PeekAreaInsets.Right, Carousel.PeekAreaInsets.Bottom);
return listView;
}
double GetItemWidth()
{
var itemWidth = ActualWidth;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal)
{
itemWidth = (ActualWidth - Carousel.PeekAreaInsets.Left - Carousel.PeekAreaInsets.Right);
}
return Math.Max(itemWidth, 0);
}
double GetItemHeight()
{
var itemHeight = ActualHeight;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Vertical)
{
itemHeight = (ActualHeight - Carousel.PeekAreaInsets.Top - Carousel.PeekAreaInsets.Bottom);
}
return Math.Max(itemHeight, 0);
}
Thickness GetItemSpacing()
{
var itemSpacing = CarouselItemsLayout.ItemSpacing;
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Horizontal)
return new Thickness(itemSpacing, 0, 0, 0);
if (CarouselItemsLayout.Orientation == ItemsLayoutOrientation.Vertical)
return new Thickness(0, itemSpacing, 0, 0);
return new Thickness(0);
}
int FindCarouselItemIndex(object item)
{
for (int n = 0; n < CollectionViewSource?.View.Count; n++)
{
if (CollectionViewSource.View[n] is ItemTemplateContext pair)
{
if (pair.Item == item)
{
return n;
}
}
}
return -1;
}
WSnapPointsType GetWindowsSnapPointsType(SnapPointsType snapPointsType)
{
switch (snapPointsType)
{
case SnapPointsType.Mandatory:
return WSnapPointsType.Mandatory;
case SnapPointsType.MandatorySingle:
return WSnapPointsType.MandatorySingle;
case SnapPointsType.None:
return WSnapPointsType.None;
}
return WSnapPointsType.None;
}
WSnapPointsAlignment GetWindowsSnapPointsAlignment(SnapPointsAlignment snapPointsAlignment)
{
switch (snapPointsAlignment)
{
case SnapPointsAlignment.Center:
return WSnapPointsAlignment.Center;
case SnapPointsAlignment.End:
return WSnapPointsAlignment.Far;
case SnapPointsAlignment.Start:
return WSnapPointsAlignment.Near;
}
return WSnapPointsAlignment.Center;
}
protected override void FindScrollViewer(ListViewBase listView)
{
var scrollViewer = listView.GetFirstDescendant<ScrollViewer>();
if (scrollViewer != null)
{
_scrollViewer = scrollViewer;
// TODO: jsuarezruiz This breaks the ScrollTo override. Review it.
_scrollViewer.ViewChanging += OnScrollViewChanging;
_scrollViewer.ViewChanged += OnScrollViewChanged;
return;
}
void ListViewLoaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var lv = (ListViewBase)sender;
lv.Loaded -= ListViewLoaded;
FindScrollViewer(listView);
}
listView.Loaded += ListViewLoaded;
}
}
}
| 30.00947 | 178 | 0.757715 | [
"MIT"
] | in-situ-inc/Xamarin.Forms | Xamarin.Forms.Platform.UAP/CollectionView/CarouselViewRenderer.cs | 15,847 | C# |
namespace Microsoft.Maui.Controls
{
public partial class Slider : ISlider
{
IImageSource ISlider.ThumbImageSource => ThumbImageSource;
void ISlider.DragCompleted()
{
(this as ISliderController).SendDragCompleted();
}
void ISlider.DragStarted()
{
(this as ISliderController).SendDragStarted();
}
}
}
| 18 | 60 | 0.728395 | [
"MIT"
] | 3DSX/maui | src/Controls/src/Core/HandlerImpl/Slider.Impl.cs | 324 | C# |
using System;
namespace AntColony
{
#if WINDOWS || XBOX
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
using (Game1 game = new Game1())
{
game.Run();
}
}
}
#endif
}
| 17.5 | 54 | 0.431169 | [
"MIT"
] | wahabjawed/Ant-Colony-Simulation | AntColony/AntColony/AntColony/Program.cs | 385 | 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 iotanalytics-2017-11-27.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.IoTAnalytics.Model
{
/// <summary>
/// The command caused an internal limit to be exceeded.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class LimitExceededException : AmazonIoTAnalyticsException
{
/// <summary>
/// Constructs a new LimitExceededException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public LimitExceededException(string message)
: base(message) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public LimitExceededException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="innerException"></param>
public LimitExceededException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public LimitExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public LimitExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the LimitExceededException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected LimitExceededException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 46.895161 | 178 | 0.678934 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/IoTAnalytics/Generated/Model/LimitExceededException.cs | 5,815 | C# |
using adminlte.Helpers;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Rotativa;
using Rotativa.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace adminlte.Controllers
{
public class ExamplesController : Controller
{
private IPDFGeneratorHelper _iPDFGeneratorHelper;
public ExamplesController()
{
_iPDFGeneratorHelper = new PDFGeneratorHelper();
}
public ActionResult GeneratePDF()
{
return _iPDFGeneratorHelper.IsPartialView(true)
.SetViewName("_InvoicePDF")
.SetCopiesName(new List<string>() { "Original", "UserCopy-1", "UserCopy-2" })
.SetFileName("TestLabe.pdf")
.SetControlerContext(ControllerContext)
.SetContentDisposition(true)
.GeneratePDFByteArray()
.GetCombinedResult();
}
public ActionResult Index()
{
return View();
}
public ActionResult Page404()
{
return View();
}
public ActionResult Page500()
{
return View();
}
public ActionResult Blank()
{
return View();
}
public ActionResult InvoicePrint()
{
return View();
}
public ActionResult Invoice()
{
return View();
}
public ActionResult Lockscreen()
{
return View();
}
public ActionResult Login()
{
return View();
}
public ActionResult Pace()
{
return View();
}
public ActionResult PageProfile()
{
return View();
}
public ActionResult Register()
{
return View();
}
}
} | 23.153846 | 116 | 0.486948 | [
"MIT"
] | Raghavendrssnk/PDFMerger | adminlte/Controllers/ExamplesController.cs | 2,109 | C# |
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes;
using Kingmaker.Blueprints.Classes.Prerequisites;
using Kingmaker.Designers.Mechanics.Facts;
using TabletopTweaks.Config;
using TabletopTweaks.Extensions;
using TabletopTweaks.Utilities;
namespace TabletopTweaks.NewContent.Feats {
static class CelestialServant {
public static void AddCelestialServant() {
var TemplateCelestial = Resources.GetModBlueprint<BlueprintFeature>("TemplateCelestial");
var AasimarRace = Resources.GetBlueprint<BlueprintRace>("b7f02ba92b363064fb873963bec275ee");
var CelestialServant = Helpers.CreateBlueprint<BlueprintFeature>("CelestialServant", bp => {
bp.SetName("Celestial Servant");
bp.SetDescription("Your animal companion, familiar, or mount gains the celestial template and becomes a magical beast, " +
"though you may still treat it as an animal when using Handle Animal, wild empathy, or any other spells or class abilities " +
"that specifically affect animals.\n" +
"Creature gains spell resistance equal to its level + 5. It also gains:\n" +
"1 — 4 HD: resistance 5 to cold, acid, and electricity.\n" +
"5 — 10 HD: resistance 10 to cold, acid, and electricity, DR 5/evil\n" +
"11+ HD: resistance 15 to cold, acid, and electricity, DR 10/evil\n" +
"Smite Evil (Su): Once per day, the celestial creature may smite a evil-aligned creature. As a swift action, " +
"the creature chooses one target within sight to smite. If this target is evil, the creature adds its Charisma bonus (if any) to " +
"attack rolls and gains a damage bonus equal to its HD against that foe. This effect persists until the target is dead or the creature rests.");
bp.Ranks = 1;
bp.ReapplyOnLevelUp = true;
bp.IsClassFeature = true;
bp.Groups = new FeatureGroup[] { FeatureGroup.Feat };
bp.AddComponent<AddFeatureToPet>(c => {
c.m_Feature = TemplateCelestial.ToReference<BlueprintFeatureReference>();
});
bp.AddPrerequisiteFeature(AasimarRace);
bp.AddPrerequisite<PrerequisitePet>();
});
if (ModSettings.AddedContent.Feats.IsDisabled("CelestialServant")) { return; }
FeatTools.AddAsFeat(CelestialServant);
}
}
}
| 60.666667 | 164 | 0.642465 | [
"MIT"
] | 1onepower/WrathMods-TabletopTweaks | TabletopTweaks/NewContent/Feats/CelestialServant.cs | 2,554 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Web.UI.WebControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.WebPortal;
using WebsitePanel.Portal.UserControls;
namespace WebsitePanel.Portal
{
public partial class OrganizationMenu : OrganizationMenuControl
{
private const string PID_SPACE_EXCHANGE_SERVER = "SpaceExchangeServer";
protected void Page_Load(object sender, EventArgs e)
{
ShortMenu = false;
ShowImg = false;
// organization
bool orgVisible = (PanelRequest.ItemID > 0 && Request[DefaultPage.PAGE_ID_PARAM].Equals(PID_SPACE_EXCHANGE_SERVER, StringComparison.InvariantCultureIgnoreCase));
orgMenu.Visible = orgVisible;
if (orgVisible)
{
MenuItem rootItem = new MenuItem(locMenuTitle.Text);
rootItem.Selectable = false;
menu.Items.Add(rootItem);
//Add "Organization Home" menu item
MenuItem item = new MenuItem(
GetLocalizedString("Text.OrganizationHome"),
"",
"",
PortalUtils.EditUrl("ItemID", PanelRequest.ItemID.ToString(), "organization_home", "SpaceID=" + PanelSecurity.PackageId));
rootItem.ChildItems.Add(item);
BindMenu(rootItem.ChildItems);
}
}
}
}
| 40.987654 | 174 | 0.667169 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/OrganizationMenu.ascx.cs | 3,320 | C# |
namespace Renci.SshNetCore.Messages.Connection
{
/// <summary>
/// Represents "x11-req" type channel request information
/// </summary>
internal class X11ForwardingRequestInfo : RequestInfo
{
private byte[] _authenticationProtocol;
/// <summary>
/// Channel request name
/// </summary>
public const string Name = "x11-req";
/// <summary>
/// Gets the name of the request.
/// </summary>
/// <value>
/// The name of the request.
/// </value>
public override string RequestName
{
get { return Name; }
}
/// <summary>
/// Gets or sets a value indicating whether it is a single connection.
/// </summary>
/// <value>
/// <c>true</c> if it is a single connection; otherwise, <c>false</c>.
/// </value>
public bool IsSingleConnection { get; set; }
/// <summary>
/// Gets or sets the authentication protocol.
/// </summary>
/// <value>
/// The authentication protocol.
/// </value>
public string AuthenticationProtocol
{
get { return Ascii.GetString(_authenticationProtocol, 0, _authenticationProtocol.Length); }
private set { _authenticationProtocol = Ascii.GetBytes(value); }
}
/// <summary>
/// Gets or sets the authentication cookie.
/// </summary>
/// <value>
/// The authentication cookie.
/// </value>
public byte[] AuthenticationCookie { get; set; }
/// <summary>
/// Gets or sets the screen number.
/// </summary>
/// <value>
/// The screen number.
/// </value>
public uint ScreenNumber { get; set; }
/// <summary>
/// Gets the size of the message in bytes.
/// </summary>
/// <value>
/// The size of the messages in bytes.
/// </value>
protected override int BufferCapacity
{
get
{
var capacity = base.BufferCapacity;
capacity += 1; // IsSingleConnection
capacity += 4; // AuthenticationProtocol length
capacity += _authenticationProtocol.Length; // AuthenticationProtocol
capacity += 4; // AuthenticationCookie length
capacity += AuthenticationCookie.Length; // AuthenticationCookie
capacity += 4; // ScreenNumber
return capacity;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="X11ForwardingRequestInfo"/> class.
/// </summary>
public X11ForwardingRequestInfo()
{
WantReply = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="X11ForwardingRequestInfo"/> class.
/// </summary>
/// <param name="isSingleConnection">if set to <c>true</c> it is a single connection.</param>
/// <param name="protocol">The protocol.</param>
/// <param name="cookie">The cookie.</param>
/// <param name="screenNumber">The screen number.</param>
public X11ForwardingRequestInfo(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber)
: this()
{
IsSingleConnection = isSingleConnection;
AuthenticationProtocol = protocol;
AuthenticationCookie = cookie;
ScreenNumber = screenNumber;
}
/// <summary>
/// Called when type specific data need to be loaded.
/// </summary>
protected override void LoadData()
{
base.LoadData();
IsSingleConnection = ReadBoolean();
_authenticationProtocol = ReadBinary();
AuthenticationCookie = ReadBinary();
ScreenNumber = ReadUInt32();
}
/// <summary>
/// Called when type specific data need to be saved.
/// </summary>
protected override void SaveData()
{
base.SaveData();
Write(IsSingleConnection);
WriteBinaryString(_authenticationProtocol);
WriteBinaryString(AuthenticationCookie);
Write(ScreenNumber);
}
}
}
| 32.529851 | 115 | 0.540491 | [
"MIT"
] | rintindon/SSH.NET.dotnetcore | src/Renci.SshNet.Core/Messages/Connection/ChannelRequest/X11ForwardingRequestInfo.cs | 4,361 | C# |
using System.Collections.Generic;
namespace Microsoft.Dafny {
public class FunctionCallSubstituter : Substituter {
public readonly Function A, B;
public FunctionCallSubstituter(Expression receiverReplacement, Dictionary<IVariable, Expression/*!*/>/*!*/ substMap, Function a, Function b)
: base(receiverReplacement, substMap, new Dictionary<TypeParameter, Type>()) {
A = a;
B = b;
}
public override Expression Substitute(Expression expr) {
if (expr is FunctionCallExpr) {
FunctionCallExpr e = (FunctionCallExpr)expr;
Expression receiver = Substitute(e.Receiver);
List<Expression> newArgs = SubstituteExprList(e.Args);
FunctionCallExpr newFce = new FunctionCallExpr(expr.tok, e.Name, receiver, e.OpenParen, newArgs, e.AtLabel);
if (e.Function == A) {
newFce.Function = B;
newFce.Type = e.Type; // TODO: this may not work with type parameters.
} else {
newFce.Function = e.Function;
newFce.Type = e.Type;
}
newFce.TypeApplication_AtEnclosingClass = e.TypeApplication_AtEnclosingClass; // resolve here
newFce.TypeApplication_JustFunction = e.TypeApplication_JustFunction; // resolve here
newFce.IsByMethodCall = e.IsByMethodCall;
return newFce;
}
return base.Substitute(expr);
}
}
} | 42.78125 | 144 | 0.673484 | [
"MIT"
] | Anjiang-Wei/dafny | Source/Dafny/Verifier/FunctionCallSubstituter.cs | 1,369 | C# |
//
// This file manually written from cef/include/internal/cef_types.h.
// C API name: cef_drag_operations_mask.
//
#pragma warning disable 1591
// ReSharper disable once CheckNamespace
namespace Xilium.CefGlue
{
using System;
/// <summary>
/// "Verb" of a drag-and-drop operation as negotiated between the source and
/// destination. These constants match their equivalents in WebCore's
/// DragActions.h and should not be renumbered.
/// </summary>
public enum CefDragOperationsMask : uint
{
None = 0,
Copy = 1,
Link = 2,
Generic = 4,
Private = 8,
Move = 16,
Delete = 32,
Every = UInt32.MaxValue,
}
}
| 25.178571 | 80 | 0.625532 | [
"MIT",
"BSD-3-Clause"
] | NovusTheory/Chromely | src/Chromely.CefGlue/CefGlue/Enums/CefDragOperationsMask.cs | 707 | C# |
namespace WasaKredit.Client.Dotnet.Sdk.Contracts
{
public class CartItem
{
public string ProductId { get; set; }
public string ProductName { get; set; }
public Price PriceExVat { get; set; }
public int Quantity { get; set; }
public string VatPercentage { get; set; }
public Price VatAmount { get; set; }
public string ImageUrl { get; set; }
}
}
| 21 | 49 | 0.597619 | [
"MIT"
] | wasakredit/dotnet-checkout-sdk | src/WasaKredit.Client.Dotnet.Sdk/Contracts/CartItem.cs | 422 | C# |
using Newtonsoft.Json;
namespace AuroraNative
{
/// <summary>
/// 群系统消息 - 进群消息列表 抽象类
/// </summary>
public sealed class JoinRequest : BaseRequest
{
#region --属性--
/// <summary>
/// 请求者
/// </summary>
[JsonProperty(PropertyName = "requester_uin")]
public long RequesterUserID;
/// <summary>
/// 请求者昵称
/// </summary>
[JsonProperty(PropertyName = "requester_nick")]
public string RequesterNickName;
/// <summary>
/// 验证信息
/// </summary>
[JsonProperty(PropertyName = "message")]
public long Message;
#endregion
}
}
| 20.515152 | 55 | 0.524372 | [
"Apache-2.0"
] | fossabot/AuroraNative | AuroraNative/Abstract/Groups/SystemMessage/JoinRequest.cs | 735 | C# |
namespace Calculator_CSharp.Models
{
public class Calculator
{
public Calculator(decimal leftOperand, decimal rightOperand, string @operator)
{
LeftOperand = leftOperand;
RightOperand = rightOperand;
Operator = @operator;
Result = 0;
}
public Calculator()
{
this.Result = 0;
}
public decimal LeftOperand { get; set; }
public decimal RightOperand { get; set; }
public string Operator { get; set; }
public decimal Result { get; set; }
public decimal CalculatoreResult()
{
decimal result = 0;
switch (Operator)
{
case "+":
result = this.LeftOperand + this.RightOperand;
break;
case "-":
result = this.LeftOperand - this.RightOperand;
break;
case "*":
result = this.LeftOperand * this.RightOperand;
break;
case "/":
result = this.LeftOperand / this.RightOperand;
break;
}
this.Result = result;
return result;
}
}
} | 24.865385 | 86 | 0.46249 | [
"MIT"
] | Supbads/Softuni-Education | 08 SoftwareTechnologies 06.17/Software-Technologies/asp.net/01. Calculator/Calculator-CSharp/Models/Calculator.cs | 1,295 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.