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
/* * 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 kafka-2018-11-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Kafka.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Kafka.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UpdateBrokerType operation /// </summary> public class UpdateBrokerTypeResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { UpdateBrokerTypeResponse response = new UpdateBrokerTypeResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("clusterArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ClusterArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("clusterOperationArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ClusterOperationArn = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException")) { return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException")) { return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException")) { return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedException")) { return UnauthorizedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonKafkaException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static UpdateBrokerTypeResponseUnmarshaller _instance = new UpdateBrokerTypeResponseUnmarshaller(); internal static UpdateBrokerTypeResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateBrokerTypeResponseUnmarshaller Instance { get { return _instance; } } } }
42.535714
189
0.616121
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Kafka/Generated/Model/Internal/MarshallTransformations/UpdateBrokerTypeResponseUnmarshaller.cs
5,955
C#
 // IPluginConstants.cs // Copyright (c) 2014+ by Michael Penner. All rights reserved. namespace EamonRT.Framework.Plugin { /// <summary></summary> public interface IPluginConstants : EamonDD.Framework.Plugin.IPluginConstants { /// <summary></summary> long StartRoom { get; } /// <summary></summary> long NumSaveSlots { get; } /// <summary></summary> long ScaledHardinessUnarmedMaxDamage { get; } /// <summary></summary> double ScaledHardinessMaxDamageDivisor { get; } /// <summary></summary> string CommandPrompt { get; } /// <summary></summary> string PageSep { get; } /// <summary></summary> string RtProgVersion { get; } } }
21.30303
79
0.638691
[ "MIT" ]
TheRealEamonCS/Eamon-CS
System/EamonRT/Framework/Plugin/IPluginConstants.cs
705
C#
namespace BuscarParaula { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(87, 44); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(521, 88); this.textBox1.TabIndex = 0; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(153, 218); this.textBox2.Multiline = true; this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(311, 89); this.textBox2.TabIndex = 1; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(209, 166); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(100, 20); this.textBox3.TabIndex = 2; // // button1 // this.button1.Location = new System.Drawing.Point(354, 166); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 3; this.button1.Text = "Buscar"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.Button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(455, 166); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 4; this.button2.Text = "Girar text"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.Button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(513, 218); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 23); this.button3.TabIndex = 5; this.button3.Text = "Vocals"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.Button3_Click); // // button4 // this.button4.Location = new System.Drawing.Point(513, 263); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 23); this.button4.TabIndex = 6; this.button4.Text = "MayusMinus"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.Button4_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(662, 345); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; } }
39.402985
107
0.557576
[ "Apache-2.0" ]
lavisnow/ASIX-M03
BuscarParaula/BuscarParaula/Form1.Designer.cs
5,282
C#
using Lib; using Microsoft.VisualStudio.TestTools.UnitTesting; using Test.Lib; namespace Test.Lib { [TestClass] public class ObjectExtendsTest : TestBase { private class ObjectExtendsTestClassA { } private class ObjectExtendsTestClassB : ObjectExtendsTestClassA { } [TestMethod] public void Test() { Assert.IsTrue(ObjectExtends.EqualsDefault(0)); Assert.IsFalse(ObjectExtends.EqualsDefault(1)); Assert.IsTrue(ObjectExtends.EqualsDefault(default(string))); Assert.IsFalse(ObjectExtends.EqualsDefault(string.Empty)); Assert.AreEqual(ObjectExtends.DefaultThen(default(string), string.Empty), string.Empty); Assert.AreEqual(ObjectExtends.DefaultThen(string.Empty, default(string)), string.Empty); Assert.AreNotEqual(ObjectExtends.DefaultThen(default(ObjectExtendsTestClassA)), default(ObjectExtendsTestClassA)); Assert.AreNotEqual(ObjectExtends.DefaultThen<ObjectExtendsTestClassB, ObjectExtendsTestClassA>(default(ObjectExtendsTestClassA)), default(ObjectExtendsTestClassA)); } } }
42.296296
176
0.716287
[ "MIT" ]
Song-MengQi/Lib
Test.Lib/Knowledge/Extends/ObjectExtendsTest.cs
1,144
C#
using ProtoBuf; using System; using System.Collections.Generic; namespace GameData { [ProtoContract(Name = "DLuJingShuXing_ARRAY")] [Serializable] public class DLuJingShuXing_ARRAY : IExtensible { private readonly List<DLuJingShuXing> _items = new List<DLuJingShuXing>(); private IExtension extensionObject; [ProtoMember(1, Name = "items", DataFormat = DataFormat.Default)] public List<DLuJingShuXing> items { get { return this._items; } } IExtension IExtensible.GetExtensionObject(bool createIfMissing) { return Extensible.GetExtensionObject(ref this.extensionObject, createIfMissing); } } }
21.2
83
0.751572
[ "MIT" ]
corefan/tianqi_src
src/GameData/DLuJingShuXing_ARRAY.cs
636
C#
using System; using System.Collections.Generic; using System.Text; namespace ADN.Graphs { /// <summary> /// A class that represents a graph. /// </summary> public class Graph { /// <summary> /// Represents an edge of the graph. /// </summary> public struct Edge { public int Source; public int Destination; public double Weight; } private List<Edge>[] _adjacencyEdges; private double[,] _matrix; private readonly bool _directed; /// <summary> /// Class constructor. /// </summary> /// <param name="verticesCount">Number of vertices in the graph.</param> /// <param name="directed">True if is a direct graph, false otherwise.</param> public Graph(int verticesCount, bool directed = false) { EdgesCount = 0; _adjacencyEdges = new List<Edge>[verticesCount]; _matrix = new double[verticesCount, verticesCount]; _directed = directed; for (int i = 0; i < verticesCount; i++) { _adjacencyEdges[i] = new List<Edge>(); for (int j = 0; j < verticesCount; j++) { _matrix[i, j] = 0; } } } /// <summary> /// Number of vertices in the graph. /// </summary> /// <example> /// <code lang="csharp"> /// var verticesCount = 3; /// var graph = new Graph(verticesCount); /// var result = graph.VerticesCount; /// /// /* /// result is 3 /// */ /// </code> /// </example> public int VerticesCount { get { return _matrix.GetLength(0); } } /// <summary> /// Number of edges in the graph. /// </summary> /// <example> /// <code lang="csharp"> /// var verticesCount = 3; /// var graph = new Graph(verticesCount); /// // graph initialization /// var result = graph.EdgesCount; /// </code> /// </example> public int EdgesCount { get; private set; } /// <summary> /// Add an edge in the graph. /// </summary> /// <param name="edge">Edge to add.</param> /// <example> /// <code lang="csharp"> /// var verticesCount = 3; /// var graph = new Graph(verticesCount); /// graph.AddEdge(new Graph.Edge /// { /// Source = 0, /// Destination = 1, /// Weight = 10 /// }); /// </code> /// </example> public void AddEdge(Edge edge) { EdgesCount++; _adjacencyEdges[edge.Source].Add(edge); _matrix[edge.Source, edge.Destination] = edge.Weight; if (!_directed) { _adjacencyEdges[edge.Destination].Add( new Edge() { Source = edge.Destination, Destination = edge.Source, Weight = edge.Weight }); _matrix[edge.Destination, edge.Source] = edge.Weight; } } /// <summary> /// Get a mtatrix that represents the graph. /// </summary> /// <returns>A mtatrix that represents the graph.</returns> /// <example> /// <code lang="csharp"> /// var verticesCount = 3; /// var graph = new Graph(verticesCount); /// // graph initialization /// var result = graph.GetMatrix(); /// </code> /// </example> public double[,] GetMatrix() { return _matrix; } /// <summary> /// Gets the edges that connects a given vertex to the adjancency vertices. /// </summary> /// <param name="vertex">Origen vertex.</param> /// <returns>Edges that connects with the adjancency vertices.</returns> /// <example> /// <code lang="csharp"> /// var verticesCount = 3; /// var graph = new Graph(verticesCount); /// // graph initialization /// var adjancencyVertex = 0; /// var result = graph.Adjacency(adjancencyVertex); /// /// /* /// result is a Graph.Edge[] /// */ /// </code> /// </example> public Edge[] Adjacency(int vertex) { return _adjacencyEdges[vertex].ToArray(); } } }
29.50641
86
0.472301
[ "MIT" ]
andresdigiovanni/ADN.Graphs
src/ADN.Graphs/Models/Graph.cs
4,605
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.OpcUa.Publisher.Models { using System.Linq; /// <summary> /// Events extensions /// </summary> public static class PublishedDataSetVariableModelEx { /// <summary> /// Clone /// </summary> /// <param name="model"></param> /// <returns></returns> public static PublishedDataSetVariableModel Clone(this PublishedDataSetVariableModel model) { if (model == null) { return null; } return new PublishedDataSetVariableModel { DiscardNew = model.DiscardNew, Attribute = model.Attribute, DataChangeFilter = model.DataChangeFilter, DeadbandType = model.DeadbandType, DeadbandValue = model.DeadbandValue, IndexRange = model.IndexRange, MetaDataProperties = model.MetaDataProperties?.ToList(), PublishedVariableNodeId = model.PublishedVariableNodeId, PublishedVariableDisplayName = model.PublishedVariableDisplayName, SamplingInterval = model.SamplingInterval, SubstituteValue = model.SubstituteValue?.Copy(), QueueSize = model.QueueSize, HeartbeatInterval = model.HeartbeatInterval }; } } }
41.4
101
0.558575
[ "MIT" ]
JMayrbaeurl/Industrial-IoT
components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa/src/Publisher/Extensions/PublishedDataSetVariableModelEx.cs
1,658
C#
using System; using System.Collections.Generic; namespace Draw2D.ViewModels.Containers { public interface IDocumentContainer : ICopyable, IDisposable { string Title { get; set; } IStyleLibrary StyleLibrary { get; set; } IGroupLibrary GroupLibrary { get; set; } IBaseShape PointTemplate { get; set; } IList<IContainerView> ContainerViews { get; set; } IContainerView ContainerView { get; set; } } }
28.75
64
0.669565
[ "MIT" ]
punker76/Draw2D
src/Draw2D/ViewModels/Containers/Core/IDocumentContainer.cs
462
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Composition; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.BinaryParsers; using Microsoft.CodeAnalysis.BinaryParsers.PortableExecutable; using Microsoft.CodeAnalysis.IL.Sdk; using Microsoft.CodeAnalysis.Sarif; using Microsoft.CodeAnalysis.Sarif.Driver; namespace Microsoft.CodeAnalysis.IL.Rules { [Export(typeof(Skimmer<BinaryAnalyzerContext>)), Export(typeof(ReportingDescriptor))] public class DoNotMarkImportsSectionAsExecutable : PEBinarySkimmerBase { /// <summary> /// BA2010 /// </summary> public override string Id => RuleIds.DoNotMarkImportsSectionAsExecutable; /// <summary> /// PE sections should not be marked as both writable and executable. This condition /// makes it easier for an attacker to exploit memory corruption vulnerabilities, /// as it may provide an attacker executable location(s) to inject shellcode. /// Because the loader will always mark the imports section as writable, it is /// therefore important to mark this section as non-executable. To resolve this /// issue, ensure that your program does not mark the imports section executable. /// Look for uses of /SECTION or /MERGE on the linker command line, or #pragma /// segment in source code, which change the imports section to be executable, or /// which merge the ".rdata" segment into an executable section. /// </summary> public override MultiformatMessageString FullDescription => new MultiformatMessageString { Text = RuleResources.BA2010_DoNotMarkImportsSectionAsExecutable_Description }; protected override IEnumerable<string> MessageResourceNames => new string[] { nameof(RuleResources.BA2010_Pass), nameof(RuleResources.BA2010_Error), nameof(RuleResources.NotApplicable_InvalidMetadata) }; public override AnalysisApplicability CanAnalyzePE(PEBinary target, Sarif.PropertiesDictionary policy, out string reasonForNotAnalyzing) { PE portableExecutable = target.PE; AnalysisApplicability result = AnalysisApplicability.NotApplicableToSpecifiedTarget; reasonForNotAnalyzing = MetadataConditions.ImageIsKernelModeBinary; if (portableExecutable.IsKernelMode) { return result; } reasonForNotAnalyzing = MetadataConditions.ImageIsILOnlyAssembly; if (portableExecutable.IsILOnly) { return result; } reasonForNotAnalyzing = null; return AnalysisApplicability.ApplicableToSpecifiedTarget; } public override void Analyze(BinaryAnalyzerContext context) { PEBinary target = context.PEBinary(); string executableImportSection = null; PEHeader peHeader = target.PE.PEHeaders.PEHeader; DirectoryEntry importTable = peHeader.ImportTableDirectory; if (importTable.RelativeVirtualAddress != 0 && target.PE.PEHeaders.SectionHeaders != null) { foreach (SectionHeader sectionHeader in target.PE.PEHeaders.SectionHeaders) { SectionCharacteristics memExecute = SectionCharacteristics.MemExecute; if ((sectionHeader.SectionCharacteristics & memExecute) == 0) { continue; } int size = sectionHeader.SizeOfRawData; int address = sectionHeader.VirtualAddress; if ((address <= importTable.RelativeVirtualAddress) && (address + size >= importTable.RelativeVirtualAddress + importTable.Size)) { // Our import section is in a writable section - bad executableImportSection = sectionHeader.Name; break; } } } if (executableImportSection != null) { // '{0}' has the imports section marked executable. Because the loader will always mark // the imports section as writable, it is important to mark this section as non-executable, // so that an attacker cannot place shellcode here. To resolve this issue, ensure that your //program does not mark the imports section as executable. Look for uses of /SECTION or // /MERGE on the linker command line, or #pragma segment in source code, which change the // imports section to be executable, or which merge the ".rdata" segment into an executable // section. context.Logger.Log(this, RuleUtilities.BuildResult(FailureLevel.Error, context, null, nameof(RuleResources.BA2010_Error), context.TargetUri.GetFileName())); return; } // '{0}' does not have an imports section that is marked as executable. context.Logger.Log(this, RuleUtilities.BuildResult(ResultKind.Pass, context, null, nameof(RuleResources.BA2010_Pass), context.TargetUri.GetFileName())); } } }
50.035398
178
0.62752
[ "MIT" ]
michaelcfanning/binskim
src/BinSkim.Rules/PERules/BA2010.DoNotMarkImportsSectionAsExecutable.cs
5,656
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.open.agent.confirm /// </summary> public class AlipayOpenAgentConfirmRequest : IAopRequest<AlipayOpenAgentConfirmResponse> { /// <summary> /// 提交代商户签约、创建应用事务 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.open.agent.confirm"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.336364
92
0.60187
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Request/AlipayOpenAgentConfirmRequest.cs
2,595
C#
using System; using System.Collections.Generic; using Plugins.GameService.Tools.NaughtyAttributes.Scripts.Core.ValidatorAttributes; using UnityEditor; namespace Plugins.GameService.Tools.NaughtyAttributes.Scripts.Editor.PropertyValidators { public abstract class PropertyValidatorBase { public abstract void ValidateProperty(SerializedProperty property); } public static class ValidatorAttributeExtensions { private static Dictionary<Type, PropertyValidatorBase> _validatorsByAttributeType; static ValidatorAttributeExtensions() { _validatorsByAttributeType = new Dictionary<Type, PropertyValidatorBase>(); _validatorsByAttributeType[typeof(MinValueAttribute)] = new MinValuePropertyValidator(); _validatorsByAttributeType[typeof(MaxValueAttribute)] = new MaxValuePropertyValidator(); _validatorsByAttributeType[typeof(RequiredAttribute)] = new RequiredPropertyValidator(); _validatorsByAttributeType[typeof(ValidateInputAttribute)] = new ValidateInputPropertyValidator(); } public static PropertyValidatorBase GetValidator(this ValidatorAttribute attr) { PropertyValidatorBase validator; if (_validatorsByAttributeType.TryGetValue(attr.GetType(), out validator)) { return validator; } else { return null; } } } }
32.125
101
0.807782
[ "Apache-2.0" ]
AR-Ghodrati/DoooZ
Assets/Plugins/GameService/Tools/NaughtyAttributes/Scripts/Editor/PropertyValidators/PropertyValidatorBase.cs
1,287
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("inTeliScriptWeatherPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("inTeliScriptWeatherPlugin")] [assembly: AssemblyCopyright("Copyright © Microsoft 2007")] [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("fc08bafe-902c-43c6-8998-8ac410a6ab92")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.888889
85
0.738162
[ "BSD-3-Clause" ]
cetin01/callbutler-in-vs2008
RUN/Scripting/Dev/Sample Code/inTeliScriptWeatherPlugin/Properties/AssemblyInfo.cs
1,439
C#
using YAF.Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; using JCG = J2N.Collections.Generic; namespace YAF.Lucene.Net.Codecs.PerField { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using FieldInfo = YAF.Lucene.Net.Index.FieldInfo; using IOUtils = YAF.Lucene.Net.Util.IOUtils; using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator; using SegmentReadState = YAF.Lucene.Net.Index.SegmentReadState; using SegmentWriteState = YAF.Lucene.Net.Index.SegmentWriteState; using Terms = YAF.Lucene.Net.Index.Terms; /// <summary> /// Enables per field postings support. /// <para/> /// Note, when extending this class, the name (<see cref="PostingsFormat.Name"/>) is /// written into the index. In order for the field to be read, the /// name must resolve to your implementation via <see cref="PostingsFormat.ForName(string)"/>. /// This method uses <see cref="IPostingsFormatFactory.GetPostingsFormat(string)"/> to resolve format names. /// See <see cref="DefaultPostingsFormatFactory"/> for information about how to implement your own <see cref="PostingsFormat"/>. /// <para/> /// Files written by each posting format have an additional suffix containing the /// format name. For example, in a per-field configuration instead of <c>_1.prx</c> /// filenames would look like <c>_1_Lucene40_0.prx</c>. /// <para/> /// @lucene.experimental /// </summary> /// <seealso cref="IPostingsFormatFactory"/> /// <seealso cref="DefaultPostingsFormatFactory"/> [PostingsFormatName("PerField40")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name public abstract class PerFieldPostingsFormat : PostingsFormat { // LUCENENET specific - removed this static variable because our name is determined by the PostingsFormatNameAttribute ///// <summary> ///// Name of this <seealso cref="PostingsFormat"/>. </summary> //public static readonly string PER_FIELD_NAME = "PerField40"; /// <summary> /// <see cref="FieldInfo"/> attribute name used to store the /// format name for each field. /// </summary> public static readonly string PER_FIELD_FORMAT_KEY = typeof(PerFieldPostingsFormat).Name + ".format"; /// <summary> /// <see cref="FieldInfo"/> attribute name used to store the /// segment suffix name for each field. /// </summary> public static readonly string PER_FIELD_SUFFIX_KEY = typeof(PerFieldPostingsFormat).Name + ".suffix"; /// <summary> /// Sole constructor. </summary> protected PerFieldPostingsFormat() // LUCENENET: CA1012: Abstract types should not have constructors (marked protected) : base() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override sealed FieldsConsumer FieldsConsumer(SegmentWriteState state) { return new FieldsWriter(this, state); } internal class FieldsConsumerAndSuffix : IDisposable { internal FieldsConsumer Consumer { get; set; } internal int Suffix { get; set; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { Consumer.Dispose(); } } private class FieldsWriter : FieldsConsumer { private readonly PerFieldPostingsFormat outerInstance; internal readonly IDictionary<PostingsFormat, FieldsConsumerAndSuffix> formats = new Dictionary<PostingsFormat, FieldsConsumerAndSuffix>(); internal readonly IDictionary<string, int?> suffixes = new Dictionary<string, int?>(); internal readonly SegmentWriteState segmentWriteState; public FieldsWriter(PerFieldPostingsFormat outerInstance, SegmentWriteState state) { this.outerInstance = outerInstance; segmentWriteState = state; } public override TermsConsumer AddField(FieldInfo field) { PostingsFormat format = outerInstance.GetPostingsFormatForField(field.Name); if (format == null) { throw IllegalStateException.Create("invalid null PostingsFormat for field=\"" + field.Name + "\""); } string formatName = format.Name; string previousValue = field.PutAttribute(PER_FIELD_FORMAT_KEY, formatName); if (Debugging.AssertsEnabled) Debugging.Assert(previousValue == null); int? suffix; if (!formats.TryGetValue(format, out FieldsConsumerAndSuffix consumer) || consumer == null) { // First time we are seeing this format; create a new instance // bump the suffix if (!suffixes.TryGetValue(formatName, out suffix) || suffix == null) { suffix = 0; } else { suffix = suffix + 1; } suffixes[formatName] = suffix; string segmentSuffix = GetFullSegmentSuffix(field.Name, segmentWriteState.SegmentSuffix, GetSuffix(formatName, Convert.ToString(suffix, CultureInfo.InvariantCulture))); consumer = new FieldsConsumerAndSuffix(); consumer.Consumer = format.FieldsConsumer(new SegmentWriteState(segmentWriteState, segmentSuffix)); consumer.Suffix = suffix.Value; // LUCENENET NOTE: At this point suffix cannot be null formats[format] = consumer; } else { // we've already seen this format, so just grab its suffix if (Debugging.AssertsEnabled) Debugging.Assert(suffixes.ContainsKey(formatName)); suffix = consumer.Suffix; } previousValue = field.PutAttribute(PER_FIELD_SUFFIX_KEY, Convert.ToString(suffix, CultureInfo.InvariantCulture)); if (Debugging.AssertsEnabled) Debugging.Assert(previousValue == null); // TODO: we should only provide the "slice" of FIS // that this PF actually sees ... then stuff like // .hasProx could work correctly? // NOTE: .hasProx is already broken in the same way for the non-perfield case, // if there is a fieldinfo with prox that has no postings, you get a 0 byte file. return consumer.Consumer.AddField(field); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override void Dispose(bool disposing) { if (disposing) { // Close all subs IOUtils.Dispose(formats.Values); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetSuffix(string formatName, string suffix) { return formatName + "_" + suffix; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string GetFullSegmentSuffix(string fieldName, string outerSegmentSuffix, string segmentSuffix) { if (outerSegmentSuffix.Length == 0) { return segmentSuffix; } else { // TODO: support embedding; I think it should work but // we need a test confirm to confirm // return outerSegmentSuffix + "_" + segmentSuffix; throw IllegalStateException.Create("cannot embed PerFieldPostingsFormat inside itself (field \"" + fieldName + "\" returned PerFieldPostingsFormat)"); } } private class FieldsReader : FieldsProducer { // LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java internal readonly IDictionary<string, FieldsProducer> fields = new JCG.SortedDictionary<string, FieldsProducer>(StringComparer.Ordinal); internal readonly IDictionary<string, FieldsProducer> formats = new Dictionary<string, FieldsProducer>(); public FieldsReader(SegmentReadState readState) { // Read _X.per and init each format: bool success = false; try { // Read field name -> format name foreach (FieldInfo fi in readState.FieldInfos) { if (fi.IsIndexed) { string fieldName = fi.Name; string formatName = fi.GetAttribute(PER_FIELD_FORMAT_KEY); if (formatName != null) { // null formatName means the field is in fieldInfos, but has no postings! string suffix = fi.GetAttribute(PER_FIELD_SUFFIX_KEY); if (Debugging.AssertsEnabled) Debugging.Assert(suffix != null); PostingsFormat format = PostingsFormat.ForName(formatName); string segmentSuffix = GetSuffix(formatName, suffix); // LUCENENET: Eliminated extra lookup by using TryGetValue instead of ContainsKey if (!formats.TryGetValue(segmentSuffix, out Codecs.FieldsProducer field)) { formats[segmentSuffix] = field = format.FieldsProducer(new SegmentReadState(readState, segmentSuffix)); } fields[fieldName] = field; } } } success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(formats.Values); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override IEnumerator<string> GetEnumerator() { return fields.Keys.GetEnumerator(); // LUCENENET NOTE: enumerators are not writable in .NET } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override Terms GetTerms(string field) { if (fields.TryGetValue(field, out FieldsProducer fieldsProducer) && fieldsProducer != null) { return fieldsProducer.GetTerms(field); } return null; } public override int Count => fields.Count; [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override void Dispose(bool disposing) { if (disposing) { IOUtils.Dispose(formats.Values); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override long RamBytesUsed() { long sizeInBytes = 0; foreach (KeyValuePair<string, FieldsProducer> entry in formats) { sizeInBytes += entry.Key.Length * RamUsageEstimator.NUM_BYTES_CHAR; sizeInBytes += entry.Value.RamBytesUsed(); } return sizeInBytes; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override void CheckIntegrity() { foreach (FieldsProducer producer in formats.Values) { producer.CheckIntegrity(); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override sealed FieldsProducer FieldsProducer(SegmentReadState state) { return new FieldsReader(state); } /// <summary> /// Returns the postings format that should be used for writing /// new segments of <paramref name="field"/>. /// <para/> /// The field to format mapping is written to the index, so /// this method is only invoked when writing, not when reading. /// </summary> public abstract PostingsFormat GetPostingsFormatForField(string field); } }
45.670968
179
0.563356
[ "Apache-2.0" ]
Spinks90/YAFNET
yafsrc/Lucene.Net/Lucene.Net/Codecs/PerField/PerFieldPostingsFormat.cs
13,849
C#
namespace ZazasCleaningService.Web.Controllers { using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ZazasCleaningService.Data.Common.Repositories; using ZazasCleaningService.Data.Models; using ZazasCleaningService.Services.Data; using ZazasCleaningService.Web.ViewModels.Settings; public class SettingsController : BaseController { private readonly ISettingsService settingsService; private readonly IDeletableEntityRepository<Setting> repository; public SettingsController(ISettingsService settingsService, IDeletableEntityRepository<Setting> repository) { this.settingsService = settingsService; this.repository = repository; } public IActionResult Index() { var settings = this.settingsService.GetAll<SettingViewModel>(); var model = new SettingsListViewModel { Settings = settings }; return this.View(model); } public async Task<IActionResult> InsertSetting() { var random = new Random(); var setting = new Setting { Name = $"Name_{random.Next()}", Value = $"Value_{random.Next()}" }; await this.repository.AddAsync(setting); await this.repository.SaveChangesAsync(); return this.RedirectToAction(nameof(this.Index)); } } }
32.930233
115
0.668079
[ "MIT" ]
TihomirIvanovIvanov/ZazasCleaningService
ZazasCleaningService/Web/ZazasCleaningService.Web/Controllers/SettingsController.cs
1,418
C#
// // ICellAccessibleParent.cs // // Author: // Eitan Isaacson <eitan@ascender.com> // // Copyright (C) 2009 Eitan Isaacson. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Hyena.Data.Gui.Accessibility { public interface ICellAccessibleParent { Gdk.Rectangle GetCellExtents (ColumnCellAccessible cell, Atk.CoordType coord_type); int GetCellIndex (ColumnCellAccessible cell); bool IsCellShowing (ColumnCellAccessible cell); bool IsCellFocused (ColumnCellAccessible cell); bool IsCellSelected (ColumnCellAccessible cell); bool IsCellActive (ColumnCellAccessible cell); void InvokeColumnHeaderMenu (ColumnCellAccessible column); void ClickColumnHeader (ColumnCellAccessible column); void CellRedrawn (int column, int row); } }
40.630435
91
0.746923
[ "MIT" ]
NguyenMatthieu/f-spot
lib/Hyena/Hyena.Gui/Hyena.Data.Gui/Accessibility/ICellAccessibleParent.cs
1,869
C#
/* * Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.UI; // Image 40: Unity.TextMeshPro.dll - Assembly: Unity.TextMeshPro, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 6069-6241 namespace TMPro { [AddComponentMenu] // 0x000000018003BFB0-0x000000018003BFE0 public class TMP_InputField : Selectable, IUpdateSelectedHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler, ISubmitHandler, ICanvasElement, ILayoutElement, IScrollHandler // TypeDefIndex: 6142 { // Fields protected TouchScreenKeyboard m_SoftKeyboard; // 0xF8 private static readonly char[] kSeparators; // 0x00 protected RectTransform m_RectTransform; // 0x100 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected RectTransform m_TextViewport; // 0x108 protected RectMask2D m_TextComponentRectMask; // 0x110 protected RectMask2D m_TextViewportRectMask; // 0x118 private Rect m_CachedViewportRect; // 0x120 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected TMP_Text m_TextComponent; // 0x130 protected RectTransform m_TextComponentRectTransform; // 0x138 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected Graphic m_Placeholder; // 0x140 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected Scrollbar m_VerticalScrollbar; // 0x148 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected TMP_ScrollbarEventHandler m_VerticalScrollbarEventHandler; // 0x150 private bool m_IsDrivenByLayoutComponents; // 0x158 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private LayoutGroup m_LayoutGroup; // 0x160 private IScrollHandler m_IScrollHandlerParent; // 0x168 private float m_ScrollPosition; // 0x170 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected float m_ScrollSensitivity; // 0x174 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private ContentType m_ContentType; // 0x178 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private InputType m_InputType; // 0x17C [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private char m_AsteriskChar; // 0x180 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private TouchScreenKeyboardType m_KeyboardType; // 0x184 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private LineType m_LineType; // 0x188 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private bool m_HideMobileInput; // 0x18C [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private bool m_HideSoftKeyboard; // 0x18D [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private CharacterValidation m_CharacterValidation; // 0x190 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private string m_RegexValue; // 0x198 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private float m_GlobalPointSize; // 0x1A0 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private int m_CharacterLimit; // 0x1A4 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private SubmitEvent m_OnEndEdit; // 0x1A8 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private SubmitEvent m_OnSubmit; // 0x1B0 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private SelectionEvent m_OnSelect; // 0x1B8 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private SelectionEvent m_OnDeselect; // 0x1C0 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private TextSelectionEvent m_OnTextSelection; // 0x1C8 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private TextSelectionEvent m_OnEndTextSelection; // 0x1D0 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private OnChangeEvent m_OnValueChanged; // 0x1D8 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private TouchScreenKeyboardEvent m_OnTouchScreenKeyboardStatusChanged; // 0x1E0 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private OnValidateInput m_OnValidateInput; // 0x1E8 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private Color m_CaretColor; // 0x1F0 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private bool m_CustomCaretColor; // 0x200 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private Color m_SelectionColor; // 0x204 [SerializeField] // 0x000000018003BFE0-0x000000018003C020 [TextArea] // 0x000000018003BFE0-0x000000018003C020 protected string m_Text; // 0x218 [Range] // 0x0000000180033660-0x00000001800336A0 [SerializeField] // 0x0000000180033660-0x00000001800336A0 private float m_CaretBlinkRate; // 0x220 [Range] // 0x0000000180032B10-0x0000000180032B50 [SerializeField] // 0x0000000180032B10-0x0000000180032B50 private int m_CaretWidth; // 0x224 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private bool m_ReadOnly; // 0x228 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private bool m_RichText; // 0x229 protected int m_StringPosition; // 0x22C protected int m_StringSelectPosition; // 0x230 protected int m_CaretPosition; // 0x234 protected int m_CaretSelectPosition; // 0x238 private RectTransform caretRectTrans; // 0x240 protected UIVertex[] m_CursorVerts; // 0x248 private CanvasRenderer m_CachedInputRenderer; // 0x250 private Vector2 m_LastPosition; // 0x258 [NonSerialized] protected Mesh m_Mesh; // 0x260 private bool m_AllowInput; // 0x268 private bool m_ShouldActivateNextUpdate; // 0x269 private bool m_UpdateDrag; // 0x26A private bool m_DragPositionOutOfBounds; // 0x26B private const float kHScrollSpeed = 0.05f; // Metadata: 0x003A1F1F private const float kVScrollSpeed = 0.1f; // Metadata: 0x003A1F23 protected bool m_CaretVisible; // 0x26C private Coroutine m_BlinkCoroutine; // 0x270 private float m_BlinkStartTime; // 0x278 private Coroutine m_DragCoroutine; // 0x280 private string m_OriginalText; // 0x288 private bool m_WasCanceled; // 0x290 private bool m_HasDoneFocusTransition; // 0x291 private WaitForSecondsRealtime m_WaitForSecondsRealtime; // 0x298 private bool m_PreventCallback; // 0x2A0 private bool m_TouchKeyboardAllowsInPlaceEditing; // 0x2A1 private bool m_IsTextComponentUpdateRequired; // 0x2A2 private bool m_isLastKeyBackspace; // 0x2A3 private float m_PointerDownClickStartTime; // 0x2A4 private float m_KeyDownStartTime; // 0x2A8 private float m_DoubleClickDelay; // 0x2AC private const string kEmailSpecialCharacters = "!#$%&\'*+-/=?^_`{|}~"; // Metadata: 0x003A1F27 private bool m_IsCompositionActive; // 0x2B0 private bool m_ShouldUpdateIMEWindowPosition; // 0x2B1 private int m_PreviousIMEInsertionLine; // 0x2B4 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected TMP_FontAsset m_GlobalFontAsset; // 0x2B8 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected bool m_OnFocusSelectAll; // 0x2C0 protected bool m_isSelectAll; // 0x2C1 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected bool m_ResetOnDeActivation; // 0x2C2 private bool m_SelectionStillActive; // 0x2C3 private bool m_ReleaseSelection; // 0x2C4 private GameObject m_PreviouslySelectedObject; // 0x2C8 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 private bool m_RestoreOriginalTextOnEscape; // 0x2D0 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected bool m_isRichTextEditingAllowed; // 0x2D1 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected int m_LineLimit; // 0x2D4 [SerializeField] // 0x0000000180014D50-0x0000000180014D60 protected TMP_InputValidator m_InputValidator; // 0x2D8 private bool m_isSelected; // 0x2E0 private bool m_IsStringPositionDirty; // 0x2E1 private bool m_IsCaretPositionDirty; // 0x2E2 private bool m_forceRectTransformAdjustment; // 0x2E3 private UnityEngine.Event m_ProcessingEvent; // 0x2E8 // Properties private BaseInput inputSystem { get; } // 0x000000018052BF90-0x000000018052C0C0 private string compositionString { get; } // 0x000000018052BE10-0x000000018052BEC0 private int compositionLength { get; } // 0x000000018052BDE0-0x000000018052BE10 protected Mesh mesh { get; } // 0x000000018052C120-0x000000018052C1D0 public bool shouldHideMobileInput { get; set; } // 0x000000018052C650-0x000000018052C680 0x000000018052DB70-0x000000018052DBF0 public bool shouldHideSoftKeyboard { get; set; } // 0x000000018052C680-0x000000018052C6E0 0x000000018052DBF0-0x000000018052DD10 public string text { get; set; } // 0x000000018052C6E0-0x000000018052C6F0 0x000000018052DF50-0x000000018052DF60 public bool isFocused { get; } // 0x00000001803E8AB0-0x00000001803E8AC0 public float caretBlinkRate { get; set; } // 0x000000018052BCB0-0x000000018052BCC0 0x000000018052C7B0-0x000000018052C820 public int caretWidth { get; set; } // 0x000000018052BDA0-0x000000018052BDB0 0x000000018052CA80-0x000000018052CB20 public RectTransform textViewport { get; set; } // 0x0000000180377500-0x0000000180377510 0x000000018052DF00-0x000000018052DF50 public TMP_Text textComponent { get; set; } // 0x000000018046A620-0x000000018046A630 0x000000018052DEA0-0x000000018052DF00 public Graphic placeholder { get; set; } // 0x00000001803135E0-0x00000001803135F0 0x000000018052D550-0x000000018052D5A0 public Scrollbar verticalScrollbar { get; set; } // 0x000000018052C6F0-0x000000018052C700 0x000000018052DF60-0x000000018052E130 public float scrollSensitivity { get; set; } // 0x000000018052C5B0-0x000000018052C5C0 0x000000018052D7F0-0x000000018052D890 public Color caretColor { get; set; } // 0x000000018052BCC0-0x000000018052BD20 0x000000018052C820-0x000000018052C8A0 public bool customCaretColor { get; set; } // 0x000000018052BED0-0x000000018052BEE0 0x000000018052CE00-0x000000018052CE70 public Color selectionColor { get; set; } // 0x000000018052C5C0-0x000000018052C5D0 0x000000018052D930-0x000000018052D9B0 public SubmitEvent onEndEdit { get; set; } // 0x00000001802879C0-0x00000001802879D0 0x000000018052D2C0-0x000000018052D310 public SubmitEvent onSubmit { get; set; } // 0x0000000180288520-0x0000000180288530 0x000000018052D3C0-0x000000018052D410 public SelectionEvent onSelect { get; set; } // 0x00000001803E42C0-0x00000001803E42D0 0x000000018052D370-0x000000018052D3C0 public SelectionEvent onDeselect { get; set; } // 0x0000000180288530-0x0000000180288540 0x000000018052D270-0x000000018052D2C0 public TextSelectionEvent onTextSelection { get; set; } // 0x00000001803EB1A0-0x00000001803EB1B0 0x000000018052D410-0x000000018052D460 public TextSelectionEvent onEndTextSelection { get; set; } // 0x000000018052C200-0x000000018052C210 0x000000018052D310-0x000000018052D360 public OnChangeEvent onValueChanged { get; set; } // 0x000000018052C230-0x000000018052C240 0x000000018052D500-0x000000018052D550 public TouchScreenKeyboardEvent onTouchScreenKeyboardStatusChanged { get; set; } // 0x000000018052C220-0x000000018052C230 0x000000018052D460-0x000000018052D4B0 public OnValidateInput onValidateInput { get; set; } // 0x00000001803F5770-0x00000001803F5780 0x000000018052D4B0-0x000000018052D500 public int characterLimit { get; set; } // 0x000000018052BDB0-0x000000018052BDC0 0x000000018052CB20-0x000000018052CBD0 public float pointSize { get; set; } // 0x000000018052C240-0x000000018052C250 0x000000018052D5A0-0x000000018052D720 public TMP_FontAsset fontAsset { get; set; } // 0x000000018052BEF0-0x000000018052BF00 0x000000018052CE70-0x000000018052CFB0 public bool onFocusSelectAll { get; set; } // 0x000000018052C210-0x000000018052C220 0x000000018052D360-0x000000018052D370 public bool resetOnDeActivation { get; set; } // 0x000000018052C580-0x000000018052C590 0x000000018052D730-0x000000018052D740 public bool restoreOriginalTextOnEscape { get; set; } // 0x000000018052C590-0x000000018052C5A0 0x000000018052D740-0x000000018052D750 public bool isRichTextEditingAllowed { get; set; } // 0x000000018052C0E0-0x000000018052C0F0 0x000000018052D090-0x000000018052D0A0 public ContentType contentType { get; set; } // 0x000000018052BEC0-0x000000018052BED0 0x000000018052CC50-0x000000018052CE00 public LineType lineType { get; set; } // 0x000000018052C110-0x000000018052C120 0x000000018052D180-0x000000018052D270 public int lineLimit { get; set; } // 0x000000018052C100-0x000000018052C110 0x000000018052D110-0x000000018052D180 public InputType inputType { get; set; } // 0x000000018052C0C0-0x000000018052C0D0 0x000000018052CFB0-0x000000018052D020 public TouchScreenKeyboardType keyboardType { get; set; } // 0x000000018052C0F0-0x000000018052C100 0x000000018052D0A0-0x000000018052D110 public CharacterValidation characterValidation { get; set; } // 0x000000018052BDC0-0x000000018052BDD0 0x000000018052CBD0-0x000000018052CC40 public TMP_InputValidator inputValidator { get; set; } // 0x000000018052C0D0-0x000000018052C0E0 0x000000018052D020-0x000000018052D090 public bool readOnly { get; set; } // 0x000000018052C570-0x000000018052C580 0x000000018052D720-0x000000018052D730 public bool richText { get; set; } // 0x000000018052C5A0-0x000000018052C5B0 0x000000018052D750-0x000000018052D7F0 public bool multiLine { get; } // 0x000000018052C1E0-0x000000018052C200 public char asteriskChar { get; set; } // 0x000000018052BCA0-0x000000018052BCB0 0x000000018052C750-0x000000018052C7B0 public bool wasCanceled { get; } // 0x000000018052C700-0x000000018052C710 protected int caretPositionInternal { get; set; } // 0x000000018052BD20-0x000000018052BD60 0x000000018052C8A0-0x000000018052C900 protected int stringPositionInternal { get; set; } // 0x000000018052C5D0-0x000000018052C610 0x000000018052DD10-0x000000018052DD60 protected int caretSelectPositionInternal { get; set; } // 0x000000018052BD60-0x000000018052BDA0 0x000000018052CA20-0x000000018052CA80 protected int stringSelectPositionInternal { get; set; } // 0x000000018052C610-0x000000018052C650 0x000000018052DE50-0x000000018052DEA0 private new bool hasSelection { get; } // 0x000000018052BF00-0x000000018052BF90 public int caretPosition { get; set; } // 0x000000018052BD60-0x000000018052BDA0 0x000000018052C900-0x000000018052CA20 public int selectionAnchorPosition { get; set; } // 0x000000018052BD20-0x000000018052BD60 0x000000018052D890-0x000000018052D930 public int selectionFocusPosition { get; set; } // 0x000000018052BD60-0x000000018052BDA0 0x000000018052D9B0-0x000000018052DA50 public int stringPosition { get; set; } // 0x000000018052C610-0x000000018052C650 0x000000018052DD60-0x000000018052DE50 public int selectionStringAnchorPosition { get; set; } // 0x000000018052C5D0-0x000000018052C610 0x000000018052DA50-0x000000018052DAE0 public int selectionStringFocusPosition { get; set; } // 0x000000018052C610-0x000000018052C650 0x000000018052DAE0-0x000000018052DB70 private static string clipboard { get; set; } // 0x000000018052BDD0-0x000000018052BDE0 0x000000018052CC40-0x000000018052CC50 public virtual float minWidth { get; } // 0x000000018052C1D0-0x000000018052C1E0 public virtual float preferredWidth { get; } // 0x000000018052C3E0-0x000000018052C570 public virtual float flexibleWidth { get; } // 0x000000018052BEE0-0x000000018052BEF0 public virtual float minHeight { get; } // 0x000000018052C1D0-0x000000018052C1E0 public virtual float preferredHeight { get; } // 0x000000018052C250-0x000000018052C3E0 public virtual float flexibleHeight { get; } // 0x000000018052BEE0-0x000000018052BEF0 public virtual int layoutPriority { get; } // 0x0000000180398E30-0x0000000180398E40 Transform ICanvasElement.transform { get; } // 0x0000000180473370-0x0000000180473380 // Nested types public enum ContentType // TypeDefIndex: 6129 { Standard = 0, Autocorrected = 1, IntegerNumber = 2, DecimalNumber = 3, Alphanumeric = 4, Name = 5, EmailAddress = 6, Password = 7, Pin = 8, Custom = 9 } public enum InputType // TypeDefIndex: 6130 { Standard = 0, AutoCorrect = 1, Password = 2 } public enum CharacterValidation // TypeDefIndex: 6131 { None = 0, Digit = 1, Integer = 2, Decimal = 3, Alphanumeric = 4, Name = 5, Regex = 6, EmailAddress = 7, CustomValidator = 8 } public enum LineType // TypeDefIndex: 6132 { SingleLine = 0, MultiLineSubmit = 1, MultiLineNewline = 2 } public delegate char OnValidateInput(string text, int charIndex, char addedChar); // TypeDefIndex: 6133; 0x0000000180854010-0x00000001808544B0 [Serializable] public class SubmitEvent : UnityEvent<string> // TypeDefIndex: 6134 { // Constructors public SubmitEvent(); // 0x00000001808835A0-0x00000001808835E0 } [Serializable] public class OnChangeEvent : UnityEvent<string> // TypeDefIndex: 6135 { // Constructors public OnChangeEvent(); // 0x0000000180882ED0-0x0000000180882F10 } [Serializable] public class SelectionEvent : UnityEvent<string> // TypeDefIndex: 6136 { // Constructors public SelectionEvent(); // 0x0000000180883030-0x0000000180883070 } [Serializable] public class TextSelectionEvent : UnityEvent<string, int, int> // TypeDefIndex: 6137 { // Constructors public TextSelectionEvent(); // 0x0000000180883780-0x00000001808837C0 } [Serializable] public class TouchScreenKeyboardEvent : UnityEvent<TouchScreenKeyboard.Status> // TypeDefIndex: 6138 { // Constructors public TouchScreenKeyboardEvent(); // 0x00000001808837C0-0x0000000180883800 } protected enum EditState // TypeDefIndex: 6139 { Continue = 0, Finish = 1 } [CompilerGenerated] // 0x0000000180014D50-0x0000000180014D60 private sealed class _CaretBlink_d__276 : IEnumerator<object> // TypeDefIndex: 6140 { // Fields private int __1__state; // 0x10 private object __2__current; // 0x18 public TMP_InputField __4__this; // 0x20 // Properties object IEnumerator<System.Object>.Current { [DebuggerHidden] /* 0x0000000180014D50-0x0000000180014D60 */ get; } // 0x0000000180268C10-0x0000000180268C20 object IEnumerator.Current { [DebuggerHidden] /* 0x0000000180014D50-0x0000000180014D60 */ get; } // 0x0000000180268C10-0x0000000180268C20 // Constructors [DebuggerHidden] // 0x0000000180014D50-0x0000000180014D60 public _CaretBlink_d__276(int __1__state); // 0x0000000180296FE0-0x0000000180297010 // Methods [DebuggerHidden] // 0x0000000180014D50-0x0000000180014D60 void IDisposable.Dispose(); // 0x0000000180265310-0x0000000180265320 private bool MoveNext(); // 0x0000000180883800-0x0000000180883930 [DebuggerHidden] // 0x0000000180014D50-0x0000000180014D60 void IEnumerator.Reset(); // 0x0000000180883930-0x0000000180883970 } [CompilerGenerated] // 0x0000000180014D50-0x0000000180014D60 private sealed class _MouseDragOutsideRect_d__294 : IEnumerator<object> // TypeDefIndex: 6141 { // Fields private int __1__state; // 0x10 private object __2__current; // 0x18 public TMP_InputField __4__this; // 0x20 public PointerEventData eventData; // 0x28 // Properties object IEnumerator<System.Object>.Current { [DebuggerHidden] /* 0x0000000180014D50-0x0000000180014D60 */ get; } // 0x0000000180268C10-0x0000000180268C20 object IEnumerator.Current { [DebuggerHidden] /* 0x0000000180014D50-0x0000000180014D60 */ get; } // 0x0000000180268C10-0x0000000180268C20 // Constructors [DebuggerHidden] // 0x0000000180014D50-0x0000000180014D60 public _MouseDragOutsideRect_d__294(int __1__state); // 0x0000000180296FE0-0x0000000180297010 // Methods [DebuggerHidden] // 0x0000000180014D50-0x0000000180014D60 void IDisposable.Dispose(); // 0x0000000180265310-0x0000000180265320 private bool MoveNext(); // 0x00000001808848F0-0x0000000180884B90 [DebuggerHidden] // 0x0000000180014D50-0x0000000180014D60 void IEnumerator.Reset(); // 0x0000000180884B90-0x0000000180884BD0 } // Constructors protected TMP_InputField(); // 0x000000018052B980-0x000000018052BCA0 static TMP_InputField(); // 0x000000018052B900-0x000000018052B980 // Methods private bool isKeyboardUsingEvents(); // 0x000000018052C710-0x000000018052C750 public void SetTextWithoutNotify(string input); // 0x000000018052A2B0-0x000000018052A2C0 private void SetText(string value, bool sendCallback = true /* Metadata: 0x003A1F1D */); // 0x000000018052A2C0-0x000000018052A420 protected void ClampStringPos(ref int pos); // 0x000000018051FB20-0x000000018051FB60 protected void ClampCaretPos(ref int pos); // 0x000000018051FAC0-0x000000018051FB20 protected override void OnEnable(); // 0x0000000180527300-0x0000000180527AF0 protected override void OnDisable(); // 0x00000001805269D0-0x0000000180526D80 private void ON_TEXT_CHANGED(UnityEngine.Object obj); // 0x00000001805266B0-0x0000000180526930 [IteratorStateMachine] // 0x000000018003C020-0x000000018003C070 private IEnumerator CaretBlink(); // 0x000000018051FA50-0x000000018051FAC0 private void SetCaretVisible(); // 0x0000000180529F20-0x0000000180529F60 private void SetCaretActive(); // 0x0000000180529E70-0x0000000180529F20 protected void OnFocus(); // 0x00000001805280F0-0x0000000180528110 protected void SelectAll(); // 0x00000001805299A0-0x0000000180529A20 public void MoveTextEnd(bool shift); // 0x0000000180525990-0x0000000180525B90 public void MoveTextStart(bool shift); // 0x0000000180525B90-0x0000000180525D30 public void MoveToEndOfLine(bool shift, bool ctrl); // 0x0000000180525D30-0x0000000180526030 public void MoveToStartOfLine(bool shift, bool ctrl); // 0x0000000180526030-0x0000000180526350 private bool InPlaceEditing(); // 0x0000000180522560-0x0000000180522610 private void UpdateStringPositionFromKeyboard(); // 0x000000018052ACB0-0x000000018052B010 protected virtual void LateUpdate(); // 0x0000000180522C50-0x00000001805233A0 private bool MayDrag(PointerEventData eventData); // 0x0000000180523930-0x0000000180523A40 public virtual void OnBeginDrag(PointerEventData eventData); // 0x0000000180526930-0x0000000180526960 public virtual void OnDrag(PointerEventData eventData); // 0x0000000180526D80-0x0000000180527300 [IteratorStateMachine] // 0x000000018003C070-0x000000018003C0C0 private IEnumerator MouseDragOutsideRect(PointerEventData eventData); // 0x0000000180523A40-0x0000000180523AC0 public virtual void OnEndDrag(PointerEventData eventData); // 0x0000000180527AF0-0x0000000180527B20 public override void OnPointerDown(PointerEventData eventData); // 0x0000000180528140-0x0000000180528BE0 protected EditState KeyPressed(UnityEngine.Event evt); // 0x00000001805227B0-0x0000000180522C50 protected virtual bool IsValidChar(char c); // 0x0000000180522790-0x00000001805227B0 public void ProcessEvent(UnityEngine.Event e); // 0x0000000180529810-0x0000000180529820 public virtual void OnUpdateSelected(BaseEventData eventData); // 0x0000000180528F50-0x0000000180529120 public virtual void OnScroll(PointerEventData eventData); // 0x0000000180528BE0-0x0000000180528E20 private float GetScrollPositionRelativeToViewport(); // 0x0000000180522280-0x00000001805223E0 private string GetSelectedString(); // 0x00000001805223E0-0x00000001805224D0 private int FindNextWordBegin(); // 0x0000000180520740-0x0000000180520880 private void MoveRight(bool shift, bool ctrl); // 0x00000001805250B0-0x0000000180525990 private int FindPrevWordBegin(); // 0x0000000180520880-0x0000000180520990 private void MoveLeft(bool shift, bool ctrl); // 0x0000000180523E40-0x0000000180524610 private int LineUpCharacterPosition(int originalPos, bool goToFirstChar); // 0x0000000180523640-0x00000001805238D0 private int LineDownCharacterPosition(int originalPos, bool goToLastChar); // 0x00000001805233A0-0x0000000180523640 private int PageUpCharacterPosition(int originalPos, bool goToFirstChar); // 0x0000000180529490-0x0000000180529810 private int PageDownCharacterPosition(int originalPos, bool goToLastChar); // 0x0000000180529120-0x0000000180529490 private void MoveDown(bool shift); // 0x0000000180523AC0-0x0000000180523AD0 private void MoveDown(bool shift, bool goToLastChar); // 0x0000000180523AD0-0x0000000180523E40 private void MoveUp(bool shift); // 0x0000000180526350-0x0000000180526360 private void MoveUp(bool shift, bool goToFirstChar); // 0x0000000180526360-0x00000001805266B0 private void MovePageUp(bool shift); // 0x0000000180524B70-0x0000000180524B80 private void MovePageUp(bool shift, bool goToFirstChar); // 0x0000000180524B80-0x00000001805250B0 private void MovePageDown(bool shift); // 0x0000000180524B60-0x0000000180524B70 private void MovePageDown(bool shift, bool goToLastChar); // 0x0000000180524610-0x0000000180524B60 private void Delete(); // 0x0000000180520290-0x00000001805205A0 private void DeleteKey(); // 0x000000018051FF60-0x0000000180520290 private void Backspace(); // 0x000000018051F630-0x000000018051FA50 protected virtual void Append(string input); // 0x000000018051EEA0-0x000000018051EF50 protected virtual void Append(char input); // 0x000000018051E910-0x000000018051EEA0 private void Insert(char c); // 0x0000000180522610-0x0000000180522790 private void UpdateTouchKeyboardFromEditChanges(); // 0x000000018052B010-0x000000018052B060 private void SendOnValueChangedAndUpdateLabel(); // 0x0000000180529D50-0x0000000180529DB0 private void SendOnValueChanged(); // 0x0000000180529DB0-0x0000000180529E00 protected void SendOnEndEdit(); // 0x0000000180529A20-0x0000000180529A70 protected void SendOnSubmit(); // 0x0000000180529C10-0x0000000180529C60 protected void SendOnFocus(); // 0x0000000180529BC0-0x0000000180529C10 protected void SendOnFocusLost(); // 0x0000000180529B70-0x0000000180529BC0 protected void SendOnTextSelection(); // 0x0000000180529C60-0x0000000180529D50 protected void SendOnEndTextSelection(); // 0x0000000180529A70-0x0000000180529B70 protected void SendTouchScreenKeyboardStatusChanged(); // 0x0000000180529E00-0x0000000180529E70 protected void UpdateLabel(); // 0x000000018052A570-0x000000018052AB90 private void UpdateScrollbar(); // 0x000000018052AB90-0x000000018052ACB0 private void OnScrollbarValueChange(float value); // 0x0000000180528E20-0x0000000180528E60 private void UpdateMaskRegions(); // 0x0000000180265310-0x0000000180265320 private void AdjustTextPositionRelativeToViewport(float relativePosition); // 0x000000018051E640-0x000000018051E910 private int GetCaretPositionFromStringIndex(int stringIndex); // 0x0000000180522150-0x00000001805221E0 private int GetMinCaretPositionFromStringIndex(int stringIndex); // 0x00000001805221E0-0x0000000180522280 private int GetMaxCaretPositionFromStringIndex(int stringIndex); // 0x0000000180522150-0x00000001805221E0 private int GetStringIndexFromCaretPosition(int caretPosition); // 0x00000001805224D0-0x0000000180522560 public void ForceLabelUpdate(); // 0x0000000180520990-0x00000001805209A0 private void MarkGeometryAsDirty(); // 0x00000001805238D0-0x0000000180523930 public virtual void Rebuild(CanvasUpdate update); // 0x0000000180529820-0x00000001805298F0 public virtual void LayoutComplete(); // 0x0000000180265310-0x0000000180265320 public virtual void GraphicUpdateComplete(); // 0x0000000180265310-0x0000000180265320 private void UpdateGeometry(); // 0x000000018052A4B0-0x000000018052A570 private void AssignPositioningIfNeeded(); // 0x000000018051EF50-0x000000018051F630 private void OnFillVBO(Mesh vbo); // 0x0000000180527B20-0x00000001805280F0 private void GenerateCaret(VertexHelper vbo, Vector2 roundingOffset); // 0x00000001805209A0-0x0000000180521670 private void CreateCursorVerts(); // 0x000000018051FB60-0x000000018051FD00 private void GenerateHightlight(VertexHelper vbo, Vector2 roundingOffset); // 0x0000000180521670-0x0000000180522150 private void AdjustRectTransformRelativeToViewport(Vector2 startPosition, float height, bool isCharVisible); // 0x000000018051DE80-0x000000018051E640 protected char Validate(string text, int pos, char ch); // 0x000000018052B060-0x000000018052B900 public void ActivateInputField(); // 0x000000018051DD30-0x000000018051DE80 private void ActivateInputFieldInternal(); // 0x000000018051D830-0x000000018051DD30 public override void OnSelect(BaseEventData eventData); // 0x0000000180528E60-0x0000000180528EC0 public virtual void OnPointerClick(PointerEventData eventData); // 0x0000000180528110-0x0000000180528140 public void OnControlClick(); // 0x0000000180265310-0x0000000180265320 public void ReleaseSelection(); // 0x00000001805298F0-0x00000001805299A0 public void DeactivateInputField(bool clearSelection = false /* Metadata: 0x003A1F1E */); // 0x000000018051FD00-0x000000018051FF60 public override void OnDeselect(BaseEventData eventData); // 0x0000000180526960-0x00000001805269D0 public virtual void OnSubmit(BaseEventData eventData); // 0x0000000180528EC0-0x0000000180528F50 private void EnforceContentType(); // 0x00000001805205D0-0x0000000180520740 private void SetTextComponentWrapMode(); // 0x000000018052A1F0-0x000000018052A2B0 private void SetTextComponentRichTextMode(); // 0x000000018052A160-0x000000018052A1F0 private void SetToCustomIfContentTypeIsNot(params /* 0x0000000180014D50-0x0000000180014D60 */ ContentType[] allowedContentTypes); // 0x000000018052A420-0x000000018052A490 private void SetToCustom(); // 0x000000018052A490-0x000000018052A4B0 private void SetToCustom(CharacterValidation characterValidation); // 0x000000018052A490-0x000000018052A4B0 protected override void DoStateTransition(SelectionState state, bool instant); // 0x00000001805205A0-0x00000001805205D0 public virtual void CalculateLayoutInputHorizontal(); // 0x0000000180265310-0x0000000180265320 public virtual void CalculateLayoutInputVertical(); // 0x0000000180265310-0x0000000180265320 public void SetGlobalPointSize(float pointSize); // 0x000000018052A060-0x000000018052A160 public void SetGlobalFontAsset(TMP_FontAsset fontAsset); // 0x0000000180529F60-0x000000018052A060 } }
62.730849
223
0.813063
[ "MIT" ]
TotalJTM/PrimitierModdingFramework
Dumps/PrimitierDumpV1.0.1/TMPro/TMP_InputField.cs
30,301
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace raytracer { public partial class Form1 : Form { List<Figure> scene = new List<Figure>(); List<Light> lights = new List<Light>(); Point3D[,] points; Color[,] colormap; Point3D f; Point3D cam_normal; const float EPS = 0.0001f; public Form1() { InitializeComponent(); pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height); } public void build_scene() { // room var room = Figure.get_Hexahedron(10); room.mat = new Material(new Point3D(1, 0, 0), 0.05f, 0, 1, 0.3f, 0.4f, 0.5f, 40); scene.Add(room); // camera var cam = new Figure(room); buildColorMap(cam.sides[0].get_point(0), cam.sides[0].get_point(1), cam.sides[0].get_point(3), cam.sides[0].get_point(2), pictureBox1.Width, pictureBox1.Height); f = CalculateFocus(5, cam.sides[0].get_point(0), cam.sides[0].get_point(1), cam.sides[0].get_point(3), cam.sides[0].get_point(2)); // // lights Light l = new Light(new Point3D(-3, -3, 4.5f)); l.clr = new Point3D(new Point3D(1f, 1f, 1f)); l.amb = new Point3D(new Point3D(0.5f, 0.5f, 0.5f)); lights.Add(l); l = new Light(new Point3D(3, 3, 4.5f)); l.clr = new Point3D(new Point3D(0.5f, 0.5f, 0.5f)); l.amb = new Point3D(new Point3D(0.1f, 0.1f, 0.1f)); lights.Add(l); // silver relftive sphrere var obj = new Sphere(new Point3D(3, 0, -3), 2f); obj.set_pen(new Pen(Color.Silver)); obj.mat = new Material(new Point3D(0, 0, 0), 0.6f, 0f, 1f, 0.39225f, 0.50754f, 0.508273f, 50); scene.Add(obj); // mate icosahedron var obj2 = Figure.get_Icosahedron(2.2f); obj2.set_pen(new Pen(Color.Aquamarine)); obj2.mat = new Material(new Point3D(0, 0, 0), 0.001f, 0, 1, 0.4f, 0.6f, 1f, 30); obj2.offset(-3,0,-3); scene.Add(obj2); // bit reflictive random obj2 = Figure.get_Hexahedron(2f); obj2.set_rand_color(); obj2.mat = new Material(new Point3D(0, 0, 0), 0.3f, 0, 1, 0.2f, 0.3f, 1f, 100); obj2.offset(3, 0, 3); scene.Add(obj2); // transparent sphrere obj = new Sphere(new Point3D(0, 3, -3.9f), 1f); obj.set_pen(new Pen(Color.Gray)); obj.mat = new Material(new Point3D(0, 0, 0), 0.003f, 0.95f, 1.5f, 0.39225f, 0.50754f, 0.508273f, 50); scene.Add(obj); } public void run() { for (int i = 0; i < pictureBox1.Width; i++) { for (int j = 0; j < pictureBox1.Height; j++) { Ray r = new Ray(f, points[i, j]); r.start = points[i, j]; var c = RayTrace(r, 10,1,1); if (Math.Max(Math.Max(c.x, c.y), c.z) > 1) c = Point3D.norm(c); colormap[i, j] = Color.FromArgb((int)(255 * c.x), (int)(255 * c.y), (int)(255 * c.z)); (pictureBox1.Image as Bitmap).SetPixel(i, j, colormap[i, j]); Text = String.Format(" {0:0.00}%", ((double)(i * pictureBox1.Width + j) * 100 / (pictureBox1.Width * pictureBox1.Height))); } pictureBox1.Invalidate(); } } Point3D RayTrace(Ray r, int rec, float env = 1, float impact = 1) { bool BackToAir = false; Point3D clr = new Point3D(0, 0, 0); if (rec <= 0 || impact < EPS) return clr; Hit h = GenerateHit(r); if (!h.succes) return clr; if (Point3D.scalar(r.dir, h.normal) > 0) { h.normal = h.normal * -1; BackToAir = true ; } Point3D hit_pos = r.tpos(h.hit_point); foreach (var l in lights) { clr += Point3D.blend(h.mat.clr, l.amb * h.mat.amb_coef); if (IsVisibleLight(l.points[0], hit_pos)) clr += h.Shade(l, hit_pos,f); } if (h.mat.reflection_coef > 0) { Ray reflRay = h.Reflect(hit_pos); clr += h.mat.reflection_coef * RayTrace(reflRay,rec-1,env,impact* h.mat.reflection_coef); } if (h.mat.refraction_coef > 0) { Ray refrRay = h.Refract(hit_pos,BackToAir ? env/1 : env/h.mat.env_coef ); if(refrRay != null) clr += h.mat.refraction_coef * RayTrace(refrRay,rec-1,impact * h.mat.reflection_coef); } return clr; } Hit GenerateHit(Ray r) { float t = 0; Figure fig = null; Point3D n = null; foreach (Figure f in scene) { if (f.RayIntersection(r, out float t1, out Point3D norm)) if( (t == 0 || t1 < t) && t1 > 0) { t = t1; fig = f; n = norm; } } if (t != 0) return new Hit(t, r, n, fig.mat); else return new Hit(); } public bool IsVisibleLight(Point3D light, Point3D hit_pos) { float max_t = (light - hit_pos).length(); float min_t = 0; Ray r = new Ray(hit_pos,light); foreach (Figure f in scene) if (f.RayIntersection(r, out float t, out Point3D p) && t < max_t && t > EPS) return false; return true; } void buildColorMap(Point3D up1, Point3D up2, Point3D down1, Point3D down2, int w, int h) { points = new Point3D[w, h]; colormap = new Color[w, h]; Point3D stepup = (up2 - up1) / (w - 1); Point3D stepdown = (down2 - down1) / (w - 1); Point3D u = new Point3D(up1); Point3D d = new Point3D(down1); for (int i = 0; i < w; i++) { Point3D stepy = (u - d) / (h - 1); Point3D p = new Point3D(d); for (int j = 0; j < h; j++) { points[i, j] = p; p += stepy; } d += stepdown; u += stepup; } } Point3D CalculateFocus( float dist, Point3D up1, Point3D up2, Point3D down1, Point3D down2) { Point3D center = (up1 + up2 + down1 + down2) / 4; Point3D norm = Point3D.norm((up2 - up1)* (down1 - up1)); cam_normal = norm; center += norm * dist; return center; } private void Form1_Load(object sender, EventArgs e) { } private void Form1_Shown(object sender, EventArgs e) { build_scene(); foreach (var f in scene) f.CalculateNormals(); run(); } } }
29.764479
173
0.45635
[ "MIT" ]
Jeday/RayTracer
raytracer/Form1.cs
7,711
C#
using Akka.Actor.Internals; using Akka.TestKit; using Xunit; namespace Akka.Tests.Actor { public class ActorRefProviderSpec : AkkaSpec { [Fact] public void CanResolveActorRef() { var path = TestActor.Path.ToString(); var resolved = ((ActorSystemImpl)Sys).Provider.ResolveActorRef(path); Assert.Same(TestActor, resolved); } } }
21.789474
81
0.613527
[ "Apache-2.0" ]
HCanber/akka.net
src/core/Akka.Tests/Actor/ActorRefProviderSpec.cs
416
C#
using System.Drawing; #if __UNIFIED__ using UIKit; using Foundation; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using CGRect = global::System.Drawing.RectangleF; #endif using LoginScreen.Utils; namespace LoginScreen.Views { class CustomTextField : UITextField { UIEdgeInsets textInset = UIEdgeInsets.Zero; UIFont placeholderFont = UIFont.SystemFontOfSize (UIFont.SystemFontSize); UIColor placeholderColor = UIColor.Black.ColorWithAlpha (0.3f); public UIEdgeInsets TextInset { get { return textInset; } set { if (!value.Equals (textInset)) { textInset = value; SetNeedsDisplay (); } } } public UIFont PlaceholderFont { get { return placeholderFont; } set { if (value != placeholderFont) { placeholderFont = value; SetNeedsDisplay (); } } } public UIColor PlaceholderColor { get { return placeholderColor; } set { if (value != placeholderColor) { placeholderColor = value; SetNeedsDisplay (); } } } public override CGRect TextRect (CGRect forBounds) { return base.TextRect (forBounds).ApplyInsets (TextInset); } public override CGRect EditingRect (CGRect forBounds) { return base.EditingRect (forBounds).ApplyInsets (TextInset); } public override void DrawPlaceholder (CGRect rect) { if (PlaceholderColor != null && PlaceholderFont != null && Placeholder != null) { PlaceholderColor.SetFill (); new NSString (Placeholder).DrawString (rect, PlaceholderFont, UILineBreakMode.TailTruncation); } } } }
20.727273
98
0.694236
[ "MIT" ]
4brunu/XamarinComponents
XPlat/LoginScreen/source/LoginScreen.iOS/Views/CustomTextField.cs
1,596
C#
using bcdevexchange.Service; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; namespace bcdevexchange { public class Startup { private readonly ILogger logger; public Startup(IConfiguration configuration, ILogger<Startup> logger) { Configuration = configuration; this.logger = logger; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddSingleton(typeof(IEventBriteService), typeof(EventBriteService)); services.AddSingleton<IMemoryCache>(new MemoryCache(new MemoryCacheOptions())); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddHealthChecks().AddCheck("Webserver is running!", () => HealthCheckResult.Healthy("Ok")); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); logger.LogInformation("In Development environment"); } else { app.UseExceptionHandler("/Home/Error"); app.UseStatusCodePagesWithRedirects("/Home/Error?code={0}"); app.UseHsts(); } app.UseHealthChecks("/hc", new HealthCheckOptions { AllowCachingResponses = false }); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
40.791045
120
0.622027
[ "Apache-2.0" ]
bcgov/bcdevexchange
bcdevexchange/Startup.cs
2,735
C#
using System; using System.Reflection; using FubuMVC.Core; using FubuMVC.Validation.SemanticModel; namespace FubuMVC.Validation.Dsl { public class ViewModelTypeScanningExpression<TTypeInAssembly> { private readonly Assembly _assembly; private readonly ValidationConfiguration _validationConfiguration; public ViewModelTypeScanningExpression(ValidationConfiguration validationConfiguration) { _validationConfiguration = validationConfiguration; _assembly = typeof(TTypeInAssembly).Assembly; } public void Where(Func<Type, bool> evalTypeFunc) { _assembly.GetExportedTypes().Each(type => { if (type.IsAbstract) return; if (type.IsValueType) return; if (evalTypeFunc(type)) _validationConfiguration.DiscoveredTypes.AddDiscoveredType(type); }); } } }
31.129032
106
0.648705
[ "Apache-2.0" ]
Anupam-/fubumvc-contrib
Addons/FubuMVC.Validation/src/FubuMVC.Validation/Dsl/ViewModelTypeScanningExpression.cs
965
C#
using EngineeringUnits.Units; namespace EngineeringUnits { public partial class ApparentEnergy : BaseUnit { public ApparentEnergy() { } public ApparentEnergy(decimal value, ApparentEnergyUnit selectedUnit) : base(value, selectedUnit.Unit) { } public ApparentEnergy(double value, ApparentEnergyUnit selectedUnit) : base(value, selectedUnit.Unit) { } public ApparentEnergy(int value, ApparentEnergyUnit selectedUnit) : base(value, selectedUnit.Unit) { } public ApparentEnergy(UnknownUnit value) : base(value) { } public ApparentEnergy(UnknownUnit value, ApparentEnergyUnit selectedUnit) : base(value, selectedUnit.Unit) { } public static ApparentEnergy From(double value, ApparentEnergyUnit unit) => new(value, unit); public double As(ApparentEnergyUnit ReturnInThisUnit) => ToTheOutSideDouble(ReturnInThisUnit.Unit); public ApparentEnergy ToUnit(ApparentEnergyUnit selectedUnit) => new(ToTheOutSide(selectedUnit.Unit), selectedUnit); public static ApparentEnergy Zero => new(0, ApparentEnergyUnit.SI); public static implicit operator ApparentEnergy(UnknownUnit Unit) => new(Unit, ApparentEnergyUnit.SI); public static implicit operator ApparentEnergy(int zero) { if (zero != 0) throw new WrongUnitException($"You need to give it a unit unless you set it to 0 (zero)!"); return Zero; } } }
41.8
124
0.706767
[ "MIT" ]
MadsKirkFoged/EngineeringUnits
EngineeringUnits/CombinedUnits/ApparentEnergy/ApparentEnergy.cs
1,465
C#
using Android.Hardware.Camera2; namespace Media.Plugin.Custom.Android.Abstractions { internal interface ICaptureState { void Work<TState>(CameraCaptureSession session, CaptureRequest request, CaptureResult result, ref TState captureState) where TState : class; } }
27.4
120
0.80292
[ "MIT" ]
ProactiveSoft/Camera
src/Media.Plugin.Custom.Android/Abstractions/ICaptureState.cs
276
C#
using log4net; using Meowv.Blog.ToolKits.Helper; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Meowv.Blog.HttpApi.Hosting.Filters { /// <summary> /// 异常处理 /// </summary> public class MeowvBlogExceptionFilter : IExceptionFilter { private readonly ILog _log; public MeowvBlogExceptionFilter() { _log = LogManager.GetLogger(typeof(MeowvBlogExceptionFilter)); } public void OnException(ExceptionContext context) { _log.Error($"{context.HttpContext.Request.Path}|{context.Exception.Message}", context.Exception); } } }
25.785714
109
0.677285
[ "MIT" ]
itbetaw/Meowv.Blog
src/Meowv.Blog.HttpApi.Hosting/Filters/MeowvBlogExceptionFilter.cs
732
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 ssm-2014-11-06.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.SimpleSystemsManagement.Model { /// <summary> /// This is the response object from the RegisterTaskWithMaintenanceWindow operation. /// </summary> public partial class RegisterTaskWithMaintenanceWindowResponse : AmazonWebServiceResponse { private string _windowTaskId; /// <summary> /// Gets and sets the property WindowTaskId. /// <para> /// The id of the task in the Maintenance Window. /// </para> /// </summary> public string WindowTaskId { get { return this._windowTaskId; } set { this._windowTaskId = value; } } // Check to see if WindowTaskId property is set internal bool IsSetWindowTaskId() { return this._windowTaskId != null; } } }
30.428571
101
0.671362
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/RegisterTaskWithMaintenanceWindowResponse.cs
1,704
C#
using System; using System.Collections.Generic; using System.Text; using EventManager.Common; using EventManager.Core.Data; using EventManager.Core.Entities; using Microsoft.Azure.Documents.Client; namespace EventManger.Data.Repository { public class Repository<T> : IRepository<T> where T : BaseEntity { private DocumentClient _client = new DocumentClient(new Uri(Common.EndpointUri), Common.PrimaryKey); public void Insert(T entity) { throw new NotImplementedException(); } public void InsertRange(List<T> entities) { throw new NotImplementedException(); } public T Get(int id) { throw new NotImplementedException(); } public List<T> GetAll() { throw new NotImplementedException(); } public void Update(T entity) { throw new NotImplementedException(); } public void Remove(int id) { throw new NotImplementedException(); } } }
23.8
108
0.609711
[ "MIT" ]
alexand34/EventManager
EventManager/EventManger.Data/Repository/Repository.cs
1,073
C#
using Microsoft.Bot.Schema; using Microsoft.WindowsAzure.Storage.Table; using System; using System.Globalization; namespace Underscore.Bot.Models.Azure { public enum PartyEntityType { Bot, User, Aggregation, PendingRequest, Owner, Client } /// <summary> /// Table storage entity that represents a party. /// </summary> public class PartyEntity : TableEntity { public string ServiceUrl { get; set; } public string ChannelId { get; set; } // Channel account public string ChannelAccountId { get; set; } public string ChannelAccountName { get; set; } // Conversation account public string ConversationAccountId { get; set; } public string ConversationAccountName { get; set; } public string PartyEntityType { get; set; } public string ConnectionRequestTime { get; set; } public string ConnectionEstablishedTime { get; set; } protected virtual string DateTimeFormatSpecifier { get { return "O"; } } public PartyEntity() { } public PartyEntity(string partitionKey, string rowKey) { PartitionKey = partitionKey; RowKey = rowKey; } public PartyEntity(Party party, PartyEntityType partyEntityType) { PartitionKey = CreatePartitionKey(party, partyEntityType); RowKey = CreateRowKey(party); ChannelId = party.ChannelId; ServiceUrl = party.ServiceUrl; PartyEntityType = partyEntityType.ToString(); if (party.ChannelAccount != null) { ChannelAccountId = party.ChannelAccount.Id; ChannelAccountName = party.ChannelAccount.Name; } if (party.ConversationAccount != null) { ConversationAccountId = party.ConversationAccount.Id; ConversationAccountName = party.ConversationAccount.Name; } ConnectionRequestTime = DateTimeToString(party.ConnectionRequestTime); ConnectionEstablishedTime = DateTimeToString(party.ConnectionEstablishedTime); } public static string CreatePartitionKey(Party party, PartyEntityType partyEntityType) { if (party.ChannelAccount != null) { return $"{party.ChannelAccount.Id}|{partyEntityType.ToString()}"; } return $"{party.ChannelId}|{partyEntityType.ToString()}"; } public static string CreateRowKey(Party party) { if (party.ConversationAccount != null) { return party.ConversationAccount.Id; } return party.ServiceUrl; } public virtual Party ToParty() { ChannelAccount channelAccount = string.IsNullOrEmpty(ChannelAccountId) ? null : new ChannelAccount(ChannelAccountId, ChannelAccountName); ConversationAccount conversationAccount = new ConversationAccount(null, ConversationAccountId, ConversationAccountName); Party party = new Party(ServiceUrl, ChannelId, channelAccount, conversationAccount) { ConnectionRequestTime = DateTimeFromString(ConnectionRequestTime), ConnectionEstablishedTime = DateTimeFromString(ConnectionEstablishedTime) }; return party; } protected virtual string DateTimeToString(DateTime dateTime) { return dateTime.ToString(DateTimeFormatSpecifier); } protected virtual DateTime DateTimeFromString(string dateTimeAsString) { return DateTime.ParseExact(dateTimeAsString, DateTimeFormatSpecifier, CultureInfo.InvariantCulture); } } }
30.828125
132
0.608464
[ "MIT" ]
NT-D/TravelBotv4
TravelBotv4/BotMessageRouting/Models/Azure/PartyEntity.cs
3,948
C#
using App.Metrics; using App.Metrics.Counter; using App.Metrics.Gauge; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Neyro.AppMetrics.Extensions { public sealed class EventCountersCollector : EventListener, IHostedService { private readonly Dictionary<string, GaugeOptions> _gauges = new Dictionary<string, GaugeOptions>(); private readonly Dictionary<string, CounterOptions> _counters = new Dictionary<string, CounterOptions>(); private readonly EventCountersCollectorOptions _options; private readonly List<EventSource> _handledSources = new List<EventSource>(); private readonly IMetricsRoot _metrics; /// <summary> /// Create instance of EventCountersCollector /// </summary> /// <param name="metricsRoot">Root of AppMetrics</param> /// <param name="options">Options for EventCountersCollector</param> public EventCountersCollector(IMetricsRoot metricsRoot, EventCountersCollectorOptions options) { _metrics = metricsRoot ?? throw new ArgumentNullException(nameof(metricsRoot)); _options = options ?? throw new ArgumentNullException(nameof(options)); if (_options.RefreshIntervalSec < 0) throw new ArgumentOutOfRangeException($"{nameof(options)}.{nameof(options.RefreshIntervalSec)}"); if (_options.EnabledSources == null) throw new ArgumentNullException($"{nameof(options)}.{nameof(options.EnabledSources)}"); if (_options.EnabledSources.Length == 0) throw new ArgumentOutOfRangeException($"{nameof(options)}.{nameof(options.EnabledSources)}"); EventSourceCreated += RuntimeEventListener_EventSourceCreated; } /// <summary> /// Create instance of EventCountersCollector /// </summary> /// <param name="metricsRoot">Root of AppMetrics</param> /// <param name="options">OptionsSnapshot for EventCountersCollector</param> public EventCountersCollector(IMetricsRoot metricsRoot, IOptions<EventCountersCollectorOptions> options) : this(metricsRoot, options?.Value ?? throw new ArgumentNullException(nameof(options))) { } public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; public Task StopAsync(CancellationToken cancellationToken) { foreach (var source in _handledSources) DisableEvents(source); return Task.CompletedTask; } protected override void OnEventWritten(EventWrittenEventArgs eventData) { if (!"EventCounters".Equals(eventData.EventName)) return; if (!(eventData.Payload?[0] is IDictionary<string, object> payloadFields)) return; var payload = new CounterPayload(payloadFields, _options.SetTagsFromMetadata); if (_options.IntervalSecFilter != null && payload.IntervalSec.HasValue && _options.IntervalSecFilter.TryGetValue(eventData.EventSource.Name, out var filter) && payload.IntervalSec.Value < filter) return; switch (payload.Type) { case CounterType.Mean: RegisterGaugeValue(payload, eventData.EventSource.Name); break; case CounterType.Increment: RegisterCounterValue(payload, eventData.EventSource.Name); break; default: break; } } private void RuntimeEventListener_EventSourceCreated(object? sender, EventSourceCreatedEventArgs e) { var eventSource = e.EventSource; if (eventSource == null) return; if (!_options.EnabledSources.Contains(eventSource.Name)) return; EnableEvents(eventSource, EventLevel.Verbose, EventKeywords.All, new Dictionary<string, string?> { ["EventCounterIntervalSec"] = _options.RefreshIntervalSec.ToString() }); _handledSources.Add(eventSource); } private void RegisterCounterValue(CounterPayload payload, string eventSourceName) { var countersCacheKey = eventSourceName + payload.Key; if (!_counters.TryGetValue(countersCacheKey, out var counter)) { counter = new CounterOptions { Context = eventSourceName, Name = payload.Name, ResetOnReporting = true }; if (_options.SetTagsFromMetadata && payload.Metadata != null) { counter.Tags = new MetricTags(payload.Metadata.Keys.ToArray(), payload.Metadata.Values.ToArray()); } _counters.Add(countersCacheKey, counter); } _metrics.Measure.Counter.Increment(counter, (long)payload.Value); } private void RegisterGaugeValue(CounterPayload payload, string eventSourceName) { var gaugesCacheKey = eventSourceName + payload.Key; if (!_gauges.TryGetValue(gaugesCacheKey, out var gauge)) { gauge = new GaugeOptions { Context = eventSourceName, Name = payload.Name }; if (_options.SetTagsFromMetadata && payload.Metadata != null) { gauge.Tags = new MetricTags(payload.Metadata.Keys.ToArray(), payload.Metadata.Values.ToArray()); } _gauges.Add(gaugesCacheKey, gauge); } _metrics.Measure.Gauge.SetValue(gauge, payload.Value); } } }
41.205479
208
0.619681
[ "Apache-2.0" ]
neyromant/Neyro.AppMetrics.Extensions
src/Neyro.AppMetrics.Extensions.EventCountersCollector/Neyro.AppMetrics.Extensions.EventCountersCollector/EventCountersCollector.cs
6,018
C#
using System.IO; #nullable enable namespace MaxLib.WebServer.WebSocket.Echo { public class EchoEndpoint : WebSocketEndpoint<EchoConnection> { public override string? Protocol => null; protected override EchoConnection CreateConnection(Stream stream, HttpRequestHeader header) { return new EchoConnection(stream); } } }
22.294118
99
0.688654
[ "MIT" ]
Garados007/MaxLib.WebServer
MaxLib.WebServer.WebSocket.Echo/EchoEndpoint.cs
381
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("SmartLab.Domain")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SmartLab.Domain")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("51a6df08-a628-4eb7-9a00-9deaa9514abe")] // 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.783784
84
0.747496
[ "MIT" ]
vasylenkoArtem/AccountManagementSystem
Services/Application/AMS.Domain/Properties/AssemblyInfo.cs
1,401
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WMPLib; namespace Ropositorio { public class ReprodutorMusical { #region Atributos IWMPPlaylist playlist; IWMPMedia media; WindowsMediaPlayer wplayer; ListaMusica playList_LM; #endregion #region Construtores // O construtor somente inicializa atributos public ReprodutorMusical() { string nome_lista = "lista de reprodução"; wplayer = new WindowsMediaPlayer(); playlist = wplayer.playlistCollection.newPlaylist(nome_lista); playList_LM = new ListaMusica(); wplayer.currentPlaylist.name = nome_lista; wplayer.settings.autoStart = false; } #endregion #region PlayList /* Método recebe um objeto do tipo ListaMusica e * cria uma playList por meio dele */ public ListaMusica PlayList { set { playlist.clear(); wplayer.currentPlaylist = playlist; if (value.Count > 0) { // Adiciona as musicas na playList foreach (Musica mus in value) { media = wplayer.newMedia(mus.Caminho); playlist.appendItem(media); } wplayer.currentPlaylist = playlist; playList_LM = value; } } } #endregion #region Nome public string Nome { get { return wplayer.currentPlaylist.name; } set { //playList_LM.Nome = value; wplayer.currentPlaylist.name = value; } } #endregion #region Play // Método que da play na lista de música public void Play() { if (wplayer.playState.ToString().Equals(WMPPlayState.wmppsUndefined.ToString())) { // Verifica se a lista não está vazia if (wplayer.currentPlaylist.count > 0) { wplayer.controls.play(); } else { MessageBox.Show("Lista de Reprodução não contem músicas"); } } else { wplayer.controls.play(); } } #endregion #region Pause // Método que pausa a lista de músicas public void Pause() { wplayer.controls.pause(); } #endregion #region Next // Método que avança uma música public void Next() { wplayer.controls.next(); } #endregion #region Stop //Método que para a música public void Stop() { wplayer.controls.stop(); } #endregion #region Previous // Método que retrocede uma música public void Previous() { wplayer.controls.previous(); } #endregion #region Limpa PlayList public void LimpaPlayList() { playlist.clear(); wplayer.currentPlaylist = playlist; } #endregion #region Musica public Musica Musica { set { media = wplayer.newMedia(value.Caminho); wplayer.currentPlaylist.appendItem(media); playList_LM.Add(value); } } #endregion #region Volume public int Volume { get { return wplayer.settings.volume; } set { wplayer.settings.volume = value; } } #endregion } }
24.636364
92
0.477245
[ "Apache-2.0" ]
Berselli/C-Sharp
Quantum Player/Ropositorio/ReprodutorMusical.cs
4,087
C#
using System; using System.Collections.Generic; using System.Globalization; using Xunit; using Xunit.Extensions; namespace NuGet.Test { public class SemanticVersionTest { [Theory] [PropertyData("ConstructorData")] public void StringConstructorParsesValuesCorrectly(string version, Version versionValue, string specialValue) { // Act SemanticVersion semanticVersion = new SemanticVersion(version); // Assert Assert.Equal(versionValue, semanticVersion.Version); Assert.Equal(specialValue, semanticVersion.SpecialVersion); Assert.Equal(version, semanticVersion.ToString()); } public static IEnumerable<object[]> ConstructorData { get { yield return new object[] { "1.0.0", new Version("1.0.0.0"), "" }; yield return new object[] { "2.3-alpha", new Version("2.3.0.0"), "alpha" }; yield return new object[] { "3.4.0.3-RC-3", new Version("3.4.0.3"), "RC-3" }; } } [Fact] public void ParseThrowsIfStringIsNullOrEmpty() { ExceptionAssert.ThrowsArgNullOrEmpty(() => SemanticVersion.Parse(version: null), "version"); ExceptionAssert.ThrowsArgNullOrEmpty(() => SemanticVersion.Parse(version: String.Empty), "version"); } [Theory] [InlineData("1")] [InlineData("1beta")] [InlineData("1.2Av^c")] [InlineData("1.2..")] [InlineData("1.2.3.4.5")] [InlineData("1.2.3.Beta")] [InlineData("1.2.3.4This version is full of awesomeness!!")] [InlineData("So.is.this")] [InlineData("1.34.2Alpha")] [InlineData("1.34.2Release Candidate")] [InlineData("1.4.7-")] [InlineData("1.4.7-.")] [InlineData("1.4.7-+")] [InlineData("1.4.7-*")] [InlineData("1.4.7+*")] [InlineData("1.4.7-AA.01^")] [InlineData("1.4.7-AA.0A^")] [InlineData("1.4.7-A^A")] [InlineData("1.4.7+AA.01^")] public void ParseThrowsIfStringIsNotAValidSemVer(string versionString) { ExceptionAssert.ThrowsArgumentException(() => SemanticVersion.Parse(versionString), "version", String.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid version string.", versionString)); } public static IEnumerable<object[]> LegacyVersionData { get { yield return new object[] { "1.022", new SemanticVersion(new Version("1.22.0.0"), "") }; yield return new object[] { "23.2.3", new SemanticVersion(new Version("23.2.3.0"), "") }; yield return new object[] { "1.3.42.10133", new SemanticVersion(new Version("1.3.42.10133"), "") }; } } [Theory] [PropertyData("LegacyVersionData")] public void ParseReadsLegacyStyleVersionNumbers(string versionString, SemanticVersion expected) { // Act var actual = SemanticVersion.Parse(versionString); // Assert Assert.Equal(expected.Version, actual.Version); Assert.Equal(expected.SpecialVersion, actual.SpecialVersion); } public static IEnumerable<object[]> SemVerData { get { yield return new object[] { "1.022-Beta", new SemanticVersion(new Version("1.22.0.0"), "Beta") }; yield return new object[] { "23.2.3-Alpha", new SemanticVersion(new Version("23.2.3.0"), "Alpha") }; yield return new object[] { "1.3.42.10133-PreRelease", new SemanticVersion(new Version("1.3.42.10133"), "PreRelease") }; yield return new object[] { "1.3.42.200930-RC-2", new SemanticVersion(new Version("1.3.42.200930"), "RC-2") }; yield return new object[] { "1.3.42.200930-RC.2", new SemanticVersion(new Version("1.3.42.200930"), "RC.2") }; yield return new object[] { "1.3.42.200930-RC.2", new SemanticVersion(new Version("1.3.42.200930"), "RC.2", "meta.data.1.2-a") }; yield return new object[] { "23.2.3+Alpha", new SemanticVersion(new Version("23.2.3.0"), null, "Alpha") }; yield return new object[] { "1.0.0--", new SemanticVersion(new Version("1.0.0"), "-") }; yield return new object[] { "1.0.0+-", new SemanticVersion(new Version("1.0.0"), null, "-") }; } } [Theory] [PropertyData("SemVerData")] public void ParseReadsSemverAndHybridSemverVersionNumbers(string versionString, SemanticVersion expected) { // Act var actual = SemanticVersion.Parse(versionString); // Assert Assert.Equal(expected.Version, actual.Version); Assert.Equal(expected.SpecialVersion, actual.SpecialVersion); } public static IEnumerable<object[]> SemVerWithWhiteSpace { get { yield return new object[] { " 1.022-Beta", new SemanticVersion(new Version("1.22.0.0"), "Beta") }; yield return new object[] { "23.2.3-Alpha ", new SemanticVersion(new Version("23.2.3.0"), "Alpha") }; yield return new object[] { " 1.3.42.10133-PreRelease ", new SemanticVersion(new Version("1.3.42.10133"), "PreRelease") }; yield return new object[] { "23.2.3-1.2 ", new SemanticVersion(new Version("23.2.3.0"), "1.2", "Alpha") }; } } [Theory] [PropertyData("SemVerWithWhiteSpace")] public void ParseIgnoresLeadingAndTrailingWhitespace(string versionString, SemanticVersion expected) { // Act var actual = SemanticVersion.Parse(versionString); // Assert Assert.Equal(expected.Version, actual.Version); Assert.Equal(expected.SpecialVersion, actual.SpecialVersion); } [Theory] [InlineData("1.0", "1.0.1")] [InlineData("1.23", "1.231")] [InlineData("1.4.5.6", "1.45.6")] [InlineData("1.4.5.6", "1.4.5.60")] [InlineData("1.01", "1.10")] [InlineData("1.01-alpha", "1.10-beta")] [InlineData("1.01.0-RC-1", "1.10.0-rc-2")] [InlineData("1.01-RC-1", "1.01")] [InlineData("1.01", "1.2-preview")] [InlineData("1.01-9", "1.01-10")] public void SemVerLessThanAndGreaterThanOperatorsWorks(string versionA, string versionB) { // Arrange var itemA = new SemanticVersion(versionA); var itemB = new SemanticVersion(versionB); object objectB = itemB; // Act and Assert Assert.True(itemA < itemB); Assert.True(itemA <= itemB); Assert.True(itemB > itemA); Assert.True(itemB >= itemA); Assert.False(itemA.Equals(itemB)); Assert.False(itemA.Equals(objectB)); } [Theory] [InlineData(new object[] { 1 })] [InlineData(new object[] { "1.0.0" })] [InlineData(new object[] { new object[0] })] public void EqualsReturnsFalseIfComparingANonSemVerType(object other) { // Arrange var semVer = new SemanticVersion("1.0.0"); // Act and Assert Assert.False(semVer.Equals(other)); } [Fact] public void SemVerThrowsIfLeftHandExpressionForCompareOperatorsIsNull() { // Arrange SemanticVersion itemA = null; SemanticVersion itemB = new SemanticVersion("1.0"); // Disable this warning since it complains on mono #pragma warning disable 0219 // Act and Assert ExceptionAssert.ThrowsArgNull(() => { bool val = itemA < itemB; }, "version1"); ExceptionAssert.ThrowsArgNull(() => { bool val = itemA <= itemB; }, "version1"); ExceptionAssert.ThrowsArgNull(() => { bool val = itemA > itemB; }, "version1"); ExceptionAssert.ThrowsArgNull(() => { bool val = itemA >= itemB; }, "version1"); #pragma warning restore 0219 } [Theory] [InlineData("1.0", "1.0.0.0")] [InlineData("1.23.01", "1.23.1")] [InlineData("1.45.6", "1.45.6.0")] [InlineData("1.45.6-Alpha", "1.45.6-Alpha")] [InlineData("1.6.2-BeTa", "1.6.02-beta")] [InlineData("22.3.07 ", "22.3.07")] [InlineData("1.0+a", "1.0.0.0+a")] [InlineData("1.0-1.1+a", "1.0.0.0-1.1+a")] public void SemVerEqualsOperatorWorks(string versionA, string versionB) { // Arrange var itemA = new SemanticVersion(versionA); var itemB = new SemanticVersion(versionB); object objectB = itemB; // Act and Assert Assert.True(itemA == itemB); Assert.True(itemA.Equals(itemB)); Assert.True(itemA.Equals(objectB)); Assert.True(itemA <= itemB); Assert.True(itemB == itemA); Assert.True(itemB >= itemA); } [Fact] public void SemVerEqualityComparisonsWorkForNullValues() { // Arrange SemanticVersion itemA = null; SemanticVersion itemB = null; // Act and Assert Assert.True(itemA == itemB); Assert.True(itemB == itemA); Assert.True(itemA <= itemB); Assert.True(itemB <= itemA); Assert.True(itemA >= itemB); Assert.True(itemB >= itemA); } [Theory] [InlineData("1.0")] [InlineData("1.0.0")] [InlineData("1.0.0.0")] [InlineData("1.0-alpha")] [InlineData("1.0.0-b")] [InlineData("3.0.1.2")] [InlineData("2.1.4.3-pre-1")] public void ToStringReturnsOriginalValue(string version) { // Act SemanticVersion semVer = new SemanticVersion(version); // Assert Assert.Equal(version, semVer.ToString()); Assert.Equal(version, semVer.ToOriginalString()); } [Theory] [InlineData("1.0.0+meta")] [InlineData("1.0.0+meta.1-2")] [InlineData("1.0.0.0+meta.1-2")] [InlineData("1.0.0.0-1.2+meta.1-2")] public void ToStringReturnsDropsMetadata(string version) { // Act SemanticVersion semVer = new SemanticVersion(version); // Assert Assert.Equal(-1, semVer.ToString().IndexOf('+')); Assert.Equal(-1, semVer.ToNormalizedString().IndexOf('+')); } public static IEnumerable<object[]> ToStringFromVersionData { get { yield return new object[] { new Version("1.0"), null, "1.0" }; yield return new object[] { new Version("1.0.3.120"), String.Empty, "1.0.3.120" }; yield return new object[] { new Version("1.0.3.120"), "alpha", "1.0.3.120-alpha" }; yield return new object[] { new Version("1.0.3.120"), "rc-2", "1.0.3.120-rc-2" }; yield return new object[] { new Version("1.0.3.120"), "rc.2", "1.0.3.120-rc.2" }; } } [Theory] [PropertyDataAttribute("ToStringFromVersionData")] public void ToStringConstructedFromVersionAndSpecialVersionConstructor(Version version, string specialVersion, string expected) { // Act SemanticVersion semVer = new SemanticVersion(version, specialVersion); // Assert Assert.Equal(expected, semVer.ToString()); } [Fact] public void TryParseStrictParsesStrictVersion() { // Arrange var versionString = "1.3.2-CTP-2-Refresh-Alpha"; // Act SemanticVersion version; bool result = SemanticVersion.TryParseStrict(versionString, out version); // Assert Assert.True(result); Assert.Equal(new Version("1.3.2.0"), version.Version); Assert.Equal("CTP-2-Refresh-Alpha", version.SpecialVersion); } [Theory] [InlineData("2.7")] [InlineData("1.3.4.5")] [InlineData("1.3-alpha")] [InlineData("1.3 .4")] [InlineData("2.3.18.2-a")] public void TryParseStrictReturnsFalseIfVersionIsNotStrictSemVer(string version) { // Act SemanticVersion semanticVersion; bool result = SemanticVersion.TryParseStrict(version, out semanticVersion); // Assert Assert.False(result); Assert.Null(semanticVersion); } [Theory] [InlineData("1.2.4.5", new string[] { "1", "2", "4", "5" })] [InlineData("01.02.4.5-gamma", new string[] { "01", "02", "4", "5" })] [InlineData("1.02.3", new string[] { "1", "02", "3", "0" })] [InlineData("1.02.3-beta", new string[] { "1", "02", "3", "0" })] [InlineData("00100.02", new string[] { "00100", "02", "0", "0" })] [InlineData("00100.02-alpha", new string[] { "00100", "02", "0", "0" })] [InlineData("00100.02-alpha.1+2", new string[] { "00100", "02", "0", "0" })] public void TestGetOriginalVersionComponents( string originalVersion, string[] expectedComponents) { // Arrange var semVer = new SemanticVersion(originalVersion); // Act string[] components = semVer.GetOriginalVersionComponents(); // Assert Assert.Equal(expectedComponents, components); } [Theory] [InlineData("1.2.4.5", new string[] { "1", "2", "4", "5" })] [InlineData("1.02.3", new string[] { "1", "2", "3", "0" })] [InlineData("00100.02", new string[] { "100", "2", "0", "0" })] public void TestGetOriginalVersionComponentsWhenPassingVersion( string originalVersion, string[] expectedComponents) { // Arrange var version = new Version(originalVersion); var semVer = new SemanticVersion(version); // Act string[] components = semVer.GetOriginalVersionComponents(); // Assert Assert.Equal(expectedComponents, components); } [Theory] [InlineData("1.0", "1.0.0")] [InlineData("1.7", "1.7.0")] [InlineData("1.0.0.0", "1.0.0")] [InlineData("1.0.0", "1.0.0")] [InlineData("1.2.3", "1.2.3")] [InlineData("1.2.03", "1.2.3")] [InlineData("1.2.0.4", "1.2.0.4")] [InlineData("1.2.3.4", "1.2.3.4")] [InlineData("1.2-special", "1.2.0-special")] [InlineData("1.2.3-special", "1.2.3-special")] [InlineData("1.2.3.5-special", "1.2.3.5-special")] [InlineData("1.2.0.5-special", "1.2.0.5-special")] [InlineData("1.2.0.5-special.1", "1.2.0.5-special.1")] [InlineData("1.2.0.5-special.1+a", "1.2.0.5-special.1")] public void NormalizeVersion_NormalizesVersionTo3Digits(string versionString, string expected) { // Arrange var version = new SemanticVersion(versionString); // Act var result = version.ToNormalizedString(); // Assert Assert.Equal(result, expected); } [Theory] [InlineData("1.0.0")] [InlineData("0.0.1")] [InlineData("1.2.3")] [InlineData("1.2.3-alpha")] [InlineData("1.2.3-X.yZ.3.234.243.32423423.4.23423.4324.234.234.3242")] [InlineData("1.2.3-X.yZ.3.234.243.32423423.4.23423+METADATA")] [InlineData("1.2.3-X.y3+0")] [InlineData("1.2.3-X+0")] [InlineData("1.2.3+0")] [InlineData("1.2.3-0")] public void ParseSemanticVersionStrict(string versionString) { // Act SemanticVersion semVer = null; SemanticVersion.TryParseStrict(versionString, out semVer); // Assert Assert.Equal<string>(versionString, semVer.ToFullString()); Assert.Equal<string>(semVer.ToNormalizedString(), semVer.ToString()); } [Theory] [InlineData("1.2.3")] [InlineData("1.2.3+0")] [InlineData("1.2.3+321")] [InlineData("1.2.3+XYZ")] public void SemanticVersionStrictEquality(string versionString) { // Act SemanticVersion main = null; SemanticVersion.TryParseStrict("1.2.3", out main); SemanticVersion semVer = null; SemanticVersion.TryParseStrict(versionString, out semVer); // Assert Assert.True(main.Equals(semVer)); Assert.True(semVer.Equals(main)); Assert.True(main.GetHashCode() == semVer.GetHashCode()); } [Theory] [InlineData("1.2.3-alpha")] [InlineData("1.2.3-alpha+0")] [InlineData("1.2.3-alpha+10")] [InlineData("1.2.3-alpha+beta")] public void SemanticVersionStrictEqualityPreRelease(string versionString) { // Act SemanticVersion main = null; SemanticVersion.TryParseStrict("1.2.3-alpha", out main); SemanticVersion semVer = null; SemanticVersion.TryParseStrict(versionString, out semVer); // Assert Assert.True(main.Equals(semVer)); Assert.True(semVer.Equals(main)); Assert.True(main.GetHashCode() == semVer.GetHashCode()); } [Theory] [InlineData("2.7")] [InlineData("1.3.4.5")] [InlineData("1.3-alpha")] [InlineData("1.3 .4")] [InlineData("2.3.18.2-a")] [InlineData("1.2.3-A..B")] [InlineData("01.2.3")] [InlineData("1.02.3")] [InlineData("1.2.03")] [InlineData(".2.03")] [InlineData("1.2.")] [InlineData("1.2.3-a$b")] [InlineData("a.b.c")] [InlineData("1.2.3-00")] [InlineData("1.2.3-A.00.B")] public void TryParseStrictReturnsFalseIfVersionIsNotStrictSemVer200(string version) { // Act SemanticVersion semanticVersion; var result = SemanticVersion.TryParseStrict(version, out semanticVersion); // Assert Assert.False(result); Assert.Null(semanticVersion); } [Theory] [InlineData("1.0.0+alpha", "alpha")] [InlineData("1.0.0-1.1+a", "a")] public void MetadataTest(string version, string metadata) { // Act SemanticVersion semVer = new SemanticVersion(version); // Assert Assert.Equal(metadata, semVer.Metadata); } } }
38.867735
146
0.530498
[ "ECL-2.0", "Apache-2.0" ]
NuGet/NuGet2
test/Core.Test/SemanticVersionTest.cs
19,397
C#
using System.Collections.Generic; using Microsoft.IdentityModel.Claims; namespace Rebus.IdentityClaims { public interface IIdentityClaimsResolver { IEnumerable<Claim> GetClaims(); } }
19.909091
45
0.69863
[ "Apache-2.0" ]
martijnburgers/NET40-Rebus-0.72.0-with-DataBus-Poc
src/Rebus.Identities/IIdentityClaimsResolver.cs
221
C#
using Newtonsoft.Json; namespace Battlerite.NET.Rest.DTOs.Matches { public class Stats { [JsonProperty("mapID")] public string MapId { get; set; } } }
18
42
0.622222
[ "MIT" ]
RethoughtSolutions/Battlerite.NET
Battlerite.NET.Rest/DTOs/Matches/Stats.cs
182
C#
using System; namespace ClassLibrary1 { public class PersonPrinter { public Person Person { get; } public PersonPrinter(Person person) { Person = person ?? throw new ArgumentNullException(nameof(person)); } public void PrintPerson() { Console.WriteLine(Person.ToString()); } } }
19.684211
79
0.569519
[ "MIT" ]
Martinus82/Learning2021
InheritanceHierarchy/PersonPrinter.cs
376
C#
using System; using System.ComponentModel.DataAnnotations; using Swan.AspNetCore.Models; namespace Swan.AspNetCore.Test.Mocks { public class AuditTrailMock : IAuditTrailEntry { [Key] public int AuditId { get; set; } public string UserId { get; set; } public string TableName { get; set; } public int Action { get; set; } public string JsonBody { get; set; } public DateTime DateCreated { get; set; } } }
27.823529
50
0.640592
[ "MIT" ]
unosquare/swan-aspnetcore
test/Unosquare.Swan.AspNetCore.Test/Mocks/AuditTrailMock.cs
475
C#
#region License // Copyright 2015 Ken Worst - R.C. Worst & Company Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using NUnit.Framework; using WaTaxRateLookup; namespace WaTaxRateLookup_Test { [TestFixture] public class Wa_Tax_Rate_Lookup_TF { Client _Client = new Client(); [Test] public void Good_Address_Test() { var address = new Address("6500 Linderson way", "Olympia", "98501"); var response = _Client.Get(address); Assert.AreEqual(0, response.ResultCode); Assert.AreEqual("The address was found.", response.ResultCodeDefinition); Assert.AreEqual("3406", response.LocationCode); Assert.NotNull(response.ResultCodeDefinition); Assert.NotNull(response.LocalRate); Assert.NotNull(response.LocationCode); Assert.NotNull(response.LocationName); Assert.NotNull(response.StateRate); } [Test] public void Bad_ZipCode_Test() { var address = new Address("6500 Linderson way", "", "980501"); var response = _Client.Get(address); Assert.AreEqual(3, response.ResultCode); Assert.AreEqual("The address, ZIP+4, and ZIP could not be found.", response.ResultCodeDefinition); Assert.NotNull(response.ResultCodeDefinition); Assert.IsNull(response.LocalRate); Assert.IsNull(response.LocationCode); Assert.IsNull(response.LocationName); Assert.IsNull(response.StateRate); } [Test] public void No_Address_Test() { var address = new Address("", "", "98501"); var response = _Client.Get(address); Assert.AreEqual(2, response.ResultCode); Assert.AreEqual("Neither the address or ZIP+4 was found, but the 5-digit ZIP was located.", response.ResultCodeDefinition); Assert.NotNull(response.ResultCodeDefinition); Assert.NotNull(response.LocalRate); Assert.NotNull(response.LocationCode); Assert.NotNull(response.LocationName); Assert.NotNull(response.StateRate); } [Test] public void Bad_Address_Good_ZipCode_Test() { var address = new Address("&&&&&&&&&&&&&", "", "98501"); var response = _Client.Get(address); Assert.AreEqual(2, response.ResultCode); Assert.AreEqual("Neither the address or ZIP+4 was found, but the 5-digit ZIP was located.", response.ResultCodeDefinition); Assert.NotNull(response.ResultCodeDefinition); Assert.NotNull(response.LocalRate); Assert.NotNull(response.LocationCode); Assert.NotNull(response.LocationName); Assert.NotNull(response.StateRate); } [Test] public void Good_Address_Bad_ZipCode_Test() { var address = new Address("6500 Linderson way", "", "9111118501"); var response = _Client.Get(address); Assert.AreEqual(4, response.ResultCode); Assert.AreEqual("Invalid arguements.", response.ResultCodeDefinition); Assert.NotNull(response.ResultCodeDefinition); Assert.IsNull(response.LocalRate); Assert.IsNull(response.LocationCode); Assert.IsNull(response.LocationName); Assert.IsNull(response.StateRate); } [Test] public void No_Address_Bad_ZipCode_Test() { var address = new Address(null, null, "9111118501"); var response = _Client.Get(address); Assert.AreEqual(4, response.ResultCode); Assert.AreEqual("Invalid arguements.", response.ResultCodeDefinition); Assert.NotNull(response.ResultCodeDefinition); Assert.IsNull(response.LocalRate); Assert.IsNull(response.LocationCode); Assert.IsNull(response.LocationName); Assert.IsNull(response.StateRate); } } }
42.579439
136
0.635426
[ "Apache-2.0" ]
worstone/WA-Sales-Tax-Rate-Lookup
WaTaxRateLookup_Tests/Wa_Tax_Rate_Lookup_TF.cs
4,558
C#
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation #endregion namespace FluentValidation { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Internal; using Resources; using Validators; /// <summary> /// Default options that can be used to configure a validator. /// </summary> public static class DefaultValidatorOptions { /// <summary> /// Specifies the cascade mode for failures. /// If set to 'Stop' then execution of the rule will stop once the first validator in the chain fails. /// If set to 'Continue' then all validators in the chain will execute regardless of failures. /// </summary> public static IRuleBuilderInitial<T, TProperty> Cascade<T, TProperty>(this IRuleBuilderInitial<T, TProperty> ruleBuilder, CascadeMode cascadeMode) { return ruleBuilder.Configure(cfg => { cfg.CascadeMode = cascadeMode; }); } /// <summary> /// Specifies the cascade mode for failures. /// If set to 'Stop' then execution of the rule will stop once the first validator in the chain fails. /// If set to 'Continue' then all validators in the chain will execute regardless of failures. /// </summary> public static IRuleBuilderInitialCollection<T, TProperty> Cascade<T, TProperty>(this IRuleBuilderInitialCollection<T, TProperty> ruleBuilder, CascadeMode cascadeMode) { return ruleBuilder.Configure(cfg => { cfg.CascadeMode = cascadeMode; }); } /// <summary> /// Transforms the property value before validation occurs. The transformed value must be of the same type as the input value. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="ruleBuilder"></param> /// <param name="transformationFunc"></param> /// <returns></returns> public static IRuleBuilderInitial<T, TProperty> Transform<T, TProperty>(this IRuleBuilderInitial<T, TProperty> ruleBuilder, Func<TProperty, TProperty> transformationFunc) { return ruleBuilder.Configure(cfg => { cfg.Transformer = transformationFunc.CoerceToNonGeneric(); }); } /// <summary> /// Transforms the property value before validation occurs. The transformed value must be of the same type as the input value. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="ruleBuilder"></param> /// <param name="transformationFunc"></param> /// <returns></returns> public static IRuleBuilderInitialCollection<T, TProperty> Transform<T, TProperty>(this IRuleBuilderInitialCollection<T, TProperty> ruleBuilder, Func<TProperty, TProperty> transformationFunc) { return ruleBuilder.Configure(cfg => { cfg.Transformer = transformationFunc.CoerceToNonGeneric(); }); } /// <summary> /// Specifies a custom action to be invoked when the validator fails. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="onFailure"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OnAnyFailure<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<T> onFailure) { return rule.Configure(config => { config.OnFailure = onFailure.CoerceToNonGeneric(); }); } /// <summary> /// Specifies a custom error message to use when validation fails. Only applies to the rule that directly precedes it. /// </summary> /// <param name="rule">The current rule</param> /// <param name="errorMessage">The error message to use</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage) { errorMessage.Guard("A message must be specified when calling WithMessage.", nameof(errorMessage)); return rule.Configure(config => { config.CurrentValidator.Options.ErrorMessageSource = new StaticStringSource(errorMessage); }); } /// <summary> /// Specifies a custom error message to use when validation fails. Only applies to the rule that directly precedes it. /// </summary> /// <param name="rule">The current rule</param> /// <param name="messageProvider">Delegate that will be invoked to retrieve the localized message. </param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, string> messageProvider) { messageProvider.Guard("A messageProvider must be provided.", nameof(messageProvider)); return rule.Configure(config => { config.CurrentValidator.Options.ErrorMessageSource = new LazyStringSource(ctx => messageProvider((T)ctx.InstanceToValidate)); }); } /// <summary> /// Specifies a custom error message to use when validation fails. Only applies to the rule that directly precedes it. /// </summary> /// <param name="rule">The current rule</param> /// <param name="messageProvider">Delegate that will be invoked.Uses_localized_name to retrieve the localized message. </param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, TProperty, string> messageProvider) { messageProvider.Guard("A messageProvider must be provided.", nameof(messageProvider)); return rule.Configure(config => { config.CurrentValidator.Options.ErrorMessageSource = new LazyStringSource(context => messageProvider((T)context.InstanceToValidate, (TProperty)context.PropertyValue)); }); } /// <summary> /// Specifies a custom error code to use if validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="errorCode">The error code to use</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithErrorCode<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorCode) { errorCode.Guard("A error code must be specified when calling WithErrorCode.", nameof(errorCode)); return rule.Configure(config => { config.CurrentValidator.Options.ErrorCodeSource = new StaticStringSource(errorCode); }); } /// <summary> /// Specifies a custom error message resource to use when validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="resourceType">Resource type representing a resx file</param> /// <param name="resourceName">Name of resource</param> /// <returns></returns> [Obsolete("WithLocalizedMessage is deprecated. Use the overload of WithMessage that takes a Func instead.")] public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Type resourceType, string resourceName) { resourceType.Guard("A resource type must be provided.", nameof(resourceType)); resourceName.Guard("A resource name must be provided.", nameof(resourceName)); return rule.Configure(config => { config.CurrentValidator.Options.ErrorMessageSource = new LocalizedStringSource(resourceType, resourceName); }); } /// <summary> /// Specifies a condition limiting when the validator should run. /// The validator will only be executed if the result of the lambda returns true. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> When<T,TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling When.", nameof(predicate)); // Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain. return rule.Configure(config => { config.ApplyCondition(ctx => predicate((T)ctx.Instance), applyConditionTo); }); } /// <summary> /// Specifies a condition limiting when the validator should not run. /// The validator will only be executed if the result of the lambda returns false. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should not run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> Unless<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling Unless", nameof(predicate)); return rule.When(x => !predicate(x), applyConditionTo); } /// <summary> /// Specifies an asynchronous condition limiting when the validator should run. /// The validator will only be executed if the result of the lambda returns true. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WhenAsync<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, CancellationToken, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling WhenAsync.", nameof(predicate)); // Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain. return rule.Configure(config => { config.ApplyAsyncCondition((ctx, ct) => predicate((T)ctx.Instance, ct), applyConditionTo); }); } /// <summary> /// Specifies an asynchronous condition limiting when the validator should not run. /// The validator will only be executed if the result of the lambda returns false. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should not run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> UnlessAsync<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, CancellationToken, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling UnlessAsync", nameof(predicate)); return rule.WhenAsync(async (x, ct) => !await predicate(x, ct), applyConditionTo); } /// <summary> /// Applies a filter to a collection property. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">The condition</param> /// <returns></returns> public static IRuleBuilderInitialCollection<T, TCollectionElement> Where<T, TCollectionElement>(this IRuleBuilderInitialCollection<T, TCollectionElement> rule, Func<TCollectionElement, bool> predicate) { // This overload supports RuleFor().SetCollectionValidator() (which returns IRuleBuilderOptions<T, IEnumerable<TElement>>) predicate.Guard("Cannot pass null to Where.", nameof(predicate)); return rule.Configure(cfg => { cfg.Filter = predicate; }); } /// <summary> /// Triggers an action when the rule passes. Typically used to configure dependent rules. This applies to all preceding rules in the chain. /// </summary> /// <param name="rule">The current rule</param> /// <param name="action">An action to be invoked if the rule is valid</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> DependentRules<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action action) { var dependencyContainer = new List<IValidationRule>(); if (rule is IExposesParentValidator<T> exposesParentValidator) { if (exposesParentValidator.ParentValidator is AbstractValidator<T> parent) { // Capture any rules added to the parent validator inside this delegate. using (parent.Rules.Capture(dependencyContainer.Add)) { action(); } } else { throw new NotSupportedException("DependentRules can only be called as part of classes that inherit from AbstractValidator"); } } else { throw new NotSupportedException("DependentRules can only be called as part of classes that inherit from AbstractValidator"); } rule.Configure(cfg => { if (cfg.RuleSets.Length > 0) { foreach (var dependentRule in dependencyContainer) { if (dependentRule is PropertyRule propRule && propRule.RuleSets.Length == 0) { propRule.RuleSets = cfg.RuleSets; } } } cfg.DependentRules.AddRange(dependencyContainer); }); return rule; } /// <summary> /// Specifies a custom property name to use within the error message. /// </summary> /// <param name="rule">The current rule</param> /// <param name="overridePropertyName">The property name to use</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string overridePropertyName) { overridePropertyName.Guard("A property name must be specified when calling WithName.", nameof(overridePropertyName)); return rule.Configure(config => { config.DisplayName = new StaticStringSource(overridePropertyName); }); } /// <summary> /// Specifies a custom property name to use within the error message. /// </summary> /// <param name="rule">The current rule</param> /// <param name="nameProvider">Func used to retrieve the property's display name</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, string> nameProvider) { nameProvider.Guard("A nameProvider WithName.", nameof(nameProvider)); return rule.Configure(config => { // Must use null propagation here. // The MVC clientside validation will try and retrieve the name, but won't // be able to to so if we've used this overload of WithName. config.DisplayName = new LazyStringSource(ctx => nameProvider((T)ctx?.InstanceToValidate)); }); } /// <summary> /// Overrides the name of the property associated with this rule. /// NOTE: This is a considered to be an advanced feature. Most of the time that you use this, you actually meant to use WithName. /// </summary> /// <param name="rule">The current rule</param> /// <param name="propertyName">The property name to use</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OverridePropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string propertyName) { // Allow string.Empty as this could be a model-level rule. if (propertyName == null) throw new ArgumentNullException(nameof(propertyName), "A property name must be specified when calling OverridePropertyName."); return rule.Configure(config => config.PropertyName = propertyName); } /// <summary> /// Overrides the name of the property associated with this rule. /// NOTE: This is a considered to be an advanced feature. Most of the time that you use this, you actually meant to use WithName. /// </summary> /// <param name="rule">The current rule</param> /// <param name="expr">An expression referencing another property</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OverridePropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Expression<Func<T, object>> expr) { if (expr == null) throw new ArgumentNullException(nameof(expr)); var member = expr.GetMember(); if (member == null) throw new NotSupportedException("Must supply a MemberExpression when calling OverridePropertyName"); return rule.OverridePropertyName(member.Name); } /// <summary> /// Specifies custom state that should be stored alongside the validation message when validation fails for this rule. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="stateProvider"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithState<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, object> stateProvider) { stateProvider.Guard("A lambda expression must be passed to WithState", nameof(stateProvider)); var wrapper = new Func<PropertyValidatorContext, object>(ctx => stateProvider((T) ctx.Instance)); return rule.Configure(config => config.CurrentValidator.Options.CustomStateProvider = wrapper); } /// <summary> /// Specifies custom state that should be stored alongside the validation message when validation fails for this rule. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="stateProvider"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithState<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, TProperty, object> stateProvider) { stateProvider.Guard("A lambda expression must be passed to WithState", nameof(stateProvider)); var wrapper = new Func<PropertyValidatorContext, object>(ctx => { return stateProvider((T) ctx.Instance, (TProperty) ctx.PropertyValue); }); return rule.Configure(config => config.CurrentValidator.Options.CustomStateProvider = wrapper); } ///<summary> /// Specifies custom severity that should be stored alongside the validation message when validation fails for this rule. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="severity"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithSeverity<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Severity severity) { return rule.Configure(config => config.CurrentValidator.Options.Severity = severity); } /// <summary> /// Specifies custom method that will be called when specific rule fails /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="onFailure"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OnFailure<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<T> onFailure) { return rule.Configure(config => config.ReplaceValidator(config.CurrentValidator, new OnFailureValidator<T>(config.CurrentValidator, (instance, ctx, message) => onFailure(instance)))); } /// <summary> /// Specifies custom method that will be called when specific rule fails /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="onFailure"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OnFailure<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<T, PropertyValidatorContext> onFailure) { return rule.Configure(config => config.ReplaceValidator(config.CurrentValidator, new OnFailureValidator<T>(config.CurrentValidator, (instance, ctx, message) => onFailure(instance, ctx)))); } /// <summary> /// Specifies custom method that will be called when specific rule fails /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="onFailure"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OnFailure<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<T, PropertyValidatorContext, string> onFailure) { return rule.Configure(config => config.ReplaceValidator(config.CurrentValidator, new OnFailureValidator<T>(config.CurrentValidator, onFailure))); } /// <summary> /// Allows the generated indexer to be overridden for collection rules. /// </summary> /// <param name="rule">The current rule</param> /// <param name="callback">The callback. Receives the model, the collection, the current element and the current index as parameters. Should return a string representation of the indexer. The default is "[" + index + "]"</param> /// <returns></returns> public static IRuleBuilderInitialCollection<T, TCollectionElement> OverrideIndexer<T, TCollectionElement>(this IRuleBuilderInitialCollection<T, TCollectionElement> rule, Func<T, IEnumerable<TCollectionElement>, TCollectionElement, int, string> callback) { // This overload supports RuleFor().SetCollectionValidator() (which returns IRuleBuilderOptions<T, IEnumerable<TElement>>) callback.Guard("Cannot pass null to OverrideIndexer.", nameof(callback)); return rule.Configure(cfg => { cfg.IndexBuilder = (x, collection, element, index) => callback((T)x, (IEnumerable<TCollectionElement>)collection, (TCollectionElement)element, index); }); } /// <summary> /// Gets the default message for a property validator /// </summary> /// <typeparam name="T">The validator type</typeparam> /// <returns>The translated string</returns> public static string GetStringForValidator<T>(this ILanguageManager languageManager) { return languageManager.GetString(typeof(T).Name); } internal static Func<T, object>[] ConvertArrayOfObjectsToArrayOfDelegates<T>(object[] objects) { if(objects == null || objects.Length == 0) { return new Func<T, object>[0]; } return objects.Select(obj => new Func<T, object>(x => obj)).ToArray(); } } }
52.05531
258
0.711972
[ "Apache-2.0" ]
MDormann/FluentValidation
src/FluentValidation/DefaultValidatorOptions.cs
23,529
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("XamarinFormsListViewXamlImage.Windows.Windows")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XamarinFormsListViewXamlImage.Windows.Windows")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
38.172414
84
0.753388
[ "MIT" ]
xamarin-samples/XamarinFormsListViewXamlImage
XamarinFormsListViewXamlImage/XamarinFormsListViewXamlImage.Windows/Properties/AssemblyInfo.cs
1,110
C#
/********************************************************************************************************************** * IO.NET (https://github.com/mkloubert/IO.NET) * * * * Copyright (c) 2015, Marcel Joachim Kloubert <marcel.kloubert@gmx.net> * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * * following disclaimer. * * * * 2. 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. * * * * 3. Neither the name of the copyright holder 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.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace MarcelJoachimKloubert.IO { /// <summary> /// Async version of <see cref="AggregateTextWriter" /> class. /// </summary> public partial class AsyncAggregateTextWriter : AggregateTextWriter { #region Constructors (1) /// <summary> /// Initializes a new instance of the <see cref="AsyncAggregateTextWriter" /> class. /// </summary> /// <param name="ownsWriters"> /// Underlying stream should also been closed / disposed or not. /// </param> /// <param name="syncRoot">The custom object that should be used for thread safe opertations.</param> public AsyncAggregateTextWriter(bool ownsWriters = false, object syncRoot = null) : base(ownsWriters: ownsWriters, syncRoot: syncRoot) { } #endregion Constructors (1) #region Methods (1) /// <inheriteddoc /> protected override IEnumerable<TResult> InvokeForWriters<T, TResult>(Func<TextWriter, T, TResult> func, Func<TextWriter, T> funcStateFactory) { if (func == null) { throw new ArgumentNullException("func"); } if (funcStateFactory == null) { throw new ArgumentNullException("funcStateFactory"); } var result = new List<TResult>(); var exceptions = new List<Exception>(); var sync = SyncRoot; var addException = new Action<Exception>((ex) => { lock (sync) { exceptions.Add(ex); } }); var addResult = new Action<TResult>((r) => { lock (sync) { result.Add(r); } }); try { var tasks = new List<Task>(); using (var e = _WRITERS.GetEnumerator()) { while (e.MoveNext()) { try { var execCtx = new WriterExecutionContext<T, TResult>() { AddException = addException, AddResult = addResult, Function = func, StateFactory = funcStateFactory, Writer = e.Current, }; var newTask = new Task((state) => { var ctx = (WriterExecutionContext<T, TResult>)state; ctx.Invoke(); }, execCtx); newTask.Start(); tasks.Add(newTask); } catch (Exception ex) { addException(ex); } } } Task.WaitAll(tasks.ToArray()); } catch (Exception ex) { addException(ex); } if (exceptions.Count > 0) { throw new AggregateException(exceptions); } return result; } #endregion Methods (1) } }
48.47973
150
0.388711
[ "BSD-3-Clause" ]
mkloubert/IO.NET
MarcelJoachimKloubert/IO/AsyncAggregateTextWriter.cs
7,177
C#
using System.Runtime.InteropServices.ComTypes; using UnityEngine; namespace BDFramework.UI { public interface IView { DataListenerService Model { get; } Transform Transform { get; } void Show(); void Hide(); void BindModel(); void Destory(); } }
17.277778
47
0.601286
[ "Apache-2.0" ]
qiangtoucao01/Odin
Assets/Code/BDFramework/Core/_UI@hotfix/MVC/IView.cs
313
C#
namespace Infestation { using System; public class InfestationSpores : Supplement, ISupplement { const int PowerEffectInfestation = -1; const int AggresionEffectWInfestation = 20; public InfestationSpores(int healthEffect=0) :base(InfestationSpores.PowerEffectInfestation,healthEffect,InfestationSpores.AggresionEffectWInfestation) { } } }
23.722222
118
0.669789
[ "MIT" ]
aleksandra992/CSharp
Object-Oriented-Programming/Exams/Infestation-Skeleton/Infestation/InfestationSpores.cs
429
C#
using System; using System.Collections.Generic; using Ink; namespace Ink { public class Compiler { public class Options { public string sourceFilename; public List<string> pluginNames; public bool countAllVisits; public Ink.ErrorHandler errorHandler; public Ink.IFileHandler fileHandler; } public List<string> errors { get { return _errors; } } public List<string> warnings { get { return _warnings; } } public List<string> authorMessages { get { return _authorMessages; } } public Parsed.Story parsedStory { get { return _parsedStory; } } public Compiler (string inkSource, Options options = null) { _inputString = inkSource; _options = options ?? new Options(); if( _options.pluginNames != null ) _pluginManager = new PluginManager (_options.pluginNames); } public Parsed.Story Parse() { _parser = new InkParser(_inputString, _options.sourceFilename, OnError, _options.fileHandler); _parsedStory = _parser.Parse(); return _parsedStory; } public Runtime.Story Compile () { Parse(); if( _pluginManager != null ) _pluginManager.PostParse(_parsedStory); if (_parsedStory != null && _errors.Count == 0) { _parsedStory.countAllVisits = _options.countAllVisits; _runtimeStory = _parsedStory.ExportRuntime (OnError); if( _pluginManager != null ) _pluginManager.PostExport (_parsedStory, _runtimeStory); } else { _runtimeStory = null; } return _runtimeStory; } public class CommandLineInputResult { public bool requestsExit; public int choiceIdx = -1; public string divertedPath; public string output; } public CommandLineInputResult ReadCommandLineInput (string userInput) { var inputParser = new InkParser (userInput); var inputResult = inputParser.CommandLineUserInput (); var result = new CommandLineInputResult (); // Choice if (inputResult.choiceInput != null) { result.choiceIdx = ((int)inputResult.choiceInput) - 1; } // Help else if (inputResult.isHelp) { result.output = "Type a choice number, a divert (e.g. '-> myKnot'), an expression, or a variable assignment (e.g. 'x = 5')"; } // Quit else if (inputResult.isExit) { result.requestsExit = true; } // Request for debug source line number else if (inputResult.debugSource != null) { var offset = (int)inputResult.debugSource; var dm = DebugMetadataForContentAtOffset (offset); if (dm != null) result.output = "DebugSource: " + dm.ToString (); else result.output = "DebugSource: Unknown source"; } // Request for runtime path lookup (to line number) else if (inputResult.debugPathLookup != null) { var pathStr = inputResult.debugPathLookup; var contentResult = _runtimeStory.ContentAtPath (new Runtime.Path (pathStr)); var dm = contentResult.obj.debugMetadata; if( dm != null ) result.output = "DebugSource: " + dm.ToString (); else result.output = "DebugSource: Unknown source"; } // User entered some ink else if (inputResult.userImmediateModeStatement != null) { var parsedObj = inputResult.userImmediateModeStatement as Parsed.Object; // Variable assignment: create in Parsed.Story as well as the Runtime.Story // so that we don't get an error message during reference resolution if (parsedObj is Parsed.VariableAssignment) { var varAssign = (Parsed.VariableAssignment)parsedObj; if (varAssign.isNewTemporaryDeclaration) { _parsedStory.TryAddNewVariableDeclaration (varAssign); } } parsedObj.parent = _parsedStory; var runtimeObj = parsedObj.runtimeObject; parsedObj.ResolveReferences (_parsedStory); if (!_parsedStory.hadError) { // Divert if (parsedObj is Parsed.Divert) { var parsedDivert = parsedObj as Parsed.Divert; result.divertedPath = parsedDivert.runtimeDivert.targetPath.ToString(); } // Expression or variable assignment else if (parsedObj is Parsed.Expression || parsedObj is Parsed.VariableAssignment) { var evalResult = _runtimeStory.EvaluateExpression ((Runtime.Container)runtimeObj); if (evalResult != null) { result.output = evalResult.ToString (); } } } else { _parsedStory.ResetError (); } } else { result.output = "Unexpected input. Type 'help' or a choice number."; } return result; } public void RetrieveDebugSourceForLatestContent () { foreach (var outputObj in _runtimeStory.state.outputStream) { var textContent = outputObj as Runtime.StringValue; if (textContent != null) { var range = new DebugSourceRange (); range.length = textContent.value.Length; range.debugMetadata = textContent.debugMetadata; range.text = textContent.value; _debugSourceRanges.Add (range); } } } Runtime.DebugMetadata DebugMetadataForContentAtOffset (int offset) { int currOffset = 0; Runtime.DebugMetadata lastValidMetadata = null; foreach (var range in _debugSourceRanges) { if (range.debugMetadata != null) lastValidMetadata = range.debugMetadata; if (offset >= currOffset && offset < currOffset + range.length) return lastValidMetadata; currOffset += range.length; } return null; } public struct DebugSourceRange { public int length; public Runtime.DebugMetadata debugMetadata; public string text; } void OnError (string message, ErrorType errorType) { switch (errorType) { case ErrorType.Author: _authorMessages.Add (message); break; case ErrorType.Warning: _warnings.Add (message); break; case ErrorType.Error: _errors.Add (message); break; } if (_options.errorHandler != null) _options.errorHandler (message, errorType); } string _inputString; Options _options; InkParser _parser; Parsed.Story _parsedStory; Runtime.Story _runtimeStory; PluginManager _pluginManager; List<string> _errors = new List<string> (); List<string> _warnings = new List<string> (); List<string> _authorMessages = new List<string> (); List<DebugSourceRange> _debugSourceRanges = new List<DebugSourceRange> (); } }
32.618474
140
0.529796
[ "MIT" ]
PiOverFour/ink
compiler/Compiler.cs
8,124
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Reflection.Emit { public sealed partial class AssemblyBuilder : System.Reflection.Assembly { internal AssemblyBuilder() { } public override string FullName { get { return default(string); } } public override bool IsDynamic { get { return default(bool); } } public override System.Reflection.Module ManifestModule { get { return default(System.Reflection.Module); } } public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) { return default(System.Reflection.Emit.AssemblyBuilder); } public static System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.ModuleBuilder DefineDynamicModule(string name) { return default(System.Reflection.Emit.ModuleBuilder); } public override bool Equals(object obj) { return default(bool); } public System.Reflection.Emit.ModuleBuilder GetDynamicModule(string name) { return default(System.Reflection.Emit.ModuleBuilder); } public override int GetHashCode() { return default(int); } public override System.Reflection.ManifestResourceInfo GetManifestResourceInfo(string resourceName) { return default(System.Reflection.ManifestResourceInfo); } public override string[] GetManifestResourceNames() { return default(string[]); } public override System.IO.Stream GetManifestResourceStream(string name) { return default(System.IO.Stream); } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } } [System.FlagsAttribute] public enum AssemblyBuilderAccess { Run = 1, RunAndCollect = 9, } public sealed partial class ConstructorBuilder : System.Reflection.ConstructorInfo { internal ConstructorBuilder() { } public override System.Reflection.MethodAttributes Attributes { get { return default(System.Reflection.MethodAttributes); } } public override System.Reflection.CallingConventions CallingConvention { get { return default(System.Reflection.CallingConventions); } } public override System.Type DeclaringType { get { return default(System.Type); } } public bool InitLocals { get { return default(bool); } set { } } public override string Name { get { return default(string); } } public System.Reflection.Emit.ParameterBuilder DefineParameter(int iSequence, System.Reflection.ParameterAttributes attributes, string strParamName) { return default(System.Reflection.Emit.ParameterBuilder); } public System.Reflection.Emit.ILGenerator GetILGenerator() { return default(System.Reflection.Emit.ILGenerator); } public System.Reflection.Emit.ILGenerator GetILGenerator(int streamSize) { return default(System.Reflection.Emit.ILGenerator); } public override System.Reflection.ParameterInfo[] GetParameters() { return default(System.Reflection.ParameterInfo[]); } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { } public override string ToString() { return default(string); } } public sealed partial class EnumBuilder : System.Reflection.TypeInfo { internal EnumBuilder() { } public override string AssemblyQualifiedName { get { return default(string); } } public override string FullName { get { return default(string); } } public override string Name { get { return default(string); } } public System.Reflection.Emit.FieldBuilder UnderlyingField { get { return default(System.Reflection.Emit.FieldBuilder); } } public System.Reflection.TypeInfo CreateTypeInfo() { return default(System.Reflection.TypeInfo); } public System.Reflection.Emit.FieldBuilder DefineLiteral(string literalName, object literalValue) { return default(System.Reflection.Emit.FieldBuilder); } public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { return default(bool); } public override System.Type MakeArrayType() { return default(System.Type); } public override System.Type MakeArrayType(int rank) { return default(System.Type); } public override System.Type MakeByRefType() { return default(System.Type); } public override System.Type MakePointerType() { return default(System.Type); } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } } public sealed partial class EventBuilder { internal EventBuilder() { } public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetAddOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetRaiseMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetRemoveOnMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } } public sealed partial class FieldBuilder : System.Reflection.FieldInfo { internal FieldBuilder() { } public override System.Reflection.FieldAttributes Attributes { get { return default(System.Reflection.FieldAttributes); } } public override System.Type DeclaringType { get { return default(System.Type); } } public override System.Type FieldType { get { return default(System.Type); } } public override string Name { get { return default(string); } } public override object GetValue(object obj) { return default(object); } public void SetConstant(object defaultValue) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetOffset(int iOffset) { } } public sealed partial class GenericTypeParameterBuilder : System.Reflection.TypeInfo { internal GenericTypeParameterBuilder() { } public override string AssemblyQualifiedName { get { return default(string); } } public override string FullName { get { return default(string); } } public override bool IsGenericParameter { get { return default(bool); } } public override string Name { get { return default(string); } } public override bool Equals(object o) { return default(bool); } public override System.Type GetGenericTypeDefinition() { return default(System.Type); } public override int GetHashCode() { return default(int); } public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { return default(bool); } public override System.Type MakeArrayType() { return default(System.Type); } public override System.Type MakeArrayType(int rank) { return default(System.Type); } public override System.Type MakeByRefType() { return default(System.Type); } public override System.Type MakeGenericType(params System.Type[] typeArguments) { return default(System.Type); } public override System.Type MakePointerType() { return default(System.Type); } public void SetBaseTypeConstraint(System.Type baseTypeConstraint) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetGenericParameterAttributes(System.Reflection.GenericParameterAttributes genericParameterAttributes) { } public void SetInterfaceConstraints(params System.Type[] interfaceConstraints) { } public override string ToString() { return default(string); } } public sealed partial class MethodBuilder : System.Reflection.MethodInfo { internal MethodBuilder() { } public override System.Reflection.MethodAttributes Attributes { get { return default(System.Reflection.MethodAttributes); } } public override System.Reflection.CallingConventions CallingConvention { get { return default(System.Reflection.CallingConventions); } } public override bool ContainsGenericParameters { get { return default(bool); } } public override System.Type DeclaringType { get { return default(System.Type); } } public bool InitLocals { get { return default(bool); } set { } } public override bool IsGenericMethod { get { return default(bool); } } public override bool IsGenericMethodDefinition { get { return default(bool); } } public override string Name { get { return default(string); } } public override System.Reflection.ParameterInfo ReturnParameter { get { return default(System.Reflection.ParameterInfo); } } public override System.Type ReturnType { get { return default(System.Type); } } public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { return default(System.Reflection.Emit.GenericTypeParameterBuilder[]); } public System.Reflection.Emit.ParameterBuilder DefineParameter(int position, System.Reflection.ParameterAttributes attributes, string strParamName) { return default(System.Reflection.Emit.ParameterBuilder); } public override bool Equals(object obj) { return default(bool); } public override System.Type[] GetGenericArguments() { return default(System.Type[]); } public override System.Reflection.MethodInfo GetGenericMethodDefinition() { return default(System.Reflection.MethodInfo); } public override int GetHashCode() { return default(int); } public System.Reflection.Emit.ILGenerator GetILGenerator() { return default(System.Reflection.Emit.ILGenerator); } public System.Reflection.Emit.ILGenerator GetILGenerator(int size) { return default(System.Reflection.Emit.ILGenerator); } public override System.Reflection.ParameterInfo[] GetParameters() { return default(System.Reflection.ParameterInfo[]); } public override System.Reflection.MethodInfo MakeGenericMethod(params System.Type[] typeArguments) { return default(System.Reflection.MethodInfo); } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetImplementationFlags(System.Reflection.MethodImplAttributes attributes) { } public void SetParameters(params System.Type[] parameterTypes) { } public void SetReturnType(System.Type returnType) { } public void SetSignature(System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { } public override string ToString() { return default(string); } } public partial class ModuleBuilder : System.Reflection.Module { internal ModuleBuilder() { } public override System.Reflection.Assembly Assembly { get { return default(System.Reflection.Assembly); } } public override string FullyQualifiedName { get { return default(string); } } public override string Name { get { return default(string); } } public void CreateGlobalFunctions() { } public System.Reflection.Emit.EnumBuilder DefineEnum(string name, System.Reflection.TypeAttributes visibility, System.Type underlyingType) { return default(System.Reflection.Emit.EnumBuilder); } public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { return default(System.Reflection.Emit.MethodBuilder); } public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] requiredReturnTypeCustomModifiers, System.Type[] optionalReturnTypeCustomModifiers, System.Type[] parameterTypes, System.Type[][] requiredParameterTypeCustomModifiers, System.Type[][] optionalParameterTypeCustomModifiers) { return default(System.Reflection.Emit.MethodBuilder); } public System.Reflection.Emit.MethodBuilder DefineGlobalMethod(string name, System.Reflection.MethodAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { return default(System.Reflection.Emit.MethodBuilder); } public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { return default(System.Reflection.Emit.FieldBuilder); } public System.Reflection.Emit.TypeBuilder DefineType(string name) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, int typesize) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packsize) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packingSize, int typesize) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Type[] interfaces) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { return default(System.Reflection.Emit.FieldBuilder); } public override bool Equals(object obj) { return default(bool); } public System.Reflection.MethodInfo GetArrayMethod(System.Type arrayClass, string methodName, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { return default(System.Reflection.MethodInfo); } public override int GetHashCode() { return default(int); } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } } public sealed partial class PropertyBuilder : System.Reflection.PropertyInfo { internal PropertyBuilder() { } public override System.Reflection.PropertyAttributes Attributes { get { return default(System.Reflection.PropertyAttributes); } } public override bool CanRead { get { return default(bool); } } public override bool CanWrite { get { return default(bool); } } public override System.Type DeclaringType { get { return default(System.Type); } } public override string Name { get { return default(string); } } public override System.Type PropertyType { get { return default(System.Type); } } public void AddOtherMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public override System.Reflection.ParameterInfo[] GetIndexParameters() { return default(System.Reflection.ParameterInfo[]); } public override object GetValue(object obj, object[] index) { return default(object); } public void SetConstant(object defaultValue) { } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetGetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public void SetSetMethod(System.Reflection.Emit.MethodBuilder mdBuilder) { } public override void SetValue(object obj, object value, object[] index) { } } public sealed partial class TypeBuilder : System.Reflection.TypeInfo { internal TypeBuilder() { } public const int UnspecifiedTypeSize = 0; public override string AssemblyQualifiedName { get { return default(string); } } public override string FullName { get { return default(string); } } public override bool IsGenericParameter { get { return default(bool); } } public override string Name { get { return default(string); } } public System.Reflection.Emit.PackingSize PackingSize { get { return default(System.Reflection.Emit.PackingSize); } } public int Size { get { return default(int); } } public void AddInterfaceImplementation(System.Type interfaceType) { } public System.Reflection.TypeInfo CreateTypeInfo() { return default(System.Reflection.TypeInfo); } public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes) { return default(System.Reflection.Emit.ConstructorBuilder); } public System.Reflection.Emit.ConstructorBuilder DefineConstructor(System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type[] parameterTypes, System.Type[][] requiredCustomModifiers, System.Type[][] optionalCustomModifiers) { return default(System.Reflection.Emit.ConstructorBuilder); } public System.Reflection.Emit.ConstructorBuilder DefineDefaultConstructor(System.Reflection.MethodAttributes attributes) { return default(System.Reflection.Emit.ConstructorBuilder); } public System.Reflection.Emit.EventBuilder DefineEvent(string name, System.Reflection.EventAttributes attributes, System.Type eventtype) { return default(System.Reflection.Emit.EventBuilder); } public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Reflection.FieldAttributes attributes) { return default(System.Reflection.Emit.FieldBuilder); } public System.Reflection.Emit.FieldBuilder DefineField(string fieldName, System.Type type, System.Type[] requiredCustomModifiers, System.Type[] optionalCustomModifiers, System.Reflection.FieldAttributes attributes) { return default(System.Reflection.Emit.FieldBuilder); } public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { return default(System.Reflection.Emit.GenericTypeParameterBuilder[]); } public System.Reflection.Emit.FieldBuilder DefineInitializedData(string name, byte[] data, System.Reflection.FieldAttributes attributes) { return default(System.Reflection.Emit.FieldBuilder); } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes) { return default(System.Reflection.Emit.MethodBuilder); } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention) { return default(System.Reflection.Emit.MethodBuilder); } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { return default(System.Reflection.Emit.MethodBuilder); } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { return default(System.Reflection.Emit.MethodBuilder); } public System.Reflection.Emit.MethodBuilder DefineMethod(string name, System.Reflection.MethodAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { return default(System.Reflection.Emit.MethodBuilder); } public void DefineMethodOverride(System.Reflection.MethodInfo methodInfoBody, System.Reflection.MethodInfo methodInfoDeclaration) { } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, int typeSize) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packSize) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Reflection.Emit.PackingSize packSize, int typeSize) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.TypeBuilder DefineNestedType(string name, System.Reflection.TypeAttributes attr, System.Type parent, System.Type[] interfaces) { return default(System.Reflection.Emit.TypeBuilder); } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] parameterTypes) { return default(System.Reflection.Emit.PropertyBuilder); } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Reflection.CallingConventions callingConvention, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { return default(System.Reflection.Emit.PropertyBuilder); } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[] parameterTypes) { return default(System.Reflection.Emit.PropertyBuilder); } public System.Reflection.Emit.PropertyBuilder DefineProperty(string name, System.Reflection.PropertyAttributes attributes, System.Type returnType, System.Type[] returnTypeRequiredCustomModifiers, System.Type[] returnTypeOptionalCustomModifiers, System.Type[] parameterTypes, System.Type[][] parameterTypeRequiredCustomModifiers, System.Type[][] parameterTypeOptionalCustomModifiers) { return default(System.Reflection.Emit.PropertyBuilder); } public System.Reflection.Emit.ConstructorBuilder DefineTypeInitializer() { return default(System.Reflection.Emit.ConstructorBuilder); } public System.Reflection.Emit.FieldBuilder DefineUninitializedData(string name, int size, System.Reflection.FieldAttributes attributes) { return default(System.Reflection.Emit.FieldBuilder); } public static System.Reflection.ConstructorInfo GetConstructor(System.Type type, System.Reflection.ConstructorInfo constructor) { return default(System.Reflection.ConstructorInfo); } public static System.Reflection.FieldInfo GetField(System.Type type, System.Reflection.FieldInfo field) { return default(System.Reflection.FieldInfo); } public override System.Type GetGenericTypeDefinition() { return default(System.Type); } public static System.Reflection.MethodInfo GetMethod(System.Type type, System.Reflection.MethodInfo method) { return default(System.Reflection.MethodInfo); } public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { return default(bool); } public bool IsCreated() { return default(bool); } public override System.Type MakeArrayType() { return default(System.Type); } public override System.Type MakeArrayType(int rank) { return default(System.Type); } public override System.Type MakeByRefType() { return default(System.Type); } public override System.Type MakeGenericType(params System.Type[] typeArguments) { return default(System.Type); } public override System.Type MakePointerType() { return default(System.Type); } public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder) { } public void SetParent(System.Type parent) { } public override string ToString() { return default(string); } } }
110.139344
506
0.770373
[ "MIT" ]
er0dr1guez/corefx
src/System.Reflection.Emit/ref/System.Reflection.Emit.cs
26,874
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName ="myassets/create interactive assets")] public class InteractiveEnvObjectScriptObject : ScriptableObject { public List<EnviromentInteractiveObjectInfo> envs; public List<EnviromentInteractiveObjectInfo> toys; public List<EnviromentInteractiveObjectInfo> others; public List<EnviromentInteractiveObjectInfo> audio_response; public List<EnviromentInteractiveObjectInfo> global_env; } [System.Serializable] public class EnviromentInteractiveObjectInfo { public string name; public string asset_name; public EnviromentObjectType type; public int id; public string texture_name; public Vector3 localposition; public Quaternion rotation; } public enum EnviromentObjectType { Env,Toy,Other,Audioresponse,GlobalEnv }
28.096774
66
0.802526
[ "MIT" ]
bosssu/LocalMusicPlayerVR
Assets/Scripts/SimpleMusicPlayer/InteractiveEnvObjectScriptObject.cs
873
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HTLib2.Bioinfo { public partial class Gromacs { public class FileGro { /// gro file format /// /// Main Table of Contents VERSION 4.6 /// GROMACS homepage Sat 19 Jan 2013 /// Files with the gro file extension contain a molecular structure in Gromos87 format. /// gro files can be used as trajectory by simply concatenating files. An attempt will /// be made to read a time value from the title string in each frame, which should be /// preceded by 't=', as in the sample below. /// /// A sample piece is included below: /// /// MD of 2 waters, t= 0.0 /// 6 /// 1WATER OW1 1 0.126 1.624 1.679 0.1227 -0.0580 0.0434 /// 1WATER HW2 2 0.190 1.661 1.747 0.8085 0.3191 -0.7791 /// 1WATER HW3 3 0.177 1.568 1.613 -0.9045 -2.6469 1.3180 /// 2WATER OW1 4 1.275 0.053 0.622 0.2519 0.3140 -0.1734 /// 2WATER HW2 5 1.337 0.002 0.680 -1.0641 -1.1349 0.0257 /// 2WATER HW3 6 1.326 0.120 0.568 1.9427 -0.8216 -0.0244 /// 1.82060 1.82060 1.82060 /// /// Lines contain the following information (top to bottom): /// /// * title string (free format string, optional time in ps after 't=') /// * number of atoms (free format integer) /// * one line for each atom (fixed format, see below) /// * box vectors (free format, space separated reals), /// values: v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y), /// the last 6 values may be omitted (they will be set to zero). /// Gromacs only supports boxes with v1(y)=v1(z)=v2(z)=0. /// /// This format is fixed, ie. all columns are in a fixed position. Optionally (for now /// only yet with trjconv) you can write gro files with any number of decimal places, /// the format will then be n+5 positions with n decimal places (n+1 for velocities) in /// stead of 8 with 3 (with 4 for velocities). Upon reading, the precision will be /// inferred from the distance between the decimal points (which will be n+5). Columns /// contain the following information (from left to right): /// /// * residue number (5 positions, integer) /// * residue name (5 characters) /// * atom name (5 characters) /// * atom number (5 positions, integer) /// * position (in nm, x y z in 3 columns, each 8 positions with 3 decimal places) /// * velocity (in nm/ps (or km/s), x y z in 3 columns, each 8 positions with 4 decimal places) /// /// Note that separate molecules or ions (e.g. water or Cl-) are regarded as residues. /// If you want to write such a file in your own program without using the GROMACS /// libraries you can use the following formats: /// /// C format /// "%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f" /// /// Fortran format /// (i5,2a5,i5,3f8.3,3f8.4) /// /// Pascal format /// This is left as an exercise for the user /// /// Note that this is the format for writing, as in the above example fields may be written without spaces, and therefore can not be read with the same format statement in C. /// http://www.gromacs.org public class Element { public Element(string line) { this.line = line; } public readonly string line; public override string ToString() { return line; } public Title toTitle { get { return (Title )this; } } public NumAtom toNumAtom { get { return (NumAtom)this; } } public Atom toAtom { get { return (Atom )this; } } public Box toBox { get { return (Box )this; } } } public class Title : Element { public Title(string line) : base(line) { } } public class NumAtom : Element { public NumAtom(string line) : base(line) { } public int value { get { return int.Parse(line); } } } public class Atom : Element { public Atom(string line) : base(line) { } } public class Box : Element { public Box(string line) : base(line) { } public Box(double v1x, double v2y, double v3z) : base(string.Format(" {0:0.00000} {1:0.00000} {2:0.00000}", v1x, v2y, v3z)) { } public double v1x { get { return double.Parse(line.Split().HRemoveAll("")[0]); } } public double v2y { get { return double.Parse(line.Split().HRemoveAll("")[1]); } } public double v3z { get { return double.Parse(line.Split().HRemoveAll("")[2]); } } public double? v1y { get { try{ return double.Parse(line.Split()[3]); } catch { return null; } } } public double? v1z { get { try{ return double.Parse(line.Split()[4]); } catch { return null; } } } public double? v2x { get { try{ return double.Parse(line.Split()[5]); } catch { return null; } } } public double? v2z { get { try{ return double.Parse(line.Split()[6]); } catch { return null; } } } public double? v3x { get { try{ return double.Parse(line.Split()[7]); } catch { return null; } } } public double? v3y { get { try{ return double.Parse(line.Split()[8]); } catch { return null; } } } } public Element[] elements; public Box elements_box { get { return elements.Last().toBox; } } static bool selftest = HDebug.IsDebuggerAttached; public static void SelfTest(string rootpath, string[] args) { if(selftest == false) return; selftest = false; string filepath = rootpath + @"\Bioinfo\External.Gromacs\Selftest\FileTrajectory.traj.txt"; FileGro eigvec = FromFile(filepath); } public static FileGro FromFile(string filepath) { string[] lines = HFile.ReadAllLines(filepath); return FromLines(lines); } public static FileGro FromLines(string[] lines) { List<Element> elements = new List<Element>(); elements.Add(new Title (lines[0])); elements.Add(new NumAtom(lines[1])); int numatom = elements[1].toNumAtom.value; for(int i=0; i<numatom; i++) elements.Add(new Atom(lines[i+2])); elements.Add(new Box(lines[2+numatom])); return new FileGro { elements = elements.ToArray() }; } public FileGro UpdateBox(double v1x, double v2y, double v3z) { Element[] nelem = this.elements.HClone(); nelem[nelem.Length-1] = new Box(v1x, v2y, v3z); return new FileGro { elements = nelem }; } public void ToFile(string filepath) { string[] lines = new string[elements.Length]; for(int i=0; i<elements.Length; i++) lines[i] = elements[i].line; HFile.WriteAllLines(filepath, lines); } } } }
50.546584
187
0.503441
[ "MIT" ]
htna/HCsbLib
HCsbLib/HCsbLib/HTLib2.Bioinfo/External.Gromacs/Gromacs.FileGro.cs
8,140
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: anttech.oceanbase.testplatform.task.sync /// </summary> public class AnttechOceanbaseTestplatformTaskSyncRequest : IAopRequest<AnttechOceanbaseTestplatformTaskSyncResponse> { /// <summary> /// 同步提测平台任务成绩 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "anttech.oceanbase.testplatform.task.sync"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public void PutOtherTextParam(string key, string value) { if(this.udfParams == null) { this.udfParams = new Dictionary<string, string>(); } this.udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); if(udfParams != null) { parameters.AddAll(this.udfParams); } return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
25.056452
120
0.590924
[ "Apache-2.0" ]
alipay/alipay-sdk-net
AlipaySDKNet.Standard/Request/AnttechOceanbaseTestplatformTaskSyncRequest.cs
3,127
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TesteBarClearSale.Models { public class ItemComanda { public ItemComanda() { } public ItemComanda(int comandaid, int produtoid, decimal valorunit, int qtd) { ComandaId = comandaid; ProdutoId = produtoid; ValorUnit = valorunit; CalcularTotal(); } [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int ComandaId { get; set; } public int ProdutoId { get; set; } public Produto Produto { get; set; } public decimal ValorUnit { get; set; } [Range(1, 999, ErrorMessage = "A Qtd. deve ser maior ou igual a 1")] public int Qtd { get; set; } public decimal ValorTotal { get; set; } public bool Status { get; set; } public decimal CalcularTotal() { ValorUnit = Produto.Valor; ValorTotal = ValorUnit * Qtd; return ValorTotal; } } }
26.957447
84
0.588792
[ "MIT" ]
fabiodiez/TesteDgBar
TesteBarClearSale/Models/ItemComanda.cs
1,269
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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { using RelatedTypeCache = ConditionalWeakTable<Solution, ConcurrentDictionary<(SymbolKey, IImmutableSet<Project>), AsyncLazy<ImmutableArray<(SymbolKey, ProjectId)>>>>; using SymbolAndProjectIdSet = HashSet<SymbolAndProjectId<INamedTypeSymbol>>; /// <summary> /// Provides helper methods for finding dependent types (derivations, implementations, /// etc.) across a solution. The results found are returned in pairs of <see cref="ISymbol"/>s /// and <see cref="ProjectId"/>s. The Ids specify what project we were searching in when /// we found the symbol. That project has the compilation that we found the specific /// source or metadata symbol within. Note that for metadata symbols there could be /// many projects where the same symbol could be found. However, we only return the /// first instance we found. /// </summary> internal static partial class DependentTypeFinder { private static Func<Location, bool> s_isInMetadata = loc => loc.IsInMetadata; private static Func<Location, bool> s_isInSource = loc => loc.IsInSource; private static Func<INamedTypeSymbol, bool> s_isNonSealedClass = t => t?.TypeKind == TypeKind.Class && !t.IsSealed; private static readonly Func<INamedTypeSymbol, bool> s_isInterfaceOrNonSealedClass = t => t.TypeKind == TypeKind.Interface || s_isNonSealedClass(t); private static readonly ObjectPool<SymbolAndProjectIdSet> s_setPool = new ObjectPool<SymbolAndProjectIdSet>( () => new SymbolAndProjectIdSet(SymbolAndProjectIdComparer<INamedTypeSymbol>.SymbolEquivalenceInstance)); // Caches from a types to their related types (in the context of a specific solution). // Kept as a cache so that clients who make many calls into us won't end up computing // the same data over and over again. Will be let go the moment the solution they're // based off of is no longer alive. // // Importantly, the caches only store SymbolKeys and Ids. As such, they will not hold // any Symbols or Compilations alive. private static readonly RelatedTypeCache s_typeToImmediatelyDerivedClassesMap = new RelatedTypeCache(); private static readonly RelatedTypeCache s_typeToTransitivelyDerivedClassesMap = new RelatedTypeCache(); private static readonly RelatedTypeCache s_typeToTransitivelyImplementingStructuresClassesAndInterfacesMap = new RelatedTypeCache(); private static readonly RelatedTypeCache s_typeToImmediatelyDerivedAndImplementingTypesMap = new RelatedTypeCache(); public static async Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindTypesFromCacheOrComputeAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, RelatedTypeCache cache, Func<CancellationToken, Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>>> findAsync, CancellationToken cancellationToken) { var dictionary = cache.GetOrCreateValue(solution); var result = default(ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>); // Do a quick lookup first to avoid the allocation. If it fails, go through the // slower allocating path. var key = (type.GetSymbolKey(), projects); if (!dictionary.TryGetValue(key, out var lazy)) { lazy = dictionary.GetOrAdd(key, new AsyncLazy<ImmutableArray<(SymbolKey, ProjectId)>>( async c => { // If we're the code that is actually computing the symbols, then just // take our result and store it in the outer frame. That way the caller // doesn't need to incur the cost of deserializing the symbol keys that // we're create right below this. result = await findAsync(c).ConfigureAwait(false); return result.SelectAsArray(t => (t.Symbol.GetSymbolKey(), t.ProjectId)); }, cacheResult: true)); } // If we were the caller that actually computed the symbols, then we can just return // the values we got. if (!result.IsDefault) { return result; } // Otherwise, someone else computed the symbols and cached the results as symbol // keys. Convert those symbol keys back to symbols and return. var symbolKeys = await lazy.GetValueAsync(cancellationToken).ConfigureAwait(false); var builder = ArrayBuilder<SymbolAndProjectId<INamedTypeSymbol>>.GetInstance(); // Group by projectId so that we only process one project/compilation at a time. // Also, process in dependency order so that previous compilations are ready if // they're referenced by later compilations. var dependencyOrder = solution.GetProjectDependencyGraph() .GetTopologicallySortedProjects() .Select((id, index) => (id, index)) .ToDictionary(t => t.id, t => t.index); var orderedGroups = symbolKeys.GroupBy(t => t.Item2).OrderBy(g => dependencyOrder[g.Key]); foreach (var group in orderedGroups) { var project = solution.GetProject(group.Key); if (project.SupportsCompilation) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var (symbolKey, _) in group) { var resolvedSymbol = symbolKey.Resolve(compilation, cancellationToken: cancellationToken).GetAnySymbol(); if (resolvedSymbol is INamedTypeSymbol namedType) { builder.Add(new SymbolAndProjectId<INamedTypeSymbol>(namedType, project.Id)); } } } } return builder.ToImmutableAndFree(); } /// <summary> /// Used for implementing the Inherited-By relation for progression. /// </summary> public static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindImmediatelyDerivedClassesAsync( INamedTypeSymbol type, Solution solution, CancellationToken cancellationToken) { return FindTypesFromCacheOrComputeAsync( type, solution, projects: null, cache: s_typeToImmediatelyDerivedClassesMap, findAsync: c => FindDerivedClassesAsync( SymbolAndProjectId.Create(type, projectId: null), solution, projects: null, transitive: false, cancellationToken: c), cancellationToken: cancellationToken); } /// <summary> /// This is an internal implementation of <see cref="SymbolFinder.FindDerivedClassesAsync(SymbolAndProjectId{INamedTypeSymbol}, Solution, IImmutableSet{Project}, CancellationToken)"/>, which is a publically callable method. /// </summary> public static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindTransitivelyDerivedClassesAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken) { return FindTypesFromCacheOrComputeAsync( type, solution, projects, s_typeToTransitivelyDerivedClassesMap, c => FindDerivedClassesAsync( SymbolAndProjectId.Create(type, projectId: null), solution, projects, transitive: true, cancellationToken: c), cancellationToken); } private static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindDerivedClassesAsync( SymbolAndProjectId<INamedTypeSymbol> type, Solution solution, IImmutableSet<Project> projects, bool transitive, CancellationToken cancellationToken) { if (s_isNonSealedClass(type.Symbol)) { bool metadataTypeMatches(SymbolAndProjectIdSet set, INamedTypeSymbol metadataType) => TypeDerivesFrom(set, metadataType, transitive); bool sourceTypeImmediatelyMatches(SymbolAndProjectIdSet set, INamedTypeSymbol metadataType) => set.Contains(SymbolAndProjectId.Create(metadataType.BaseType?.OriginalDefinition, projectId: null)); return FindTypesAsync(type, solution, projects, metadataTypeMatches: metadataTypeMatches, sourceTypeImmediatelyMatches: sourceTypeImmediatelyMatches, shouldContinueSearching: s_isNonSealedClass, transitive: transitive, cancellationToken: cancellationToken); } return SpecializedTasks.EmptyImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>(); } /// <summary> /// Implementation of <see cref="SymbolFinder.FindImplementationsAsync(SymbolAndProjectId, Solution, IImmutableSet{Project}, CancellationToken)"/> for /// <see cref="INamedTypeSymbol"/>s /// </summary> public static async Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindTransitivelyImplementingStructuresAndClassesAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken) { var derivedAndImplementingTypes = await FindTransitivelyImplementingStructuresClassesAndInterfacesAsync(type, solution, projects, cancellationToken).ConfigureAwait(false); // We only want implementing types here, not derived interfaces. return derivedAndImplementingTypes.WhereAsArray( t => t.Symbol.TypeKind == TypeKind.Class || t.Symbol.TypeKind == TypeKind.Struct); } /// <summary> /// Implementation of <see cref="SymbolFinder.FindImplementationsAsync(SymbolAndProjectId, Solution, IImmutableSet{Project}, CancellationToken)"/> for /// <see cref="INamedTypeSymbol"/>s /// </summary> public static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindTransitivelyImplementingStructuresClassesAndInterfacesAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken) { return FindTypesFromCacheOrComputeAsync( type, solution, projects, s_typeToTransitivelyImplementingStructuresClassesAndInterfacesMap, c => FindTransitivelyImplementingStructuresClassesAndInterfacesWorkerAsync(type, solution, projects, c), cancellationToken); } private static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindTransitivelyImplementingStructuresClassesAndInterfacesWorkerAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken) { return FindDerivedAndImplementingTypesAsync( SymbolAndProjectId.Create(type, projectId: null), solution, projects, transitive: true, cancellationToken: cancellationToken); } /// <summary> /// Used for implementing the Inherited-By relation for progression. /// </summary> public static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindImmediatelyDerivedAndImplementingTypesAsync( INamedTypeSymbol type, Solution solution, CancellationToken cancellationToken) { return FindTypesFromCacheOrComputeAsync( type, solution, projects: null, cache: s_typeToImmediatelyDerivedAndImplementingTypesMap, findAsync: c => FindDerivedAndImplementingTypesAsync( SymbolAndProjectId.Create(type, projectId: null), solution, projects: null, transitive: false, cancellationToken: c), cancellationToken: cancellationToken); } private static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindDerivedAndImplementingTypesAsync( SymbolAndProjectId<INamedTypeSymbol> type, Solution solution, IImmutableSet<Project> projects, bool transitive, CancellationToken cancellationToken) { // Only an interface can be implemented. if (type.Symbol?.TypeKind == TypeKind.Interface) { bool metadataTypeMatches(SymbolAndProjectIdSet s, INamedTypeSymbol t) => TypeDerivesFrom(s, t, transitive) || TypeImplementsFrom(s, t, transitive); return FindTypesAsync(type, solution, projects, metadataTypeMatches: metadataTypeMatches, sourceTypeImmediatelyMatches: ImmediatelyDerivesOrImplementsFrom, shouldContinueSearching: s_isInterfaceOrNonSealedClass, transitive: transitive, cancellationToken: cancellationToken); } return SpecializedTasks.EmptyImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>(); } private static async Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindTypesAsync( SymbolAndProjectId<INamedTypeSymbol> type, Solution solution, IImmutableSet<Project> projects, Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> metadataTypeMatches, Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> sourceTypeImmediatelyMatches, Func<INamedTypeSymbol, bool> shouldContinueSearching, bool transitive, CancellationToken cancellationToken) { type = type.WithSymbol(type.Symbol.OriginalDefinition); projects ??= ImmutableHashSet.Create(solution.Projects.ToArray()); var searchInMetadata = type.Symbol.Locations.Any(s_isInMetadata); // Note: it is not sufficient to just walk the list of projects passed in, // searching only those for derived types. // // Say we have projects: A <- B <- C, but only projects A and C are passed in. // We might miss a derived type in C if there's an intermediate derived type // in B. // // However, say we have projects A <- B <- C <- D, only only projects A and C // are passed in. There is no need to check D as there's no way it could // contribute an intermediate type that affects A or C. We only need to check // A, B and C // First find all the projects that could potentially reference this type. var projectsThatCouldReferenceType = await GetProjectsThatCouldReferenceTypeAsync( type.Symbol, solution, searchInMetadata, cancellationToken).ConfigureAwait(false); // Now, based on the list of projects that could actually reference the type, // and the list of projects the caller wants to search, find the actual list of // projects we need to search through. // // This list of projects is properly topologicaly ordered. Because of this we // can just process them in order from first to last because we know no project // in this list could affect a prior project. var orderedProjectsToExamine = GetOrderedProjectsToExamine( solution, projects, projectsThatCouldReferenceType); var currentMetadataTypes = CreateSymbolAndProjectIdSet(); var currentSourceAndMetadataTypes = CreateSymbolAndProjectIdSet(); currentSourceAndMetadataTypes.Add(type); if (searchInMetadata) { currentMetadataTypes.Add(type); } var result = CreateSymbolAndProjectIdSet(); // Now walk the projects from left to right seeing what our type cascades to. Once we // reach a fixed point in that project, take all the types we've found and move to the // next project. Continue this until we've exhausted all projects. // // Because there is a data-dependency between the projects, we cannot process them in // parallel. (Processing linearly is also probably preferable to limit the amount of // cache churn we could cause creating all those compilations. foreach (var project in orderedProjectsToExamine) { Debug.Assert(project.SupportsCompilation); await FindTypesInProjectAsync( searchInMetadata, result, currentMetadataTypes, currentSourceAndMetadataTypes, project, metadataTypeMatches, sourceTypeImmediatelyMatches, shouldContinueSearching, transitive, cancellationToken).ConfigureAwait(false); } return ToImmutableAndFree(result); } private static ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>> ToImmutableAndFree( SymbolAndProjectIdSet set) { var array = set.ToImmutableArray(); s_setPool.ClearAndFree(set); return array; } private static async Task FindTypesInProjectAsync( bool searchInMetadata, SymbolAndProjectIdSet result, SymbolAndProjectIdSet currentMetadataTypes, SymbolAndProjectIdSet currentSourceAndMetadataTypes, Project project, Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> metadataTypeMatches, Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> sourceTypeImmediatelyMatches, Func<INamedTypeSymbol, bool> shouldContinueSearching, bool transitive, CancellationToken cancellationToken) { Debug.Assert(project.SupportsCompilation); // First see what derived metadata types we might find in this project. // This is only necessary if we started with a metadata type. if (searchInMetadata) { var foundMetadataTypes = CreateSymbolAndProjectIdSet(); try { await AddAllMatchingMetadataTypesInProjectAsync( currentMetadataTypes, project, metadataTypeMatches, foundMetadataTypes, cancellationToken).ConfigureAwait(false); foreach (var foundTypeAndProjectId in foundMetadataTypes) { var foundType = foundTypeAndProjectId.Symbol; Debug.Assert(foundType.Locations.Any(s_isInMetadata)); // Add to the result list. result.Add(foundTypeAndProjectId); if (transitive && shouldContinueSearching(foundType)) { currentMetadataTypes.Add(foundTypeAndProjectId); currentSourceAndMetadataTypes.Add(foundTypeAndProjectId); } } } finally { s_setPool.ClearAndFree(foundMetadataTypes); } } // Now search the project and see what source types we can find. var foundSourceTypes = CreateSymbolAndProjectIdSet(); try { await AddSourceTypesInProjectAsync( currentSourceAndMetadataTypes, project, sourceTypeImmediatelyMatches, shouldContinueSearching, transitive, foundSourceTypes, cancellationToken).ConfigureAwait(false); foreach (var foundTypeAndProjectId in foundSourceTypes) { var foundType = foundTypeAndProjectId.Symbol; Debug.Assert(foundType.Locations.All(s_isInSource)); // Add to the result list. result.Add(foundTypeAndProjectId); if (transitive && shouldContinueSearching(foundType)) { currentSourceAndMetadataTypes.Add(foundTypeAndProjectId); } } } finally { s_setPool.ClearAndFree(foundSourceTypes); } } private static async Task<ISet<ProjectId>> GetProjectsThatCouldReferenceTypeAsync( INamedTypeSymbol type, Solution solution, bool searchInMetadata, CancellationToken cancellationToken) { var dependencyGraph = solution.GetProjectDependencyGraph(); if (searchInMetadata) { // For a metadata type, find all projects that refer to the metadata assembly that // the type is defined in. Note: we pass 'null' for projects intentionally. We // Need to find all the possible projects that contain this metadata. var projectsThatReferenceMetadataAssembly = await DependentProjectsFinder.GetDependentProjectsAsync( type, solution, projects: null, cancellationToken: cancellationToken).ConfigureAwait(false); // Now collect all the dependent projects as well. var projectsThatCouldReferenceType = projectsThatReferenceMetadataAssembly.SelectMany( p => GetProjectsThatCouldReferenceType(dependencyGraph, p)).ToSet(); return projectsThatCouldReferenceType; } else { // For a source project, find the project that that type was defined in. var sourceProject = solution.GetProject(type.ContainingAssembly); if (sourceProject == null) { return SpecializedCollections.EmptySet<ProjectId>(); } // Now find all the dependent of those projects. var projectsThatCouldReferenceType = GetProjectsThatCouldReferenceType( dependencyGraph, sourceProject).ToSet(); return projectsThatCouldReferenceType; } } private static IEnumerable<ProjectId> GetProjectsThatCouldReferenceType( ProjectDependencyGraph dependencyGraph, Project project) { // Get all the projects that depend on 'project' as well as 'project' itself. return dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(project.Id) .Concat(project.Id); } private static List<Project> GetOrderedProjectsToExamine( Solution solution, IImmutableSet<Project> projects, IEnumerable<ProjectId> projectsThatCouldReferenceType) { var projectsToExamine = GetProjectsToExamineWorker( solution, projects, projectsThatCouldReferenceType); // Ensure the projects we're going to examine are ordered topologically. // That way we can just sweep over them from left to right as no project // could affect a previous project in the sweep. return OrderTopologically(solution, projectsToExamine); } private static List<Project> OrderTopologically( Solution solution, IEnumerable<Project> projectsToExamine) { var order = new Dictionary<ProjectId, int>(capacity: solution.ProjectIds.Count); var index = 0; var dependencyGraph = solution.GetProjectDependencyGraph(); foreach (var projectId in dependencyGraph.GetTopologicallySortedProjects()) { order.Add(projectId, index); index++; } return projectsToExamine.OrderBy((p1, p2) => order[p1.Id] - order[p2.Id]).ToList(); } private static IEnumerable<Project> GetProjectsToExamineWorker( Solution solution, IImmutableSet<Project> projects, IEnumerable<ProjectId> projectsThatCouldReferenceType) { var dependencyGraph = solution.GetProjectDependencyGraph(); // Take the projects that were passed in, and find all the projects that // they depend on (including themselves). i.e. if we have a solution that // looks like: // A <- B <- C <- D // / // └ // E // and we're passed in 'B, C, E' as the project to search, then this set // will be A, B, C, E. var allProjectsThatTheseProjectsDependOn = projects .SelectMany(p => dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id)) .Concat(projects.Select(p => p.Id)).ToSet(); // We then intersect this set with the actual set of projects that could reference // the type. Say this list is B, C, D. The intersection of this list and the above // one will then be 'B' and 'C'. // // In other words, there is no point searching A and E (because they can't even // reference the type). And there's no point searching 'D' because it can't contribute // any information that would affect the result in the projects we are asked to search // within. // Finally, because we're searching metadata and source symbols, this needs to be a project // that actually supports compilations. return projectsThatCouldReferenceType.Intersect(allProjectsThatTheseProjectsDependOn) .Select(solution.GetProject) .Where(p => p.SupportsCompilation) .ToList(); } private static async Task AddAllMatchingMetadataTypesInProjectAsync( SymbolAndProjectIdSet metadataTypes, Project project, Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> metadataTypeMatches, SymbolAndProjectIdSet result, CancellationToken cancellationToken) { Debug.Assert(project.SupportsCompilation); if (metadataTypes.Count == 0) { return; } var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); // Seed the current set of types we're searching for with the types we were given. var currentTypes = metadataTypes; while (currentTypes.Count > 0) { var immediateDerivedTypes = CreateSymbolAndProjectIdSet(); foreach (var reference in compilation.References.OfType<PortableExecutableReference>()) { await FindImmediateMatchingMetadataTypesInMetadataReferenceAsync( currentTypes, project, metadataTypeMatches, compilation, reference, immediateDerivedTypes, cancellationToken).ConfigureAwait(false); } // Add what we found to the result set. result.AddRange(immediateDerivedTypes); // Now keep looping, using the set we found to spawn the next set of searches. currentTypes = immediateDerivedTypes; } } private static async Task FindImmediateMatchingMetadataTypesInMetadataReferenceAsync( SymbolAndProjectIdSet metadataTypes, Project project, Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> metadataTypeMatches, Compilation compilation, PortableExecutableReference reference, SymbolAndProjectIdSet result, CancellationToken cancellationToken) { // We store an index in SymbolTreeInfo of the *simple* metadata type name // to the names of the all the types that either immediately derive or // implement that type. Because the mapping is from the simple name // we might get false positives. But that's fine as we still use // 'metadataTypeMatches' to make sure the match is correct. var symbolTreeInfo = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync( project.Solution, reference, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false); // For each type we care about, see if we can find any derived types // in this index. foreach (var metadataType in metadataTypes) { var baseTypeName = metadataType.Symbol.Name; // For each derived type we find, see if we can map that back // to an actual symbol. Then check if that symbol actually fits // our criteria. foreach (var derivedType in symbolTreeInfo.GetDerivedMetadataTypes(baseTypeName, compilation, cancellationToken)) { if (derivedType != null && derivedType.Locations.Any(s_isInMetadata)) { if (metadataTypeMatches(metadataTypes, derivedType)) { result.Add(SymbolAndProjectId.Create(derivedType, project.Id)); } } } } } private static bool TypeDerivesFrom( SymbolAndProjectIdSet metadataTypes, INamedTypeSymbol type, bool transitive) { if (transitive) { for (var current = type.BaseType; current != null; current = current.BaseType) { if (metadataTypes.Contains( SymbolAndProjectId.Create(current.OriginalDefinition, projectId: null))) { return true; } } return false; } else { return metadataTypes.Contains( SymbolAndProjectId.Create(type.BaseType?.OriginalDefinition, projectId: null)); } } private static bool TypeImplementsFrom( SymbolAndProjectIdSet metadataTypes, INamedTypeSymbol type, bool transitive) { var interfaces = transitive ? type.AllInterfaces : type.Interfaces; foreach (var interfaceType in interfaces) { if (metadataTypes.Contains(SymbolAndProjectId.Create(interfaceType.OriginalDefinition, projectId: null))) { return true; } } return false; } private static async Task AddSourceTypesInProjectAsync( SymbolAndProjectIdSet sourceAndMetadataTypes, Project project, Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> sourceTypeImmediatelyMatches, Func<INamedTypeSymbol, bool> shouldContinueSearching, bool transitive, SymbolAndProjectIdSet finalResult, CancellationToken cancellationToken) { // We're going to be sweeping over this project over and over until we reach a // fixed point. In order to limit GC and excess work, we cache all the semantic // models and DeclaredSymbolInfo for hte documents we look at. // Because we're only processing a project at a time, this is not an issue. var cachedModels = new ConcurrentSet<SemanticModel>(); var typesToSearchFor = CreateSymbolAndProjectIdSet(); typesToSearchFor.AddAll(sourceAndMetadataTypes); var projectIndex = await ProjectIndex.GetIndexAsync(project, cancellationToken).ConfigureAwait(false); var localBuffer = CreateSymbolAndProjectIdSet(); // As long as there are new types to search for, keep looping. while (typesToSearchFor.Count > 0) { localBuffer.Clear(); foreach (var type in typesToSearchFor) { switch (type.Symbol.SpecialType) { case SpecialType.System_Object: await AddMatchingTypesAsync( cachedModels, projectIndex.ClassesThatMayDeriveFromSystemObject, localBuffer, predicateOpt: n => n.BaseType?.SpecialType == SpecialType.System_Object, cancellationToken: cancellationToken).ConfigureAwait(false); break; case SpecialType.System_ValueType: await AddMatchingTypesAsync( cachedModels, projectIndex.ValueTypes, localBuffer, predicateOpt: null, cancellationToken: cancellationToken).ConfigureAwait(false); break; case SpecialType.System_Enum: await AddMatchingTypesAsync( cachedModels, projectIndex.Enums, localBuffer, predicateOpt: null, cancellationToken: cancellationToken).ConfigureAwait(false); break; case SpecialType.System_MulticastDelegate: await AddMatchingTypesAsync( cachedModels, projectIndex.Delegates, localBuffer, predicateOpt: null, cancellationToken: cancellationToken).ConfigureAwait(false); break; } await AddTypesThatDeriveFromNameAsync( sourceTypeImmediatelyMatches, cachedModels, typesToSearchFor, projectIndex, localBuffer, type.Symbol.Name, cancellationToken).ConfigureAwait(false); } // Clear out the information about the types we're looking for. We'll // fill these in if we discover any more types that we need to keep searching // for. typesToSearchFor.Clear(); foreach (var derivedType in localBuffer) { if (finalResult.Add(derivedType)) { if (transitive && shouldContinueSearching(derivedType.Symbol)) { typesToSearchFor.Add(derivedType); } } } } s_setPool.ClearAndFree(localBuffer); } private static bool ImmediatelyDerivesOrImplementsFrom( SymbolAndProjectIdSet typesToSearchFor, INamedTypeSymbol type) { if (typesToSearchFor.Contains(SymbolAndProjectId.Create(type.BaseType?.OriginalDefinition, projectId: null))) { return true; } foreach (var interfaceType in type.Interfaces) { if (typesToSearchFor.Contains(SymbolAndProjectId.Create(interfaceType.OriginalDefinition, projectId: null))) { return true; } } return false; } private static async Task AddTypesThatDeriveFromNameAsync( Func<SymbolAndProjectIdSet, INamedTypeSymbol, bool> typeImmediatelyMatches, ConcurrentSet<SemanticModel> cachedModels, SymbolAndProjectIdSet typesToSearchFor, ProjectIndex index, SymbolAndProjectIdSet result, string name, CancellationToken cancellationToken) { foreach (var (document, info) in index.NamedTypes[name]) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); cachedModels.Add(semanticModel); var resolvedType = info.TryResolve(semanticModel, cancellationToken); if (resolvedType is INamedTypeSymbol namedType && typeImmediatelyMatches(typesToSearchFor, namedType)) { result.Add(new SymbolAndProjectId<INamedTypeSymbol>(namedType, document.Project.Id)); } } } private static async Task AddMatchingTypesAsync( ConcurrentSet<SemanticModel> cachedModels, MultiDictionary<Document, DeclaredSymbolInfo> documentToInfos, SymbolAndProjectIdSet result, Func<INamedTypeSymbol, bool> predicateOpt, CancellationToken cancellationToken) { foreach (var (document, infos) in documentToInfos) { Debug.Assert(infos.Count > 0); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); cachedModels.Add(semanticModel); foreach (var info in infos) { var resolvedSymbol = info.TryResolve(semanticModel, cancellationToken); if (resolvedSymbol is INamedTypeSymbol namedType) { if (predicateOpt == null || predicateOpt(namedType)) { result.Add(new SymbolAndProjectId<INamedTypeSymbol>(namedType, document.Project.Id)); } } } } } private static SymbolAndProjectIdSet CreateSymbolAndProjectIdSet() { return s_setPool.Allocate(); } } }
48.012151
231
0.604064
[ "Apache-2.0" ]
20chan/roslyn
src/Workspaces/Core/Portable/FindSymbols/FindReferences/DependentTypeFinder.cs
39,518
C#
namespace Nivaes.App.Cross.Mobile.Droid.Sample { [Android.Runtime.Preserve(AllMembers = true)] public class LinkerPleaseInclude { //public void Include(MultiDexApplication multiDexApplication) //{ // viewModel = new WalkthroughViewModel((IMvxLogProvider)null, (IMvxNavigationService)null); // activity = new WalkthroughActivity(); //} } }
30.923077
103
0.664179
[ "MIT" ]
Nivaes/Nivaes.App.Cross
Samples/Nivaes.App.Cross.Mobile.Droid.Sample/Components/LinkerPleaseInclude/LinkerPleaseInclude.cs
404
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using LinqToDB; using LinqToDB.Data; using LinqToDB.Expressions; using LinqToDB.Extensions; using LinqToDB.Mapping; using LinqToDB.SqlQuery; using Newtonsoft.Json; using NUnit.Framework; namespace Tests.Playground { [AttributeUsage(AttributeTargets.Property)] public class JSonContentAttribute : Attribute { } public static class MappingHelper { private static MethodInfo _deserializeMethod; private static MethodInfo _serializeMethod; private static ConstructorInfo _dataParamContructor; static MappingHelper() { _deserializeMethod = MemberHelper.MethodOf(() => JsonConvert.DeserializeObject(null, typeof(int))); _serializeMethod = MemberHelper.MethodOf(() => JsonConvert.SerializeObject(null)); _dataParamContructor = typeof(DataParameter).GetConstructor(new[] { typeof(string), typeof(object) }); } public static void GenerateConvertorsForTables(Type dataConnectionType, MappingSchema ms) { var propsWithTables = dataConnectionType.GetProperties() .Where(p => typeof(IQueryable<>).IsSameOrParentOf(p.PropertyType)); var types = propsWithTables.Select(p => p.PropertyType.GenericTypeArguments[0]).Distinct().ToArray(); foreach (var t in types) { GenerateConvertors(t, ms); } } public static void GenerateConvertors(Type entityType, MappingSchema ms) { foreach (var propertyInfo in entityType.GetProperties().Where(p => p.GetCustomAttribute(typeof(JSonContentAttribute)) != null)) { // emulating inParam => JsonConvert.DeserializeObject(inParam, propertyInfo.PropertyType) var inParam = Expression.Parameter(typeof(string)); var lambda = Expression.Lambda( Expression.Convert( Expression.Call(null, _deserializeMethod, inParam, Expression.Constant(propertyInfo.PropertyType)), propertyInfo.PropertyType), inParam); ms.SetConvertExpression(typeof(string), propertyInfo.PropertyType, lambda); var inObjParam = Expression.Parameter(propertyInfo.PropertyType); var lambdaSql = Expression.Lambda( Expression.New(_dataParamContructor, Expression.Constant("p"), Expression.Call(null, _serializeMethod, inObjParam)) , inObjParam); ms.SetConvertExpression(propertyInfo.PropertyType, typeof(DataParameter), lambdaSql); } } } public class MyDataConnection : DataConnection { private static MappingSchema _convertorSchema; static MyDataConnection() { _convertorSchema = new MappingSchema(); MappingHelper.GenerateConvertorsForTables(typeof(MyDataConnection), _convertorSchema); } public MyDataConnection(string providerName, string connectionString, MappingSchema mappingSchema) : base(providerName, connectionString, mappingSchema) { AddMappingSchema(_convertorSchema); } public MyDataConnection(string configurationString) : base(configurationString) { AddMappingSchema(_convertorSchema); } public ITable<SampleClass> SampleClass => GetTable<SampleClass>(); } [Table] public class SampleClass { [Column] public int Id { get; set; } [Column(DataType = DataType.VarChar, Length = 4000), JSonContent] public DataClass Data { get; set; } } public class DataClass { public string Property1 { get; set; } } public static class Json { class JsonValueBuilder : Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var pathExpr = builder.Arguments[0]; if (pathExpr.NodeType != ExpressionType.MemberAccess) throw new NotSupportedException(); var pathList = new List<Expression>(); var current = pathExpr; while (true) { pathList.Add(current); if (current.NodeType == ExpressionType.MemberAccess) { current = ((MemberExpression) current).Expression; } else break; } pathList.Reverse(); var entity = pathList[0]; var field = pathList[1]; var fieldSql = builder.ConvertExpressionToSql(field); builder.AddParameter("field", fieldSql); var propPathStr = "$"; for (int i = 2; i < pathList.Count; i++) { propPathStr += "." + ((MemberExpression) pathList[i]).Member.Name; } builder.AddParameter("propPath", new SqlValue(propPathStr)); } } [Sql.Extension("JSON_VALUE({field}, {propPath})", Precedence = Precedence.Primary, BuilderType = typeof(JsonValueBuilder), ServerSideOnly = true, CanBeNull = false)] public static string Value(object path) { throw new NotImplementedException(); } } [TestFixture] public class JsonConvertTests : TestBase { [Test] public void SampleSelectTest([IncludeDataSources(false, TestProvName.SqlAzure)] string context) { using (var db = new MyDataConnection(context)) using (var table = db.CreateLocalTable<SampleClass>()) { db.Insert(new SampleClass { Id = 1, Data = new DataClass { Property1 = "Pr1" } }); var objects = table.Where(t => Json.Value(t.Data.Property1) == "Pr1") .ToArray(); Assert.That(!db.LastQuery.Contains("IS NULL")); Assert.AreEqual(1, objects.Length); Assert.AreEqual("Pr1", objects[0].Data.Property1); } } } }
29.331522
168
0.700019
[ "MIT" ]
BlackballSoftware/linq2db
Tests/Linq/Samples/JsonConvertTests.cs
5,399
C#
public class Burger { public Burger(BurgerBuilder burgerBuilder) { this.size = burgerBuilder.Size; this.hasLettuce = burgerBuilder.HasLettuce; this.hasPepproni = burgerBuilder.HasPepproni; this.hasTomato = burgerBuilder.HasTomato; } private int size; private bool hasPepproni; private bool hasTomato; private bool hasLettuce; }
27.642857
53
0.692506
[ "MIT" ]
sivachamarthi/designpatterns-csharp
CreationalPatterns/04-Builder/Burger.cs
387
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.EventGrid.V20200401Preview.Inputs { /// <summary> /// Information about the storage queue destination for an event subscription. /// </summary> public sealed class StorageQueueEventSubscriptionDestinationArgs : Pulumi.ResourceArgs { /// <summary> /// Type of the endpoint for the event subscription destination. /// </summary> [Input("endpointType", required: true)] public Input<string> EndpointType { get; set; } = null!; /// <summary> /// The name of the Storage queue under a storage account that is the destination of an event subscription. /// </summary> [Input("queueName")] public Input<string>? QueueName { get; set; } /// <summary> /// The Azure Resource ID of the storage account that contains the queue that is the destination of an event subscription. /// </summary> [Input("resourceId")] public Input<string>? ResourceId { get; set; } public StorageQueueEventSubscriptionDestinationArgs() { } } }
34.439024
130
0.657224
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/EventGrid/V20200401Preview/Inputs/StorageQueueEventSubscriptionDestinationArgs.cs
1,412
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace POSH_sharp.sys.strict { /// <summary> /// A drive element. /// </summary> public class DriveElement : Element { internal Trigger trigger; private Object root; private object element; private long maxFreq; private long lastFired; protected internal List<Behaviour> behaviours; Agent agent; public bool isLatched { get; internal protected set; } // TODO: replace root which should be a polymoph type (maybe create superclass) /// <summary> /// Initialises the drive element. /// /// The log domain is set to [AgentName].DE.[element_name] /// </summary> /// <param name="agent">The element's agent.</param> /// <param name="elementName">The name of the drive element.</param> /// <param name="trigger">The trigger of the element.</param> /// <param name="root">The element's root element. /// root is either POSH.strict.Action, POSH.strict.Competence or POSH.strict.ActionPattern /// </param> /// <param name="maxFreq">The maximum frequency at which is element is /// fired. The frequency is given in milliseconds between /// invocation. A negative number disables this feature.</param> public DriveElement(Agent agent, string elementName, Trigger trigger, Object root, long maxFreq) : base(string.Format("DE.{0}", elementName), agent) { this.name = elementName; this.trigger = trigger; this.root = root; this.element = root; this.maxFreq = maxFreq; // the timestamp when it was last fired this.lastFired = -100000L; log.Debug("Created"); this.agent = agent; this.isLatched = false; this.behaviours = new List<Behaviour>(); foreach (POSHSense sense in trigger.senses) this.behaviours.Add(sense.behaviour); } /// <summary> /// Resets the drive element to its root element, /// and resets the firing frequency. /// </summary> public override void reset() { log.Debug("Reset"); element = root; lastFired = -100000L; } /// <summary> /// Returns if the element is ready to be fired. /// /// The element is ready to be fired if its trigger is /// satisfied and if the time since the last firing is /// larger than the one given by C{maxFreq}. The time of the /// last firing is determined by the timestamp given /// to L{isReady} when it was called the last time and returned /// True. This implies that the element has to be fired /// every time when this method returns True. /// </summary> /// <param name="timeStamp">The current timestamp in milliseconds</param> /// <returns></returns> public override bool isReady(long timeStamp) { if (trigger.fire()) if (maxFreq < 0 || timeStamp - lastFired > +maxFreq) { lastFired = timeStamp; return true; } else { log.Debug("Max. firing frequency exceeded"); } return false; } /// <summary> /// Fires the drive element. /// /// This method fires the current drive element and always /// returns None. It uses the slip-stack architecture to determine /// the element to fire in the next step. /// </summary> /// <returns>The result returned is null.</returns> public override FireResult fire() { FireResult result; log.Debug("Fired"); // if our element is an action, we just fire it and do // nothing afterwards. That's because we can only have an action // as an element, if it is the drive element's root element. // Hence, we didn't descend in the plan tree and can keep // the same element. if (element is POSHAction || element.GetType().IsSubclassOf(typeof(POSHAction))) { ((POSHAction)element).fire(); element = root; return null; } // the element is a competence or an action pattern result = ((ElementCollection)element).fire(); if (result.continueExecution()) { // if we have a new next element, store it as the next // element to execute CopiableElement next = result.nextElement(); if (next is CopiableElement) element = next; } else // we were told not to continue the execution -> back to root // We must not call reset() here, as that would also reset // the firing frequency of the element. element = root; return null; } public override CopiableElement copy() { throw new NotImplementedException("DriveElement.copy() is never supposed to be called"); } } }
35.288462
104
0.544233
[ "MIT" ]
domhauton/CM30229-UT2004-Bot
core/sys/DriveElement.cs
5,507
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2019 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: Numidium // // Notes: // using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using DaggerfallWorkshop.Utility; using DaggerfallConnect; using DaggerfallConnect.Arena2; using DaggerfallConnect.Utility; using DaggerfallWorkshop.Game.Serialization; using DaggerfallWorkshop.Game.UserInterfaceWindows; using DaggerfallWorkshop.Game.Entity; using DaggerfallWorkshop.Game.MagicAndEffects; namespace DaggerfallWorkshop.Game { /// <summary> /// Assist player controller to enter and exit building interiors and dungeons. /// Should be attached to player object with PlayerGPS for climate tracking. /// </summary> public class PlayerEnterExit : MonoBehaviour { const HideFlags defaultHideFlags = HideFlags.None; UnderwaterFog underwaterFog; DaggerfallUnity dfUnity; CharacterController controller; bool isPlayerInside = false; bool isPlayerInsideDungeon = false; bool isPlayerInsideDungeonCastle = false; bool isPlayerInsideSpecialArea = false; bool isPlayerInsideOpenShop = false; bool isPlayerSwimming = false; bool isPlayerSubmerged = false; bool isPlayerInSunlight = false; bool isPlayerInHolyPlace = false; bool isRespawning = false; bool lastInteriorStartFlag; bool displayAfloatMessage = false; DaggerfallInterior interior; DaggerfallDungeon dungeon; StreamingWorld world; PlayerGPS playerGPS; Entity.DaggerfallEntityBehaviour player; LevitateMotor levitateMotor; List<StaticDoor> exteriorDoors = new List<StaticDoor>(); public GameObject ExteriorParent; public GameObject InteriorParent; public GameObject DungeonParent; public DaggerfallLocation OverrideLocation; int lastPlayerDungeonBlockIndex = -1; DFLocation.DungeonBlock playerDungeonBlockData = new DFLocation.DungeonBlock(); public short blockWaterLevel = 10000; DFLocation.BuildingTypes buildingType; ushort factionID = 0; PlayerGPS.DiscoveredBuilding buildingDiscoveryData; DaggerfallLocation holidayTextLocation; bool holidayTextPrimed = false; float holidayTextTimer = 0f; /// <summary> /// Gets player world context. /// </summary> public WorldContext WorldContext { get { return GetWorldContext(); } } /// <summary> /// Gets start flag from most recent interior transition. /// Helps inform other systems if first-time load or enter/exit transition /// </summary> public bool LastInteriorStartFlag { get { return lastInteriorStartFlag; } } /// <summary> /// True when player is inside any structure. /// </summary> public bool IsPlayerInside { get { return isPlayerInside; } } /// <summary> /// True only when player is inside a building. /// </summary> public bool IsPlayerInsideBuilding { get { return (IsPlayerInside && !IsPlayerInsideDungeon); } } /// <summary> /// True only when player is inside a dungeon. /// </summary> public bool IsPlayerInsideDungeon { get { return isPlayerInsideDungeon; } } /// <summary> /// True only when player inside castle blocks of a dungeon. /// For example, main hall in Daggerfall castle. /// </summary> public bool IsPlayerInsideDungeonCastle { get { return isPlayerInsideDungeonCastle; } } /// <summary> /// True only when player inside special blocks of a dungeon. /// For example, treasure room in Daggerfall castle. /// </summary> public bool IsPlayerInsideSpecialArea { get { return isPlayerInsideSpecialArea; } } /// <summary> /// True when player is inside an open shop. /// Set upon entry, so doesn't matter if shop 'closes' with player inside. /// </summary> public bool IsPlayerInsideOpenShop { get { return isPlayerInsideOpenShop; } set { isPlayerInsideOpenShop = value; } } /// <summary> /// True when player is swimming in water. /// </summary> public bool IsPlayerSwimming { get { return isPlayerSwimming; } set { isPlayerSwimming = value; } } /// <summary> /// True when player is submerged in water. /// </summary> public bool IsPlayerSubmerged { get { return isPlayerSubmerged; } } /// <summary> /// True when player is in sunlight. /// </summary> public bool IsPlayerInSunlight { get { return isPlayerInSunlight; } } /// <summary> /// True when player is in darkness. /// Same as !IsPlayerInSunlight. /// </summary> public bool IsPlayerInDarkness { get { return !isPlayerInSunlight; } } /// <summary> /// True when player is in a holy place. /// Holy places include all Temples and guildhalls of the Fighter Trainers (faction #849) /// https://en.uesp.net/wiki/Daggerfall:ClassMaker#Special_Disadvantages /// Refreshed once per game minute. /// </summary> public bool IsPlayerInHolyPlace { get { return isPlayerInHolyPlace; } } /// <summary> /// True when a player respawn is in progress. /// e.g. After loading a game or teleporting back to a marked location. /// </summary> public bool IsRespawning { get { return isRespawning; } } /// <summary> /// Gets current player dungeon. /// Only valid when player is inside a dungeon. /// </summary> public DaggerfallDungeon Dungeon { get { return dungeon; } } /// <summary> /// Gets information about current player dungeon block. /// Only valid when player is inside a dungeon. /// </summary> public DFLocation.DungeonBlock DungeonBlock { get { return playerDungeonBlockData; } } /// <summary> /// Gets current building interior. /// Only valid when player inside building. /// </summary> public DaggerfallInterior Interior { get { return interior; } } /// <summary> /// Gets current building type. /// Only valid when player inside building. /// </summary> public DFLocation.BuildingTypes BuildingType { get { return buildingType; } } /// <summary> /// Gets current building's faction ID. /// </summary> public uint FactionID { get { return factionID; } } /// <summary> /// Gets current building's discovery data. /// Only valid when player is inside a building. /// This is set every time player enters a building and is saved/loaded with each save game. /// Notes: /// Older save games will not carry this data until player exits and enters building again. /// When consuming this property, try to handle empty BuildingDiscoveryData (buildingKey == 0) if possible. /// </summary> public PlayerGPS.DiscoveredBuilding BuildingDiscoveryData { get { return buildingDiscoveryData; } internal set { buildingDiscoveryData = value; } } /// <summary> /// Gets or sets exterior doors of current interior. /// Returns empty array if player not inside. /// </summary> public StaticDoor[] ExteriorDoors { get { return exteriorDoors.ToArray(); } set { SetExteriorDoors(value); } } void Awake() { dfUnity = DaggerfallUnity.Instance; playerGPS = GetComponent<PlayerGPS>(); world = FindObjectOfType<StreamingWorld>(); player = GameManager.Instance.PlayerEntityBehaviour; } void Start() { // Wire event for when player enters a new location PlayerGPS.OnEnterLocationRect += PlayerGPS_OnEnterLocationRect; EntityEffectBroker.OnNewMagicRound += EntityEffectBroker_OnNewMagicRound; levitateMotor = GetComponent<LevitateMotor>(); underwaterFog = new UnderwaterFog(); } void Update() { // Track which dungeon block player is inside of if (dungeon && isPlayerInsideDungeon) { int playerBlockIndex = dungeon.GetPlayerBlockIndex(transform.position); if (playerBlockIndex != lastPlayerDungeonBlockIndex) { lastPlayerDungeonBlockIndex = playerBlockIndex; if (playerBlockIndex != -1) { dungeon.GetBlockData(playerBlockIndex, out playerDungeonBlockData); blockWaterLevel = playerDungeonBlockData.WaterLevel; isPlayerInsideDungeonCastle = playerDungeonBlockData.CastleBlock; SpecialAreaCheck(); } else { blockWaterLevel = 10000; isPlayerInsideDungeonCastle = false; isPlayerInsideSpecialArea = false; } //Debug.Log(string.Format("Player is now inside block {0}", playerDungeonBlockData.BlockName)); } if (playerBlockIndex != -1) { underwaterFog.UpdateFog(blockWaterLevel); } } if (holidayTextPrimed && holidayTextLocation != GameManager.Instance.StreamingWorld.CurrentPlayerLocationObject) { holidayTextTimer = 0; holidayTextPrimed = false; } // Count down holiday text display if (holidayTextTimer > 0) holidayTextTimer -= Time.deltaTime; if (holidayTextTimer <= 0 && holidayTextPrimed) { holidayTextPrimed = false; ShowHolidayText(); } // Underwater swimming logic should only be processed in dungeons at this time if (isPlayerInsideDungeon) { // NOTE: Player's y value in DF unity is 0.95 units off from classic, so subtracting it to get correct comparison if (blockWaterLevel == 10000 || (player.transform.position.y + (50 * MeshReader.GlobalScale) - 0.95f) >= (blockWaterLevel * -1 * MeshReader.GlobalScale)) { isPlayerSwimming = false; levitateMotor.IsSwimming = false; } else { if (!isPlayerSwimming) SendMessage("PlayLargeSplash", SendMessageOptions.DontRequireReceiver); isPlayerSwimming = true; levitateMotor.IsSwimming = true; } bool overEncumbered = (GameManager.Instance.PlayerEntity.CarriedWeight * 4 > 250); if ((overEncumbered && levitateMotor.IsSwimming) && !displayAfloatMessage && !GameManager.Instance.PlayerEntity.IsWaterWalking) { DaggerfallUI.AddHUDText(HardStrings.cannotFloat, 1.75f); displayAfloatMessage = true; } else if ((!overEncumbered || !levitateMotor.IsSwimming) && displayAfloatMessage) { displayAfloatMessage = false; } // Check if player is submerged and needs to start holding breath if (blockWaterLevel == 10000 || (player.transform.position.y + (76 * MeshReader.GlobalScale) - 0.95f) >= (blockWaterLevel * -1 * MeshReader.GlobalScale)) { isPlayerSubmerged = false; } else isPlayerSubmerged = true; } else { // Clear flags when not in a dungeon // don't clear swimming if we're outside on a water tile - MeteoricDragon if (GameManager.Instance.StreamingWorld.PlayerTileMapIndex != 0) isPlayerSwimming = false; isPlayerSubmerged = false; levitateMotor.IsSwimming = false; } // Player in sunlight or darkness isPlayerInSunlight = DaggerfallUnity.Instance.WorldTime.Now.IsDay && !IsPlayerInside; } #region Public Methods /// <summary> /// Respawn player at the specified world coordinates, optionally inside dungeon. /// </summary> public void RespawnPlayer( int worldX, int worldZ, bool insideDungeon = false, bool importEnemies = true) { RespawnPlayer(worldX, worldZ, insideDungeon, false, null, false, importEnemies); } /// <summary> /// Respawn player at the specified world coordinates, optionally inside dungeon or building. /// Player can be forced to respawn to closest start marker or origin. /// </summary> public void RespawnPlayer( int worldX, int worldZ, bool insideDungeon, bool insideBuilding, StaticDoor[] exteriorDoors = null, bool forceReposition = false, bool importEnemies = true, bool start = true) { // Mark any existing world data for destruction if (dungeon) { Destroy(dungeon.gameObject); } if (interior) { Destroy(interior.gameObject); } // Deregister all serializable objects SaveLoadManager.DeregisterAllSerializableGameObjects(); // Start respawn process isRespawning = true; SetExteriorDoors(exteriorDoors); StartCoroutine(Respawner(worldX, worldZ, insideDungeon, insideBuilding, forceReposition, importEnemies, start)); } IEnumerator Respawner(int worldX, int worldZ, bool insideDungeon, bool insideBuilding, bool forceReposition, bool importEnemies, bool start = true) { // Wait for end of frame so existing world data can be removed yield return new WaitForEndOfFrame(); // Store if player was inside a dungeon or building before respawning bool playerWasInDungeon = IsPlayerInsideDungeon; bool playerWasInBuilding = IsPlayerInsideBuilding; // Reset dungeon block on new spawn lastPlayerDungeonBlockIndex = -1; playerDungeonBlockData = new DFLocation.DungeonBlock(); // Reset inside state isPlayerInside = false; isPlayerInsideDungeon = false; isPlayerInsideDungeonCastle = false; blockWaterLevel = 10000; // Set player GPS coordinates playerGPS.WorldX = worldX; playerGPS.WorldZ = worldZ; // Set streaming world coordinates DFPosition pos = MapsFile.WorldCoordToMapPixel(worldX, worldZ); world.MapPixelX = pos.X; world.MapPixelY = pos.Y; // Get location at this position ContentReader.MapSummary summary; bool hasLocation = dfUnity.ContentReader.HasLocation(pos.X, pos.Y, out summary); if (!insideDungeon && !insideBuilding) { // Start outside EnableExteriorParent(); if (!forceReposition) { // Teleport to explicit world coordinates world.TeleportToWorldCoordinates(worldX, worldZ); } else { // Force reposition to closest start marker if available world.TeleportToCoordinates(pos.X, pos.Y, StreamingWorld.RepositionMethods.RandomStartMarker); } // Wait until world is ready while (world.IsInit) yield return new WaitForEndOfFrame(); // Raise transition exterior event if player was inside a dungeon or building // This helps inform other systems player has transitioned to exterior without clicking a door or reloading game if (playerWasInDungeon) RaiseOnTransitionDungeonExteriorEvent(); else if (playerWasInBuilding) RaiseOnTransitionExteriorEvent(); } else if (hasLocation && insideDungeon) { // Start in dungeon DFLocation location; world.TeleportToCoordinates(pos.X, pos.Y, StreamingWorld.RepositionMethods.None); dfUnity.ContentReader.GetLocation(summary.RegionIndex, summary.MapIndex, out location); StartDungeonInterior(location, true, importEnemies); world.suppressWorld = true; } else if (hasLocation && insideBuilding && exteriorDoors != null) { // Start in building DFLocation location; world.TeleportToCoordinates(pos.X, pos.Y, StreamingWorld.RepositionMethods.None); dfUnity.ContentReader.GetLocation(summary.RegionIndex, summary.MapIndex, out location); StartBuildingInterior(location, exteriorDoors[0], start); world.suppressWorld = true; } else { // All else fails teleport to map pixel DaggerfallUnity.LogMessage("Something went wrong! Teleporting to origin of nearest map pixel."); EnableExteriorParent(); world.TeleportToCoordinates(pos.X, pos.Y); } // Lower respawn flag isRespawning = false; RaiseOnRespawnerCompleteEvent(); } public void ShowHolidayText() { const int holidaysStartID = 8349; uint minutes = DaggerfallUnity.Instance.WorldTime.DaggerfallDateTime.ToClassicDaggerfallTime(); int holidayId = Formulas.FormulaHelper.GetHolidayId(minutes, GameManager.Instance.PlayerGPS.CurrentRegionIndex); if (holidayId != 0) { DaggerfallMessageBox messageBox = new DaggerfallMessageBox(DaggerfallUI.UIManager); messageBox.SetTextTokens(holidaysStartID + holidayId); messageBox.ClickAnywhereToClose = true; messageBox.ParentPanel.BackgroundColor = Color.clear; messageBox.ScreenDimColor = new Color32(0, 0, 0, 0); messageBox.Show(); } // Set holiday text timer to a somewhat large value so it doesn't show again and again if the player is repeatedly crossing the // border of a city. holidayTextTimer = 10f; } /// <summary> /// Helper to reposition player to anywhere in world either at load or during player. /// </summary> /// <param name="playerPosition">Player position data.</param> /// <param name="start">Use true if this is a load/start operation, otherwise false.</param> public void RestorePositionHelper(PlayerPositionData_v1 playerPosition, bool start, bool importEnemies) { // Raise reposition flag if terrain sampler changed // This is required as changing terrain samplers will invalidate serialized player coordinates // Make an exception for dungeons as exterior world does not matter bool repositionPlayer = false; if ((playerPosition.terrainSamplerName != DaggerfallUnity.Instance.TerrainSampler.ToString() || playerPosition.terrainSamplerVersion != DaggerfallUnity.Instance.TerrainSampler.Version) && !playerPosition.insideDungeon) { repositionPlayer = true; if (DaggerfallUI.Instance.DaggerfallHUD != null) DaggerfallUI.Instance.DaggerfallHUD.PopupText.AddText("Terrain sampler changed. Repositioning player."); } // Check exterior doors are included in save, we need these to exit building bool hasExteriorDoors; if (playerPosition.exteriorDoors == null || playerPosition.exteriorDoors.Length == 0) hasExteriorDoors = false; else hasExteriorDoors = true; // Raise reposition flag if player is supposed to start indoors but building has no doors if (playerPosition.insideBuilding && !hasExteriorDoors) { repositionPlayer = true; if (DaggerfallUI.Instance.DaggerfallHUD != null) DaggerfallUI.Instance.DaggerfallHUD.PopupText.AddText("Building has no exterior doors. Repositioning player."); } // Start the respawn process based on saved player location if (playerPosition.insideDungeon/* && !repositionPlayer*/) // Do not need to resposition outside for dungeons { // Start in dungeon RespawnPlayer( playerPosition.worldPosX, playerPosition.worldPosZ, true, importEnemies); } else if (playerPosition.insideBuilding && hasExteriorDoors && !repositionPlayer) { // Start in building RespawnPlayer( playerPosition.worldPosX, playerPosition.worldPosZ, playerPosition.insideDungeon, playerPosition.insideBuilding, playerPosition.exteriorDoors, false, false, start); } else { // Start outside RespawnPlayer( playerPosition.worldPosX, playerPosition.worldPosZ, false, false, null, repositionPlayer); } } #endregion #region Building Transitions /// <summary> /// Transition player through an exterior door into building interior. /// </summary> /// <param name="doorOwner">Parent transform owning door array..</param> /// <param name="door">Exterior door player clicked on.</param> public void TransitionInterior(Transform doorOwner, StaticDoor door, bool doFade = false, bool start = true) { // Store start flag lastInteriorStartFlag = start; // Ensure we have component references if (!ReferenceComponents()) return; // Copy owner position to door // This ensures the door itself is all we need to reposition interior // Useful when loading a save and doorOwner is null (as outside world does not exist) if (doorOwner) { door.ownerPosition = doorOwner.position; door.ownerRotation = doorOwner.rotation; } if (!start) { // Update scene cache from serializable state for exterior->interior transition SaveLoadManager.CacheScene(world.SceneName); // Explicitly deregister all stateful objects since exterior isn't destroyed SaveLoadManager.DeregisterAllSerializableGameObjects(true); // Clear all stateful objects from world loose object tracking world.ClearStatefulLooseObjects(); } // Raise event RaiseOnPreTransitionEvent(TransitionType.ToBuildingInterior, door); // Ensure expired rooms are removed GameManager.Instance.PlayerEntity.RemoveExpiredRentedRooms(); // Get climate ClimateBases climateBase = ClimateBases.Temperate; if (OverrideLocation) climateBase = OverrideLocation.Summary.Climate; else if (playerGPS) climateBase = ClimateSwaps.FromAPIClimateBase(playerGPS.ClimateSettings.ClimateType); // Layout interior // This needs to be done first so we know where the enter markers are GameObject newInterior = new GameObject(DaggerfallInterior.GetSceneName(playerGPS.CurrentLocation, door)); newInterior.hideFlags = defaultHideFlags; interior = newInterior.AddComponent<DaggerfallInterior>(); // Try to layout interior // If we fail for any reason, use that old chestnut "this house has nothing of value" try { interior.DoLayout(doorOwner, door, climateBase, buildingDiscoveryData); } catch (Exception e) { DaggerfallUI.AddHUDText(HardStrings.thisHouseHasNothingOfValue); Debug.LogException(e); Destroy(newInterior); return; } // Position interior directly inside of exterior // This helps with finding closest enter/exit point relative to player position interior.transform.position = door.ownerPosition + (Vector3)door.buildingMatrix.GetColumn(3); interior.transform.rotation = GameObjectHelper.QuaternionFromMatrix(door.buildingMatrix); // Position player in front of closest interior door Vector3 landingPosition = Vector3.zero; Vector3 foundDoorNormal = Vector3.zero; if (interior.FindClosestInteriorDoor(transform.position, out landingPosition, out foundDoorNormal)) { landingPosition += foundDoorNormal * (GameManager.Instance.PlayerController.radius + 0.1f); } else { // If no door found position player above closest enter marker if (interior.FindClosestEnterMarker(transform.position, out landingPosition)) { landingPosition += Vector3.up * (controller.height * 0.6f); } else { // Could not find an door or enter marker, probably not a valid interior Destroy(newInterior); return; } } // Enumerate all exterior doors belonging to this building DaggerfallStaticDoors exteriorStaticDoors = interior.ExteriorDoors; if (exteriorStaticDoors && doorOwner) { List<StaticDoor> buildingDoors = new List<StaticDoor>(); for (int i = 0; i < exteriorStaticDoors.Doors.Length; i++) { if (exteriorStaticDoors.Doors[i].recordIndex == door.recordIndex) { StaticDoor newDoor = exteriorStaticDoors.Doors[i]; newDoor.ownerPosition = doorOwner.position; newDoor.ownerRotation = doorOwner.rotation; buildingDoors.Add(newDoor); } } SetExteriorDoors(buildingDoors.ToArray()); } // Assign new interior to parent if (InteriorParent != null) newInterior.transform.parent = InteriorParent.transform; // Cache some information about this interior buildingType = interior.BuildingData.BuildingType; factionID = interior.BuildingData.FactionId; // Set player to landng position transform.position = landingPosition; SetStanding(); EnableInteriorParent(); // Add quest resources GameObjectHelper.AddQuestResourceObjects(SiteTypes.Building, interior.transform, interior.EntryDoor.buildingKey); // Update serializable state from scene cache for exterior->interior transition (unless new/load game) if (!start) SaveLoadManager.RestoreCachedScene(interior.name); // Raise event RaiseOnTransitionInteriorEvent(door, interior); // Fade in from black if (doFade) DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(); } /// <summary> /// Transition player through an interior door to building exterior. Player must be inside. /// Interior stores information about exterior, no need for extra params. /// </summary> public void TransitionExterior(bool doFade = false) { // Exit if missing required components or not currently inside if (!ReferenceComponents() || !interior || !isPlayerInside) return; // Redirect to coroutine verion for fade support if (doFade) { StartCoroutine(FadedTransitionExterior()); return; } // Perform transition BuildingTransitionExteriorLogic(); } private IEnumerator FadedTransitionExterior() { // Smash to black DaggerfallUI.Instance.FadeBehaviour.SmashHUDToBlack(); yield return new WaitForEndOfFrame(); // Perform transition BuildingTransitionExteriorLogic(); // Increase fade time if outside world not ready // This indicates a first-time transition on fresh load float fadeTime = 0.7f; if (!GameManager.Instance.StreamingWorld.IsInit) fadeTime = 1.5f; // Fade in from black DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(fadeTime); } private void BuildingTransitionExteriorLogic() { // Raise event RaiseOnPreTransitionEvent(TransitionType.ToBuildingExterior); // Update scene cache from serializable state for interior->exterior transition SaveLoadManager.CacheScene(interior.name); // Find closest door and position player outside of it StaticDoor closestDoor; Vector3 closestDoorPos = DaggerfallStaticDoors.FindClosestDoor(transform.position, ExteriorDoors, out closestDoor); Vector3 normal = DaggerfallStaticDoors.GetDoorNormal(closestDoor); Vector3 position = closestDoorPos + normal * (controller.radius * 3f); world.SetAutoReposition(StreamingWorld.RepositionMethods.Offset, position); EnableExteriorParent(); // Player is now outside building isPlayerInside = false; // Update serializable state from scene cache for interior->exterior transition SaveLoadManager.RestoreCachedScene(world.SceneName); // Fire event RaiseOnTransitionExteriorEvent(); } #endregion #region Dungeon Transitions /// <summary> /// Transition player through a dungeon entrance door into dungeon interior. /// </summary> /// <param name="doorOwner">Parent transform owning door array.</param> /// <param name="door">Exterior door player clicked on.</param> public void TransitionDungeonInterior(Transform doorOwner, StaticDoor door, DFLocation location, bool doFade = false) { // Ensure we have component references if (!ReferenceComponents()) return; // Reset dungeon block on entering dungeon lastPlayerDungeonBlockIndex = -1; playerDungeonBlockData = new DFLocation.DungeonBlock(); // Override location if specified if (OverrideLocation != null) { DFLocation overrideLocation = dfUnity.ContentReader.MapFileReader.GetLocation(OverrideLocation.Summary.RegionName, OverrideLocation.Summary.LocationName); if (overrideLocation.Loaded) location = overrideLocation; } // Raise event RaiseOnPreTransitionEvent(TransitionType.ToDungeonInterior, door); // Layout dungeon GameObject newDungeon = GameObjectHelper.CreateDaggerfallDungeonGameObject(location, DungeonParent.transform); newDungeon.hideFlags = defaultHideFlags; dungeon = newDungeon.GetComponent<DaggerfallDungeon>(); // Find start marker to position player if (!dungeon.StartMarker) { // Could not find a start marker Destroy(newDungeon); return; } EnableDungeonParent(); // Set to start position MovePlayerToMarker(dungeon.StartMarker); // Find closest dungeon exit door to orient player StaticDoor[] doors = DaggerfallStaticDoors.FindDoorsInCollections(dungeon.StaticDoorCollections, DoorTypes.DungeonExit); if (doors != null && doors.Length > 0) { Vector3 doorPos; int doorIndex; if (DaggerfallStaticDoors.FindClosestDoorToPlayer(transform.position, doors, out doorPos, out doorIndex)) { // Set player facing away from door PlayerMouseLook playerMouseLook = GameManager.Instance.PlayerMouseLook; if (playerMouseLook) { Vector3 normal = DaggerfallStaticDoors.GetDoorNormal(doors[doorIndex]); playerMouseLook.SetFacing(normal); } } } // Add quest resources GameObjectHelper.AddQuestResourceObjects(SiteTypes.Dungeon, dungeon.transform); // Raise event RaiseOnTransitionDungeonInteriorEvent(door, dungeon); // Fade in from black if (doFade) DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(); } /// <summary> /// Starts player inside dungeon with no exterior world. /// </summary> public void StartDungeonInterior(DFLocation location, bool preferEnterMarker = true, bool importEnemies = true) { // Ensure we have component references if (!ReferenceComponents()) return; // Raise event RaiseOnPreTransitionEvent(TransitionType.ToDungeonInterior); // Layout dungeon GameObject newDungeon = GameObjectHelper.CreateDaggerfallDungeonGameObject(location, DungeonParent.transform, importEnemies); newDungeon.hideFlags = defaultHideFlags; dungeon = newDungeon.GetComponent<DaggerfallDungeon>(); GameObject marker = null; if (preferEnterMarker && dungeon.EnterMarker != null) marker = dungeon.EnterMarker; else marker = dungeon.StartMarker; // Find start marker to position player if (!marker) { // Could not find marker DaggerfallUnity.LogMessage("No start or enter marker found for this dungeon. Aborting load."); Destroy(newDungeon); return; } EnableDungeonParent(); // Add quest resources - except foes, these are loaded from enemy save data GameObjectHelper.AddQuestResourceObjects(SiteTypes.Dungeon, dungeon.transform, 0, true, false, true); // Set to start position MovePlayerToMarker(marker); // Set player facing north PlayerMouseLook playerMouseLook = GameManager.Instance.PlayerMouseLook; if (playerMouseLook) playerMouseLook.SetFacing(Vector3.forward); // Raise event RaiseOnTransitionDungeonInteriorEvent(new StaticDoor(), dungeon); } /// <summary> /// Starts player inside building with no exterior world. /// </summary> public void StartBuildingInterior(DFLocation location, StaticDoor exteriorDoor, bool start = true) { // Store start flag lastInteriorStartFlag = start; // Ensure we have component references if (!ReferenceComponents()) return; // Discover building GameManager.Instance.PlayerGPS.DiscoverBuilding(exteriorDoor.buildingKey); TransitionInterior(null, exteriorDoor, false, start); } public void DisableAllParents(bool cleanup = true) { if (!GameManager.Instance.IsReady) GameManager.Instance.GetProperties(); if (cleanup) { if (dungeon) Destroy(dungeon.gameObject); if (interior) Destroy(interior.gameObject); } if (ExteriorParent != null) ExteriorParent.SetActive(false); if (InteriorParent != null) InteriorParent.SetActive(false); if (DungeonParent != null) DungeonParent.SetActive(false); } /// <summary> /// Enable ExteriorParent. /// </summary> public void EnableExteriorParent(bool cleanup = true) { if (cleanup) { if (dungeon) Destroy(dungeon.gameObject); if (interior) Destroy(interior.gameObject); SetExteriorDoors(null); } DisableAllParents(false); if (ExteriorParent != null) ExteriorParent.SetActive(true); world.suppressWorld = false; isPlayerInside = false; isPlayerInsideDungeon = false; GameManager.UpdateShadowDistance(); } /// <summary> /// Enable InteriorParent. /// </summary> public void EnableInteriorParent(bool cleanup = true) { if (cleanup) { if (dungeon) Destroy(dungeon.gameObject); } DisableAllParents(false); if (InteriorParent != null) InteriorParent.SetActive(true); isPlayerInside = true; isPlayerInsideDungeon = false; GameManager.UpdateShadowDistance(); } /// <summary> /// Enable DungeonParent. /// </summary> public void EnableDungeonParent(bool cleanup = true) { if (cleanup) { if (interior) Destroy(interior.gameObject); } DisableAllParents(false); if (DungeonParent != null) DungeonParent.SetActive(true); isPlayerInside = true; isPlayerInsideDungeon = true; GameManager.UpdateShadowDistance(); } public void MovePlayerToMarker(GameObject marker) { if (!isPlayerInsideDungeon || !marker) return; // Set player to start position transform.position = marker.transform.position + Vector3.up * (controller.height * 0.6f); // Fix player standing SetStanding(); // Raise event RaiseOnMovePlayerToDungeonStartEvent(); } public void MovePlayerToDungeonStart() { MovePlayerToMarker(dungeon.StartMarker); } /// <summary> /// Player is leaving dungeon, transition them back outside. /// </summary> public void TransitionDungeonExterior(bool doFade = false) { if (!ReferenceComponents() || !dungeon || !isPlayerInsideDungeon) return; // Redirect to coroutine verion for fade support if (doFade) { StartCoroutine(FadedTransitionDungeonExterior()); return; } // Perform transition DungeonTransitionExteriorLogic(); } private IEnumerator FadedTransitionDungeonExterior() { // Smash to black DaggerfallUI.Instance.FadeBehaviour.SmashHUDToBlack(); yield return new WaitForEndOfFrame(); // Perform transition DungeonTransitionExteriorLogic(); // Increase fade time if outside world not ready // This indicates a first-time transition on fresh load float fadeTime = 0.7f; if (!GameManager.Instance.StreamingWorld.IsInit) fadeTime = 1.5f; // Fade in from black DaggerfallUI.Instance.FadeBehaviour.FadeHUDFromBlack(fadeTime); } private void DungeonTransitionExteriorLogic() { // Raise event RaiseOnPreTransitionEvent(TransitionType.ToDungeonExterior); EnableExteriorParent(); // Player is now outside dungeon isPlayerInside = false; isPlayerInsideDungeon = false; isPlayerInsideDungeonCastle = false; lastPlayerDungeonBlockIndex = -1; playerDungeonBlockData = new DFLocation.DungeonBlock(); // Position player to door world.SetAutoReposition(StreamingWorld.RepositionMethods.DungeonEntrance, Vector3.zero); // Raise event RaiseOnTransitionDungeonExteriorEvent(); } #endregion #region Private Methods private void SpecialAreaCheck() { if (!isPlayerInsideDungeon) { isPlayerInsideSpecialArea = false; return; } switch (playerDungeonBlockData.BlockName) { case "S0000161.RDB": // Daggerfall treasure room isPlayerInsideSpecialArea = true; break; default: isPlayerInsideSpecialArea = false; break; } } private void SetStanding() { // Snap player to ground RaycastHit hit; Ray ray = new Ray(transform.position, Vector3.down); if (Physics.Raycast(ray, out hit, controller.height * 2f)) { // Clear falling damage so player doesn't take damage if they transitioned into a dungeon while jumping GameManager.Instance.AcrobatMotor.ClearFallingDamage(); // Position player at hit position plus just over half controller height up Vector3 pos = hit.point; pos.y += controller.height / 2f + 0.25f; transform.position = pos; } } private bool ReferenceComponents() { // Look for required components if (controller == null) controller = GetComponent<CharacterController>(); // Fail if missing required components if (dfUnity == null || controller == null) return false; return true; } private void SetExteriorDoors(StaticDoor[] doors) { exteriorDoors.Clear(); if (doors != null && doors.Length > 0) exteriorDoors.AddRange(doors); } private WorldContext GetWorldContext() { if (!IsPlayerInside) return WorldContext.Exterior; else if (IsPlayerInsideBuilding) return WorldContext.Interior; else if (isPlayerInsideDungeon) return WorldContext.Dungeon; else return WorldContext.Nothing; } #endregion #region Event Arguments /// <summary> /// Types of transition encountered by event system. /// </summary> public enum TransitionType { NotDefined, ToBuildingInterior, ToBuildingExterior, ToDungeonInterior, ToDungeonExterior, } /// <summary> /// Arguments for PlayerEnterExit events. /// All interior/exterior/dungeon transitions use these arguments. /// Valid members will depend on which transition event was fired. /// </summary> public class TransitionEventArgs : System.EventArgs { /// <summary>The type of transition.</summary> public TransitionType TransitionType { get; set; } /// <summary>The exterior StaticDoor clicked to initiate transition. For exterior to interior transitions only.</summary> public StaticDoor StaticDoor { get; set; } /// <summary>The newly instanced building interior. For building interior transitions only.</summary> public DaggerfallInterior DaggerfallInterior { get; set; } /// <summary>The newly instanced dungeon interior. For dungeon interior transitions only.</summary> public DaggerfallDungeon DaggerfallDungeon { get; set; } /// <summary>Constructor.</summary> public TransitionEventArgs() { TransitionType = PlayerEnterExit.TransitionType.NotDefined; StaticDoor = new StaticDoor(); DaggerfallInterior = null; DaggerfallDungeon = null; } /// <summary>Constructor helper.</summary> public TransitionEventArgs(TransitionType transitionType) : base() { this.TransitionType = transitionType; } /// <summary>Constructor helper.</summary> public TransitionEventArgs(TransitionType transitionType, StaticDoor staticDoor, DaggerfallInterior daggerfallInterior = null, DaggerfallDungeon daggerfallDungeon = null) : base() { this.TransitionType = transitionType; this.StaticDoor = staticDoor; this.DaggerfallInterior = daggerfallInterior; this.DaggerfallDungeon = daggerfallDungeon; } } #endregion #region Event Handlers // Notify player when they enter location rect // For exterior towns, print out "You are entering %s". // For exterior dungeons, print out flavour text. private void PlayerGPS_OnEnterLocationRect(DFLocation location) { const int set1StartID = 500; const int set2StartID = 520; if (playerGPS && !isPlayerInside) { if (location.MapTableData.LocationType == DFRegion.LocationTypes.DungeonLabyrinth || location.MapTableData.LocationType == DFRegion.LocationTypes.DungeonKeep || location.MapTableData.LocationType == DFRegion.LocationTypes.DungeonRuin || location.MapTableData.LocationType == DFRegion.LocationTypes.Graveyard) { // Get text ID based on set start and dungeon type index int dungeonTypeIndex = (int)location.MapTableData.DungeonType; int set1ID = set1StartID + dungeonTypeIndex; int set2ID = set2StartID + dungeonTypeIndex; // Select two sets of flavour text based on dungeon type string flavourText1 = DaggerfallUnity.Instance.TextProvider.GetRandomText(set1ID); string flavourText2 = DaggerfallUnity.Instance.TextProvider.GetRandomText(set2ID); // Show flavour text a bit longer than in classic DaggerfallUI.AddHUDText(flavourText1, 3); DaggerfallUI.AddHUDText(flavourText2, 3); } else if (location.MapTableData.LocationType != DFRegion.LocationTypes.Coven && location.MapTableData.LocationType != DFRegion.LocationTypes.HomeYourShips) { // Show "You are entering %s" string youAreEntering = HardStrings.youAreEntering; youAreEntering = youAreEntering.Replace("%s", location.Name); DaggerfallUI.AddHUDText(youAreEntering, 2); // Check room rentals in this location, and display how long any rooms are rented for int mapId = playerGPS.CurrentLocation.MapTableData.MapId; PlayerEntity playerEntity = GameManager.Instance.PlayerEntity; playerEntity.RemoveExpiredRentedRooms(); List<RoomRental_v1> rooms = playerEntity.GetRentedRooms(mapId); if (rooms.Count > 0) { foreach (RoomRental_v1 room in rooms) { string remainingHours = PlayerEntity.GetRemainingHours(room).ToString(); DaggerfallUI.AddHUDText(HardStrings.youHaveRentedRoom.Replace("%s", room.name).Replace("%d", remainingHours), 6); } } if (holidayTextTimer <= 0 && !holidayTextPrimed) { holidayTextTimer = 2.5f; // Short delay to give save game fade-in time to finish holidayTextPrimed = true; } holidayTextLocation = GameManager.Instance.StreamingWorld.CurrentPlayerLocationObject; // note Nystul: this next line is not enough to manage questor dictionary update since player might load a savegame in an interior - // so this never gets triggered and questor list is rebuild always as a consequence // a better thing is if talkmanager handles all this by itself without making changes to PlayerEnterExit necessary and use events/delegates // -> so I will outcomment next line but leave it in so that original author stumbles across this comment // fixed this in TalkManager class // TalkManager.Instance.LastExteriorEntered = location.LocationIndex; } } } private void EntityEffectBroker_OnNewMagicRound() { // Player in holy place isPlayerInHolyPlace = false; if (WorldContext == WorldContext.Interior && interior != null) { if (interior.BuildingData.BuildingType == DFLocation.BuildingTypes.Temple || interior.BuildingData.FactionId == (int)FactionFile.FactionIDs.Fighter_Trainers) isPlayerInHolyPlace = true; } } #endregion #region Events // OnPreTransition - Called PRIOR to any transition, other events called AFTER transition. public delegate void OnPreTransitionEventHandler(TransitionEventArgs args); public static event OnPreTransitionEventHandler OnPreTransition; protected virtual void RaiseOnPreTransitionEvent(TransitionType transitionType) { TransitionEventArgs args = new TransitionEventArgs(transitionType); if (OnPreTransition != null) OnPreTransition(args); } protected virtual void RaiseOnPreTransitionEvent(TransitionType transitionType, StaticDoor staticDoor) { TransitionEventArgs args = new TransitionEventArgs(transitionType, staticDoor); if (OnPreTransition != null) OnPreTransition(args); } // OnTransitionInterior public delegate void OnTransitionInteriorEventHandler(TransitionEventArgs args); public static event OnTransitionInteriorEventHandler OnTransitionInterior; protected virtual void RaiseOnTransitionInteriorEvent(StaticDoor staticDoor, DaggerfallInterior daggerfallInterior) { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToBuildingInterior, staticDoor, daggerfallInterior); if (OnTransitionInterior != null) OnTransitionInterior(args); } // OnTransitionExterior public delegate void OnTransitionExteriorEventHandler(TransitionEventArgs args); public static event OnTransitionExteriorEventHandler OnTransitionExterior; protected virtual void RaiseOnTransitionExteriorEvent() { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToBuildingExterior); if (OnTransitionExterior != null) OnTransitionExterior(args); } // OnTransitionDungeonInterior public delegate void OnTransitionDungeonInteriorEventHandler(TransitionEventArgs args); public static event OnTransitionDungeonInteriorEventHandler OnTransitionDungeonInterior; protected virtual void RaiseOnTransitionDungeonInteriorEvent(StaticDoor staticDoor, DaggerfallDungeon daggerfallDungeon) { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToDungeonInterior, staticDoor, null, daggerfallDungeon); if (OnTransitionDungeonInterior != null) OnTransitionDungeonInterior(args); } // OnTransitionDungeonExterior public delegate void OnTransitionDungeonExteriorEventHandler(TransitionEventArgs args); public static event OnTransitionDungeonExteriorEventHandler OnTransitionDungeonExterior; protected virtual void RaiseOnTransitionDungeonExteriorEvent() { TransitionEventArgs args = new TransitionEventArgs(TransitionType.ToDungeonExterior); if (OnTransitionDungeonExterior != null) OnTransitionDungeonExterior(args); } // OnMovePlayerToDungeonStart public delegate void OnMovePlayerToDungeonStartEventHandler(); public static event OnMovePlayerToDungeonStartEventHandler OnMovePlayerToDungeonStart; protected virtual void RaiseOnMovePlayerToDungeonStartEvent() { if (OnMovePlayerToDungeonStart != null) OnMovePlayerToDungeonStart(); } // OnRespawnerComplete public delegate void OnRespawnerCompleteEventHandler(); public static event OnRespawnerCompleteEventHandler OnRespawnerComplete; protected virtual void RaiseOnRespawnerCompleteEvent() { if (OnRespawnerComplete != null) OnRespawnerComplete(); } #endregion } }
39.60241
182
0.586643
[ "MIT" ]
MeteoricDragon/daggerfall-unity
Assets/Scripts/Game/PlayerEnterExit.cs
55,879
C#
namespace Photon.Voice.Unity { #if UNITY_WEBGL using System; #else using UnityEngine; #endif /// <summary>A wrapper around UnityEngine.Microphone to be able to safely use Microphone and compile for WebGL.</summary> public static class UnityMicrophone { public static string[] devices { get { #if UNITY_WEBGL throw new NotImplementedException("Unity Microphone not supported on WebGL"); #else return Microphone.devices; #endif } } public static void End(string deviceName) { #if UNITY_WEBGL throw new NotImplementedException("Unity Microphone not supported on WebGL"); #else Microphone.End(deviceName); #endif } public static void GetDeviceCaps(string deviceName, out int minFreq, out int maxFreq) { #if UNITY_WEBGL throw new NotImplementedException("Unity Microphone not supported on WebGL"); #else Microphone.GetDeviceCaps(deviceName, out minFreq, out maxFreq); #endif } public static int GetPosition(string deviceName) { #if UNITY_WEBGL throw new NotImplementedException("Unity Microphone not supported on WebGL"); #else return Microphone.GetPosition(deviceName); #endif } public static bool IsRecording(string deviceName) { #if UNITY_WEBGL throw new NotImplementedException("Unity Microphone not supported on WebGL"); #else return Microphone.IsRecording(deviceName); #endif } public static AudioClip Start(string deviceName, bool loop, int lengthSec, int frequency) { #if UNITY_WEBGL throw new NotImplementedException("Unity Microphone not supported on WebGL"); #else return Microphone.Start(deviceName, loop, lengthSec, frequency); #endif } } }
31.463768
125
0.572547
[ "MIT" ]
Henrynaut/UnityBase
Assets/Photon/PhotonVoice/PhotonVoiceApi/Platforms/Unity/UnityMicrophone.cs
2,173
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: AddressBook.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; #region Messages public sealed partial class Person : pb::IMessage<Person> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { public static readonly pb::MessageParser<Person> Parser = new pb::MessageParser<Person>(() => new Person()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; pbr::MessageDescriptor pb::IMessage.Descriptor { get { throw new System.NotImplementedException(); } } public Person Clone() { throw new System.NotImplementedException(); } private string name_; public string Name { get { return name_ ?? ""; } set { name_ = value; } } private int id_; public int Id { get { if ((_hasBits0 & 1) != 0) { return id_; } else { return 0; } } set { _hasBits0 |= 1; id_ = value; } } private string email_; public string Email { get { return email_ ?? ""; } set { email_ = value; } } private static readonly pb::FieldCodec<global::Person.Types.PhoneNumber> _repeated_phones_codec = pb::FieldCodec.ForMessage(34, global::Person.Types.PhoneNumber.Parser); private readonly pbc::RepeatedField<global::Person.Types.PhoneNumber> phones_ = new pbc::RepeatedField<global::Person.Types.PhoneNumber>(); public pbc::RepeatedField<global::Person.Types.PhoneNumber> Phones { get { return phones_; } } private bool hasThing_; public bool HasThing { get { if ((_hasBits0 & 2) != 0) { return hasThing_; } else { return false; } } set { _hasBits0 |= 2; hasThing_ = value; } } public override bool Equals(object other) { return Equals(other as Person); } public bool Equals(Person other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Id != other.Id) return false; if (Email != other.Email) return false; if(!phones_.Equals(other.phones_)) return false; if (HasThing != other.HasThing) return false; return Equals(_unknownFields, other._unknownFields); } public override int GetHashCode() { int hash = 1; if (name_ != null) hash ^= Name.GetHashCode(); if ((_hasBits0 & 1) != 0) hash ^= Id.GetHashCode(); if (email_ != null) hash ^= Email.GetHashCode(); hash ^= phones_.GetHashCode(); if ((_hasBits0 & 2) != 0) hash ^= HasThing.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } public void WriteTo(pb::CodedOutputStream output) { throw new System.NotImplementedException(); } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { throw new System.NotImplementedException(); } #endif public int CalculateSize() { throw new System.NotImplementedException(); } public void MergeFrom(Person other) { throw new System.NotImplementedException(); } public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } case 16: { Id = input.ReadInt32(); break; } case 26: { Email = input.ReadString(); break; } case 34: { phones_.AddEntriesFrom(input, _repeated_phones_codec); break; } case 40: { HasThing = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } case 16: { Id = input.ReadInt32(); break; } case 26: { Email = input.ReadString(); break; } case 34: { phones_.AddEntriesFrom(ref input, _repeated_phones_codec); break; } case 40: { HasThing = input.ReadBool(); break; } } } } #endif #region Nested types public static partial class Types { public enum PhoneType { [pbr::OriginalName("MOBILE")] Mobile = 0, [pbr::OriginalName("HOME")] Home = 1, [pbr::OriginalName("WORK")] Work = 2, } public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { public static readonly pb::MessageParser<PhoneNumber> Parser = new pb::MessageParser<PhoneNumber>(() => new PhoneNumber()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; pbr::MessageDescriptor pb::IMessage.Descriptor { get { throw new System.NotImplementedException(); } } public PhoneNumber Clone() { throw new System.NotImplementedException(); } private string number_; public string Number { get { return number_ ?? ""; } set { number_ = value; } } private global::Person.Types.PhoneType type_; public global::Person.Types.PhoneType Type { get { if ((_hasBits0 & 1) != 0) { return type_; } else { return global::Person.Types.PhoneType.Mobile; } } set { _hasBits0 |= 1; type_ = value; } } public override bool Equals(object other) { return Equals(other as PhoneNumber); } public bool Equals(PhoneNumber other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Number != other.Number) return false; if (Type != other.Type) return false; return Equals(_unknownFields, other._unknownFields); } public override int GetHashCode() { int hash = 1; if (number_ != null) hash ^= Number.GetHashCode(); if ((_hasBits0 & 1) != 0) hash ^= Type.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } public void WriteTo(pb::CodedOutputStream output) { throw new System.NotImplementedException(); } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { throw new System.NotImplementedException(); } #endif public int CalculateSize() { throw new System.NotImplementedException(); } public void MergeFrom(PhoneNumber other) { throw new System.NotImplementedException(); } public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Number = input.ReadString(); break; } case 16: { Type = (global::Person.Types.PhoneType) input.ReadEnum(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Number = input.ReadString(); break; } case 16: { Type = (global::Person.Types.PhoneType) input.ReadEnum(); break; } } } } #endif } } #endregion } public sealed partial class AddressBook : pb::IMessage<AddressBook> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { public static readonly pb::MessageParser<AddressBook> Parser = new pb::MessageParser<AddressBook>(() => new AddressBook()); private pb::UnknownFieldSet _unknownFields; pbr::MessageDescriptor pb::IMessage.Descriptor { get { throw new System.NotImplementedException(); } } public AddressBook Clone() { throw new System.NotImplementedException(); } private static readonly pb::FieldCodec<global::Person> _repeated_people_codec = pb::FieldCodec.ForMessage(10, global::Person.Parser); private readonly pbc::RepeatedField<global::Person> people_ = new pbc::RepeatedField<global::Person>(); public pbc::RepeatedField<global::Person> People { get { return people_; } } public override bool Equals(object other) { return Equals(other as AddressBook); } public bool Equals(AddressBook other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!people_.Equals(other.people_)) return false; return Equals(_unknownFields, other._unknownFields); } public override int GetHashCode() { int hash = 1; hash ^= people_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } public void WriteTo(pb::CodedOutputStream output) { throw new System.NotImplementedException(); } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { throw new System.NotImplementedException(); } #endif public int CalculateSize() { throw new System.NotImplementedException(); } public void MergeFrom(AddressBook other) { throw new System.NotImplementedException(); } public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { people_.AddEntriesFrom(input, _repeated_people_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { people_.AddEntriesFrom(ref input, _repeated_people_codec); break; } } } } #endif } public sealed partial class AnotherThing : pb::IMessage<AnotherThing> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { public static readonly pb::MessageParser<AnotherThing> Parser = new pb::MessageParser<AnotherThing>(() => new AnotherThing()); private pb::UnknownFieldSet _unknownFields; private int _hasBits0; pbr::MessageDescriptor pb::IMessage.Descriptor { get { throw new System.NotImplementedException(); } } public AnotherThing Clone() { throw new System.NotImplementedException(); } private string name_; public string Name { get { return name_ ?? ""; } set { name_ = value; } } private int id_; public int Id { get { if ((_hasBits0 & 1) != 0) { return id_; } else { return 0; } } set { _hasBits0 |= 1; id_ = value; } } public override bool Equals(object other) { return Equals(other as AnotherThing); } public bool Equals(AnotherThing other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Id != other.Id) return false; return Equals(_unknownFields, other._unknownFields); } public override int GetHashCode() { int hash = 1; if (name_ != null) hash ^= Name.GetHashCode(); if ((_hasBits0 & 1) != 0) hash ^= Id.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } public void WriteTo(pb::CodedOutputStream output) { throw new System.NotImplementedException(); } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { throw new System.NotImplementedException(); } #endif public int CalculateSize() { throw new System.NotImplementedException(); } public void MergeFrom(AnotherThing other) { throw new System.NotImplementedException(); } public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } case 16: { Id = input.ReadInt32(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } case 16: { Id = input.ReadInt32(); break; } } } } #endif } #endregion #endregion Designer generated code
30.391304
141
0.628176
[ "MIT" ]
tdupont750/ProtobufMinifySharp
ProtobufMinifySharp.Sample/Generated/AddressBook.All.cs
14,679
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace webDiscussex.Models { public class Doenca { public int Id { get; set; } public string Titulo { get; set; } public string Texto { get; set; } public int CodImagem { get; set; } } }
20.0625
42
0.626168
[ "MIT" ]
gustavoFG28/Discussex
webDiscussex/webDiscussex/Models/Doenca.cs
323
C#
using EcsRx.Components; namespace MisfitLabs.EcsRx.Unity.Authoring.Components { // TODO: Should this be called AuthoredComponent? public class ConvertedComponent : IComponent { } }
19.8
53
0.737374
[ "Apache-2.0" ]
misfitlabsdev/ecsrx.unity.authoring
Packages/dev.misfitlabs.ecsrx.unity.authoring/Runtime/MisfitLabs/EcsRx.Unity.Authoring/Components/ConvertedComponent.cs
198
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using Microsoft.TemplateEngine.Utils; using Microsoft.TemplateSearch.Common; namespace Microsoft.TemplateEngine.Cli.CommandParsing { /// <summary> /// Provides the collection of supported filters for different command options. /// </summary> /// <remarks> /// Intention of SupportedFilterOptions and FilterOption classes is to make the filters extendable. In case new filter option is implemented for dotnet new command, it should be enough to: /// - implement corresponding FilterOption class /// - add filter to required collection in SupportedFilterOptions class to apply it to certain dotnet new --option. /// </remarks> internal static class SupportedFilterOptions { internal static FilterOption AuthorFilter { get; } = new TemplateFilterOption( "author", filterValue: command => command.AuthorFilter, isFilterSet: command => !string.IsNullOrWhiteSpace(command.AuthorFilter), matchFilter: command => WellKnownSearchFilters.AuthorFilter(command.AuthorFilter), mismatchCriteria: resolutionResult => resolutionResult.HasAuthorMismatch); internal static FilterOption BaselineFilter { get; } = new TemplateFilterOption( "baseline", filterValue: command => command.BaselineName, isFilterSet: command => !string.IsNullOrWhiteSpace(command.BaselineName), matchFilter: command => WellKnownSearchFilters.BaselineFilter(command.BaselineName), mismatchCriteria: resolutionResult => resolutionResult.HasBaselineMismatch); internal static FilterOption LanguageFilter { get; } = new TemplateFilterOption( "language", filterValue: command => command.Language, isFilterSet: command => !string.IsNullOrWhiteSpace(command.Language), matchFilter: command => WellKnownSearchFilters.LanguageFilter(command.Language), mismatchCriteria: resolutionResult => resolutionResult.HasLanguageMismatch); internal static FilterOption TagFilter { get; } = new TemplateFilterOption( "tag", filterValue: command => command.TagFilter, isFilterSet: command => !string.IsNullOrWhiteSpace(command.TagFilter), matchFilter: command => WellKnownSearchFilters.ClassificationFilter(command.TagFilter), mismatchCriteria: resolutionResult => resolutionResult.HasClassificationMismatch); internal static FilterOption TypeFilter { get; } = new TemplateFilterOption( "type", filterValue: command => command.TypeFilter, isFilterSet: command => !string.IsNullOrWhiteSpace(command.TypeFilter), matchFilter: command => WellKnownSearchFilters.TypeFilter(command.TypeFilter), mismatchCriteria: resolutionResult => resolutionResult.HasTypeMismatch); internal static FilterOption PackageFilter { get; } = new PackageFilterOption( "package", filterValue: command => command.PackageFilter, isFilterSet: command => !string.IsNullOrWhiteSpace(command.PackageFilter), matchFilter: PackageMatchFilter); private static Func<PackInfo, bool> PackageMatchFilter(INewCommandInput command) { return (pack) => { if (string.IsNullOrWhiteSpace(command.PackageFilter)) { return true; } return pack.Name.IndexOf(command.PackageFilter, StringComparison.OrdinalIgnoreCase) > -1; }; } } }
48.777778
192
0.651734
[ "MIT" ]
AR-May/templating
src/Microsoft.TemplateEngine.Cli/CommandParsing/SupportedFilterOptions.cs
3,951
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Channels { public interface IChannel : ICommunicationObject { T GetProperty<T>() where T : class; } }
25.571429
71
0.72067
[ "MIT" ]
Bencargs/wcf
src/System.Private.ServiceModel/src/System/ServiceModel/Channels/IChannel.cs
358
C#
using System; using Android.Content; using Android.Support.V7.Widget; using Android.Widget; using AView = Android.Views.View; using Object = Java.Lang.Object; using ViewGroup = Android.Views.ViewGroup; namespace Xamarin.Forms.Platform.Android { // TODO hartez 2018/07/25 14:43:04 Experiment with an ItemSource property change as _adapter.notifyDataSetChanged public class ItemsViewAdapter : RecyclerView.Adapter { protected readonly ItemsView ItemsView; readonly Func<IVisualElementRenderer, Context, AView> _createView; internal readonly IItemsViewSource ItemsSource; internal ItemsViewAdapter(ItemsView itemsView, Func<IVisualElementRenderer, Context, AView> createView = null) { CollectionView.VerifyCollectionViewFlagEnabled(nameof(ItemsViewAdapter)); ItemsView = itemsView; _createView = createView; ItemsSource = ItemsSourceFactory.Create(itemsView.ItemsSource, this); if (_createView == null) { _createView = (renderer, context) => new ItemContentView(renderer, context); } } public override void OnViewRecycled(Object holder) { if (holder is TemplatedItemViewHolder templatedItemViewHolder) { templatedItemViewHolder.View.Parent = null; } base.OnViewRecycled(holder); } public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { switch (holder) { case TextViewHolder textViewHolder: textViewHolder.TextView.Text = ItemsSource[position].ToString(); break; case TemplatedItemViewHolder templateViewHolder: templateViewHolder.View.Parent = ItemsView; BindableObject.SetInheritedBindingContext(templateViewHolder.View, ItemsSource[position]); break; } } public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { var context = parent.Context; // Does the ItemsView have a DataTemplate? var template = ItemsView.ItemTemplate; if (template == null) { // No template, just use the ToString view var view = new TextView(context); return new TextViewHolder(view); } // Realize the content, create a renderer out of it, and use that var templateElement = (View)template.CreateContent(); var itemContentControl = _createView(CreateRenderer(templateElement, context), context); return new TemplatedItemViewHolder(itemContentControl, templateElement); } static IVisualElementRenderer CreateRenderer(View view, Context context) { if (view == null) { throw new ArgumentNullException(nameof(view)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } var renderer = Platform.CreateRenderer(view, context); Platform.SetRenderer(view, renderer); return renderer; } public override int ItemCount => ItemsSource.Count; public override int GetItemViewType(int position) { // TODO hartez We might be able to turn this to our own purposes // We might be able to have the CollectionView signal the adapter if the ItemTemplate property changes // And as long as it's null, we return a value to that effect here // Then we don't have to check _itemsView.ItemTemplate == null in OnCreateViewHolder, we can just use // the viewType parameter. return 42; } public virtual int GetPositionForItem(object item) { for (int n = 0; n < ItemsSource.Count; n++) { if (ItemsSource[n] == item) { return n; } } return -1; } } }
28.858333
115
0.733757
[ "MIT" ]
AuriR/Xamarin.Forms
Xamarin.Forms.Platform.Android/CollectionView/ItemsViewAdapter.cs
3,463
C#
using System; using Visitor.Impl; using Visitor.Entities; namespace Visitor { internal class SampleLauncher { static void Main(string[] args) { GeneralArgument generalArgument = new GeneralArgument("General argument"); SpecialArgument specialArgument = new SpecialArgument("Special argument"); ArgumentsLooker argumentsLooker = new ArgumentsLooker(); ArgumentsResearcher argumentsResearcher = new ArgumentsResearcher(); argumentsLooker.DisplayArgument(generalArgument); argumentsLooker.DisplayArgument(specialArgument); argumentsResearcher.DisplayArgument(generalArgument); argumentsResearcher.DisplayArgument(specialArgument); Console.ReadKey(); } } }
26.923077
77
0.785714
[ "MIT" ]
AliakseiFutryn/dotnet-design-patterns-samples
Behavioral/Visitor/SampleLauncher.cs
702
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("TestWebsite")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("TestWebsite")] [assembly: System.Reflection.AssemblyTitleAttribute("TestWebsite")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.958333
80
0.648016
[ "MIT" ]
matthewcrews/test-aspnetmvc
TestWebsite/obj/Debug/netcoreapp2.0/TestWebsite.AssemblyInfo.cs
983
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. namespace AiryCore.Extensions.DependencyInjection { using System; using AiryCore.Identity.NHibernate; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; /// <summary> /// Contains extension methods to <see cref="IdentityBuilder"/> for adding entity framework stores. /// </summary> public static class IdentityNHibernateBuilderExtensions { /// <summary> /// Adds an Entity Framework implementation of identity information stores. /// </summary> /// <param name="builder">The <see cref="IdentityBuilder"/> instance this method extends.</param> /// <returns>The <see cref="IdentityBuilder"/> instance this method extends.</returns> public static IdentityBuilder AddNHibernateStores(this IdentityBuilder builder) { builder.Services.TryAdd(GetDefaultServices(builder.UserType, builder.RoleType)); return builder; } /// <summary> /// Adds an Entity Framework implementation of identity information stores. /// </summary> /// <typeparam name="TKey">The type of the primary key used for the users and roles.</typeparam> /// <param name="builder">The <see cref="IdentityBuilder"/> instance this method extends.</param> /// <returns>The <see cref="IdentityBuilder"/> instance this method extends.</returns> public static IdentityBuilder AddNHibernateStores<TKey>(this IdentityBuilder builder) where TKey : IEquatable<TKey> { builder.Services.TryAdd( GetDefaultServices(builder.UserType, builder.RoleType, typeof(TKey))); return builder; } private static IServiceCollection GetDefaultServices( Type userType, Type roleType, Type keyType = null) { keyType = keyType ?? typeof(string); var userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, keyType); var roleStoreType = typeof(RoleStore<,>).MakeGenericType(roleType, keyType); var services = new ServiceCollection(); services.AddScoped( typeof(IUserStore<>).MakeGenericType(userType), userStoreType); services.AddScoped( typeof(IRoleStore<>).MakeGenericType(roleType), roleStoreType); return services; } } }
40.954545
111
0.648539
[ "Apache-2.0" ]
mlintell/Alaunis.AspNetCore.Identity.NHibernate
Source/AiryCore.Identity.NHibernate/Extensions/DependencyInjection/IdentityNHibernateBuilderExtensions.cs
2,703
C#
using System.Collections; using System.Collections.Generic; using System; using System.Collections.Specialized; namespace AVGParser.KRKR { public class Command { public string CommandName { get; internal set; } = ""; public Dictionary<string, string> CommandParams { get; internal set; } = new Dictionary<string, string>(); public string ScriptName { get; internal set; } = ""; public string LabelName { get; internal set; } = null; public int LineNumber { get; internal set; } } public class MacroInfo { public string MacroName { get; internal set; } = ""; public string MacroLine { get; internal set; } = ""; } public class MacroBuffer { public string MacroString { get; internal set; } = ""; public int Offset { get; internal set; } public int PrevOffset { get; internal set; } public Dictionary<string, string> MacroParams { get; internal set; } = new Dictionary<string, string>(); public Dictionary<string, TJSVariable> cacheTJSDic { get; internal set; } = null; } public class CallStackInfo { public string ScriptName { get; internal set; } = ""; public string LabelName { get; internal set; } = null; public int LineNumber { get; internal set; } public int LineOffset { get; internal set; } public int PrevLineNumber { get; internal set; } public int PrevLineOffset { get; internal set; } public List<MacroBuffer> buffer { get; internal set; } = new List<MacroBuffer>(); } public enum IfState { If, ElseIf, Else, } [Serializable] public class SaveState { public int TrueIfDepth { get; internal set; } = 0; //count of @if blocks which current branch is active public int PassedIfDepth { get; internal set; } = 0; //count of @if blocks which one branch of it has been entered public int AllIfDepth { get; internal set; } = 0; //count of @if blocks public Stack<IfState> IfState { get; internal set; } = new Stack<IfState>(); public List<CallStackInfo> CallStack { get; internal set; } = new List<CallStackInfo>(); internal SaveState clone() { return MemberwiseClone() as SaveState; } } // -------------------------------------------------------------------------------- /// <summary> /// KAGParser class, parse kag-type script /// </summary> /// <remarks> /// only support line comment by ; // /// ; must be line beginning /// no texttag support /// support multi-times return by @return times=2 /// macro and endmacro must occupy one single line and begin at line start /// macro names are case sensitive /// </remarks> // -------------------------------------------------------------------------------- public class KAGParser { /// <summary>whether process SpecialTags internal, default is true</summary> /// <remarks> /// If set true, special tags like "jump" will be handled internal /// If set false, will return a Command class as normal command, offen used for scripts analysis /// All special tags are: /// if endif else elseif emb macro endmacro erasemacro jump call return /// there is small difference with raw krkr special tags /// </remarks> public bool ProcessSpecialTags = true; /// <summary>prohibit auto savepoint at savable label, such as in menu script</summary> public bool NoSaveGlobal = false; /// <summary> /// whether parse all continuous texts as one command, default is false (same as kag) /// </summary> public bool ParseTextTogether = false; /// <summary> /// VM used for eval exp /// </summary> public TJSVM VM = TJSVM.VM; public string ErrorMessage { get; internal set; } public string CurrentScript { get { int cc = currentSave.CallStack.Count; if (cc <= 0) return null; return currentSave.CallStack[cc - 1].ScriptName; } } public string CurrentLabel { get { int cc = currentSave.CallStack.Count; if (cc <= 0) return null; return currentSave.CallStack[cc - 1].LabelName; } } public int CurrentLineNumber { get { int cc = currentSave.CallStack.Count; if (cc <= 0) return -1; return currentSave.CallStack[cc - 1].LineNumber; } } public int PrevLineNumber { get { int cc = currentSave.CallStack.Count; if (cc <= 0) return -1; return currentSave.CallStack[cc - 1].PrevLineNumber; } } public int CurrentLineOffset { get { int cc = currentSave.CallStack.Count; if (cc <= 0) return -1; return currentSave.CallStack[cc - 1].LineOffset; } } public int PrevLineOffset { get { int cc = currentSave.CallStack.Count; if (cc <= 0) return -1; return currentSave.CallStack[cc - 1].PrevLineOffset; } } //callbacks public Func<string, string> LoadScriptCallback; //scriptName, label, isSaveLabel public Action<string, string, bool> OnLabel; public SaveState LastSavepointState { get { return lastSave.clone(); } } public Dictionary<string, MacroInfo> macros { get; internal set; } = new Dictionary<string, MacroInfo>(); class ScriptCache { public string[] lines = null; public Dictionary<string, int> labelmap = new Dictionary<string, int>(); public Dictionary<string, bool> labelsaveinfo = new Dictionary<string, bool>(); public bool parseOver = false; public int parseLineNumber = 0; } Dictionary<string, ScriptCache> scriptCache = new Dictionary<string, ScriptCache>(); SaveState lastSave = null; SaveState currentSave = new SaveState(); ScriptCache currentScriptCache = null; //current macro when parse macro command MacroInfo currentMacro = null; bool currentMacroValid = false; CallStackInfo currentCall { get { int cc = currentSave.CallStack.Count; if (cc <= 0) return null; return currentSave.CallStack[cc - 1]; } } //current macro context MacroBuffer currentRunMacro { get { var macrobuf = currentCall?.buffer; if (macrobuf == null || macrobuf.Count == 0) return null; return macrobuf[macrobuf.Count - 1]; } } bool currentIf { get { return currentSave.TrueIfDepth == currentSave.AllIfDepth; } } bool isLineHead = true; public TJSVariable MP(TJSVariable self, TJSVariable[] param, int start, int num) { var macrobuf = currentRunMacro; if (macrobuf.cacheTJSDic == null) { var dic = macrobuf.MacroParams; var tjsdic = new Dictionary<string, TJSVariable>(); foreach (var it in dic) { tjsdic[it.Key] = new TJSVariable(it.Value); } macrobuf.cacheTJSDic = tjsdic; } return new TJSVariable(new TJSDictionary(macrobuf.cacheTJSDic)); } public KAGParser() { //register mp property VM._global.RemoveField("mp"); VM._global.SetField("mp", new TJSVariable(new TJSProperty(MP, null, new TJSVariable()))); } /// <summary> /// recover KAGParser state from savedata /// </summary> /// <param name="state"></param> public void LoadState(SaveState state) { lastSave = state.clone(); currentSave = state.clone(); } /// <summary> /// Manual set the content of a script /// </summary> /// <param name="scriptName"></param> /// <param name="content"></param> public void SetScriptContent(string scriptName, string content) { scriptCache[scriptName] = new ScriptCache(); content = content.Replace("\r\n", "\n"); content = content.Replace("\r", "\n"); scriptCache[scriptName].lines = content.Split('\n'); } /// <summary> /// Load a new script and start from a label /// </summary> public void LoadScript(string scriptName, string label = null) { if (currentSave.CallStack.Count == 0) { newCallInfo(); } if (scriptName == null) scriptName = CurrentScript; if (!scriptCache.ContainsKey(scriptName)) { if (LoadScriptCallback != null) { //should handle error inside the function var text = LoadScriptCallback(scriptName); if (text == null) return; scriptCache[scriptName] = new ScriptCache(); text = text.Replace("\r\n", "\n"); text = text.Replace("\r", "\n"); scriptCache[scriptName].lines = text.Split('\n'); } else { var asset = UnityEngine.Resources.Load<UnityEngine.TextAsset>(scriptName); if (asset == null) { UnityEngine.Debug.LogError($"cannot find script <{scriptName}>"); return; } else { scriptCache[scriptName] = new ScriptCache(); var text = asset.text; text = text.Replace("\r\n", "\n"); text = text.Replace("\r", "\n"); scriptCache[scriptName].lines = text.Split('\n'); } } } currentScriptCache = scriptCache[scriptName]; if (scriptName != CurrentScript) { //clear if info currentSave.TrueIfDepth = currentSave.AllIfDepth = 0; } currentCall.ScriptName = scriptName; if (label != null && label.StartsWith("*")) label = label.Substring(1); currentCall.LabelName = label; int line = searchLabel(label); if (line == -1) { UnityEngine.Debug.LogError($"label <{label}> not exist in file <{scriptName}>"); currentCall.LineNumber = 0; } else { currentCall.LineNumber = line; } currentCall.LineOffset = 0; currentCall.buffer.Clear(); if (lastSave == null) lastSave = currentSave.clone(); } /// <summary> /// Call into a new label in script, if script is null, call label in current script /// </summary> public void Call(string scriptName = null, string label = null) { newCallInfo(); LoadScript(scriptName, label); } /// <summary> /// Call label in current script, same as Call(null, label) /// </summary> public void CallLabel(string label) { Call(null, label); } /// <summary> /// Jump to a label, same as LoadScript(scriptName, label) /// </summary> public void Jump(string scriptName, string label = null) { LoadScript(scriptName, label); } /// <summary> /// Return several times, default is 1 /// </summary> public void Return(int times = 1) { while (times > 0) { if (currentSave.CallStack.Count <= 1) { UnityEngine.Debug.LogError("cannot return from topest level"); return; } currentSave.CallStack.RemoveAt(currentSave.CallStack.Count - 1); times--; } } /// <summary> /// trigger a savepoint, save state internally /// </summary> public void Savepoint() { lastSave = currentSave.clone(); } /// <summary> /// Get next command, the text is converted to text command, emb is also parsed and return a text command. /// Whether special tag is processed internal is depended on the <c>ProcessSpecialTags</c> variable /// </summary> /// <returns></returns> public Command GetNextTag() { while (true) { var text = getCurLine(); while (text != null && text.Length == 0) { proceedOffset(0); text = getCurLine(); } if (text == null) return null; int n = 0; while (n < text.Length && (text[n] == '\n' || text[n] == '\t')) n++; if (n > 0) { proceedOffset(n); text = text.Substring(n); } if (text[0] == '*' && isLineHead) { //label string label = text.Substring(1); proceedOffset(text.Length); if (currentMacro != null) { error("label cannot lies inside a macro"); continue; } if (currentIf) { bool isSave = false; if (label.EndsWith("|")) { isSave = true; label = label.Substring(0, label.Length - 1); } OnLabel?.Invoke(CurrentScript, label, isSave); if (isSave && !NoSaveGlobal) { lastSave = currentSave.clone(); } } continue; } else if ((text[0] == ';' && isLineHead) || text.StartsWith("//")) { //line comment proceedOffset(text.Length); continue; } else if ((text[0] == '@' && isLineHead) || text[0] == '[') { //command bool isAt = text[0] == '@'; int j = 1; Command cmd = new Command(); cmd.ScriptName = CurrentScript; cmd.LineNumber = CurrentLineNumber; cmd.LabelName = CurrentLabel; while (j < text.Length && (char.IsLetterOrDigit(text[j]) || text[j] == '_' || text[j] > 127)) { if (j == 1 && char.IsDigit(text[j])) break; j++; } cmd.CommandName = text.Substring(1, j - 1); if (cmd.CommandName == "") { error("illegal command name"); if (isAt) proceedOffset(text.Length); else proceedOffset(skipToChar(text, "]") + 1); return null; } if (isAt) j = skipToChar(text, " \t", j); else j = skipToChar(text, " \t]", j); while (true) { while (j < text.Length && char.IsWhiteSpace(text[j])) j++; if (!isAt) { if (j < text.Length && text[j] == ']') { j++; break; } } if (j >= text.Length) { if (isAt) { break; } else { //read next line proceedOffset(j); text = getCurLine(); j = 0; } } int k = j; while (k < text.Length && (char.IsLetterOrDigit(text[k]) || text[j] == '_' || text[k] > 127)) { if (k == j && char.IsDigit(text[k])) break; k++; } var propname = text.Substring(j, k - j); if (propname == "") { error("illegal property name"); if (isAt) proceedOffset(text.Length); else proceedOffset(skipToChar(text, "]") + 1); return null; } var value = "true"; //this is default value if (text[k] == '=') { //parse value k++; if (isAt) j = skipToChar(text, " \t", k); else j = skipToChar(text, " \t]", k); value = text.Substring(k, j - k); if (value.StartsWith("\"") && value.EndsWith("\"") && value.Length > 1) { value = value.Substring(1, value.Length - 2); } else if (value.StartsWith("&")) { value = value.Substring(1); if (value.StartsWith("\"") && value.EndsWith("\"") && value.Length > 1) { value = value.Substring(1, value.Length - 2); } if (currentIf) { try { TJSVariable res = VM.Eval(value); value = res.ToString(); } catch (Exception e) { error(e.Message); return null; } } } else if (value.StartsWith("%")) { if (currentRunMacro == null) { error("cannot use %variable in non-macro context"); return null; } var valuelist = value.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var dic = currentRunMacro?.MacroParams; value = ""; foreach (var item in valuelist) { if (item.StartsWith("%")) { if (dic.ContainsKey(item.Substring(1))) { value = item.Substring(1); break; } } else { value = item; break; } } } } else { if (isAt) j = skipToChar(text, " \t", k); else j = skipToChar(text, " \t]", k); } cmd.CommandParams[propname] = value; } proceedOffset(j); if (ProcessSpecialTags) { //handle jump, call, iscript etc bool isSpecial = processSpecialTags(cmd); if (currentMacro != null && cmd.CommandName != "macro") { if (isLineHead && currentMacro.MacroLine.Length > 0) currentMacro.MacroLine += "\n"; currentMacro.MacroLine += text.Substring(0, j); continue; } // if currentIf==false, then all command is see as special else if (isSpecial) { continue; } } return cmd; } else { //text if (currentIf && currentMacro == null) { Command cmd = new Command(); cmd.ScriptName = CurrentScript; cmd.LineNumber = CurrentLineNumber; cmd.LabelName = CurrentLabel; cmd.CommandName = "text"; if (ParseTextTogether && text.Length > 1) { int end = 0; int ch = text[end]; int ch2 = text[end + 1]; while (ch != '[' && !(ch == '/' && ch2 == '/')) { end++; if (end >= text.Length) break; ch = ch2; if (end + 1 < text.Length) ch2 = text[end + 1]; else ch2 = 0; } cmd.CommandParams["text"] = text.Substring(0, end); proceedOffset(end); } else { cmd.CommandParams["text"] = text.Substring(0, 1); proceedOffset(1); } return cmd; } else { if (currentMacro != null) { if (isLineHead && currentMacro.MacroLine.Length > 0) currentMacro.MacroLine += "\n"; currentMacro.MacroLine += text[0]; } proceedOffset(1); continue; } } } } //handle jump, call, iscript etc bool processSpecialTags(Command cmd) { if (currentMacro != null) { if (cmd.CommandName == "endmacro") { if (currentMacroValid) { //manual pop macro stack currentMacro.MacroLine += "\n[macropop]"; macros[currentMacro.MacroName] = currentMacro; } currentMacro = null; } return true; } if (!currentIf) { if (cmd.CommandName == "if") { currentSave.AllIfDepth++; } else if (cmd.CommandName == "else") { if (currentSave.AllIfDepth - currentSave.TrueIfDepth == 1) { if (currentSave.AllIfDepth - currentSave.PassedIfDepth == 1) { currentSave.TrueIfDepth++; currentSave.PassedIfDepth++; } currentSave.IfState.Pop(); currentSave.IfState.Push(IfState.Else); } } else if (cmd.CommandName == "elseif") { if (currentSave.AllIfDepth - currentSave.TrueIfDepth == 1) { if (currentSave.IfState.Peek() == IfState.Else) { error("elseif behind else, will be ignore"); } else if (currentSave.AllIfDepth - currentSave.PassedIfDepth == 1) { string exp = ""; if (cmd.CommandParams.ContainsKey("exp")) { exp = cmd.CommandParams["exp"]; } bool res = false; if (exp.Length > 0) { try { TJSVariable r = VM.Eval(exp); res = r.ToBoolean(); } catch (Exception e) { error(e.Message); return true; } } if (res) { currentSave.TrueIfDepth++; currentSave.PassedIfDepth++; } currentSave.IfState.Pop(); currentSave.IfState.Push(IfState.ElseIf); } } } else if (cmd.CommandName == "endif") { if (currentSave.AllIfDepth == currentSave.IfState.Count) currentSave.IfState.Pop(); currentSave.AllIfDepth--; if (currentSave.TrueIfDepth > currentSave.AllIfDepth) currentSave.TrueIfDepth = currentSave.AllIfDepth; if (currentSave.PassedIfDepth > currentSave.AllIfDepth) currentSave.PassedIfDepth = currentSave.AllIfDepth; } return true; } if (cmd.CommandName == "jump" || cmd.CommandName == "call") { string script = null; string label = null; if (!cmd.CommandParams.ContainsKey("storage") && !cmd.CommandParams.ContainsKey("target")) { error("storage and target cannot both be null"); return true; } if (cmd.CommandParams.ContainsKey("storage")) { script = cmd.CommandParams["storage"]; } if (cmd.CommandParams.ContainsKey("target")) { label = cmd.CommandParams["target"]; if (label.StartsWith("*")) label = label.Substring(1); } if (cmd.CommandName == "jump") Jump(script, label); else Call(script, label); return true; } else if (cmd.CommandName == "return") { int times = 1; if (cmd.CommandParams.ContainsKey("times")) { int.TryParse(cmd.CommandParams["times"], out times); } Return(times); return true; } else if (cmd.CommandName == "emb") { string exp = ""; if (cmd.CommandParams.ContainsKey("exp")) { exp = cmd.CommandParams["exp"]; } if (exp.Length > 0) { try { TJSVariable r = VM.Eval(exp); string res = r.ToString(); MacroBuffer buf = new MacroBuffer(); buf.MacroString = res; buf.Offset = 0; currentCall.buffer.Add(buf); } catch (Exception e) { error(e.Message); return true; } } return true; } else if (cmd.CommandName == "eval") { string exp = ""; if (cmd.CommandParams.ContainsKey("exp")) { exp = cmd.CommandParams["exp"]; } if (exp.Length > 0) { try { VM.Eval(exp); } catch (Exception e) { error(e.Message); return true; } } return true; } else if (cmd.CommandName == "if") { string exp = ""; if (cmd.CommandParams.ContainsKey("exp")) { exp = cmd.CommandParams["exp"]; } bool res = false; if (exp.Length > 0) { try { TJSVariable r = VM.Eval(exp); res = r.ToBoolean(); } catch (Exception e) { error(e.Message); return true; } } currentSave.AllIfDepth++; currentSave.IfState.Push(IfState.If); if (res) { currentSave.TrueIfDepth++; currentSave.PassedIfDepth++; } return true; } else if (cmd.CommandName == "elseif") { if (currentSave.AllIfDepth <= 0) { error("elseif without if"); return true; } currentSave.TrueIfDepth--; if (currentSave.IfState.Peek() == IfState.Else) { error("elseif behind else, will be ignore"); } else { currentSave.IfState.Pop(); currentSave.IfState.Push(IfState.ElseIf); } } else if (cmd.CommandName == "else") { if (currentSave.AllIfDepth <= 0) { error("else without if"); return true; } currentSave.TrueIfDepth--; currentSave.IfState.Pop(); currentSave.IfState.Push(IfState.Else); } else if (cmd.CommandName == "endif") { if (currentSave.AllIfDepth <= 0) { error("endif without if"); return true; } currentSave.AllIfDepth--; if (currentSave.TrueIfDepth > currentSave.AllIfDepth) currentSave.TrueIfDepth = currentSave.AllIfDepth; if (currentSave.PassedIfDepth > currentSave.AllIfDepth) currentSave.PassedIfDepth = currentSave.AllIfDepth; currentSave.IfState.Pop(); } else if (cmd.CommandName == "macro") { if (currentCall.buffer.Count > 0) { error("macro define cannot nested in another macro define"); return true; } string name = ""; if (cmd.CommandParams.ContainsKey("name")) { name = cmd.CommandParams["name"]; } if (name.Length == 0) { error("macro must have a name"); } bool valid = true; for (int i = 0; i < name.Length; i++) { if (char.IsLetterOrDigit(name[i]) || name[i] == '_' || name[i] > 127) { if (i == 0 && char.IsDigit(name[i])) { valid = false; break; } } else { valid = false; break; } } if (!valid) { error($"macro name ({name}) is illegal"); } currentMacro = new MacroInfo(); currentMacroValid = valid; currentMacro.MacroName = name; } else if (cmd.CommandName == "endmacro") { error("endmacro without macro"); return true; } else if (cmd.CommandName == "erasemacro") { string name = ""; if (cmd.CommandParams.ContainsKey("name")) { name = cmd.CommandParams["name"]; } macros.Remove(name); } else if (cmd.CommandName == "macropop") { if (currentCall.buffer.Count > 0) { currentCall.buffer.RemoveAt(currentCall.buffer.Count - 1); } else { error("meet macropop but not in a macro context, DO NOT write this command manually"); } } else if (cmd.CommandName == "iscript") { string exp = ""; while (true) { string text = getCurLine(); if (text == null) { error("[iscript] need [endscript]"); } proceedOffset(text.Length); text = text.TrimStart(); if (text.StartsWith("[endscript]")) break; exp += text; exp += '\n'; } try { VM.Eval(exp); } catch (Exception e) { error(e.Message); return true; } } else if (macros.ContainsKey(cmd.CommandName)) { MacroBuffer buf = new MacroBuffer(); buf.MacroParams = cmd.CommandParams; buf.MacroString = macros[cmd.CommandName].MacroLine; buf.Offset = 0; currentCall.buffer.Add(buf); } else { return false; } return true; } string getCurLine() { if (currentCall.buffer.Count > 0) { var c = currentCall.buffer[currentCall.buffer.Count - 1]; var str = c.MacroString.Substring(c.Offset); if (c.Offset == 0 || c.MacroString[c.Offset - 1] == '\n') isLineHead = true; else isLineHead = false; var npos = str.IndexOf('\n'); if (npos >= 0) return str.Substring(0, npos); else return str; } isLineHead = currentCall.LineOffset == 0; if (currentCall.LineNumber < currentScriptCache.lines.Length) return currentScriptCache.lines[currentCall.LineNumber].Substring(currentCall.LineOffset); else return null; } public string GetPrevLine() { if (currentCall.buffer.Count > 0) { var c = currentCall.buffer[currentCall.buffer.Count - 1]; var str = c.MacroString.Substring(c.PrevOffset); var npos = str.IndexOf('\n'); if (npos >= 0) return str.Substring(0, npos); else return str; } if (currentCall.PrevLineNumber < currentScriptCache.lines.Length) return currentScriptCache.lines[currentCall.PrevLineNumber].Substring(currentCall.PrevLineOffset); else return null; } int skipToChar(string text, string end, int start = 0) { int i = start; bool instr = false; while (i < text.Length) { if (text[i] == '\"') { instr = !instr; i++; continue; } if (text[i] == '\\') { i++; if (i < text.Length) { if (text[i] == 'x') i += 2; else if (char.IsDigit(text[i])) i += 2; else i++; } continue; } if (end.IndexOf(text[i]) >= 0 && !instr) return i; i++; } return i; } void proceedOffset(int n) { if (currentCall.buffer.Count > 0) { var c = currentCall.buffer[currentCall.buffer.Count - 1]; c.PrevOffset = c.Offset; c.Offset += n; while (c.Offset < c.MacroString.Length && c.MacroString[c.Offset] == '\n') c.Offset++; while (c.Offset >= c.MacroString.Length) { currentCall.buffer.Remove(c); if (currentCall.buffer.Count == 0) return; c = currentCall.buffer[currentCall.buffer.Count - 1]; } return; } var curline = currentScriptCache.lines[currentCall.LineNumber]; currentCall.PrevLineOffset = currentCall.LineOffset; currentCall.PrevLineNumber = currentCall.LineNumber; currentCall.LineOffset += n; if (currentCall.LineOffset >= curline.Length) { currentCall.LineOffset = 0; currentCall.LineNumber++; } } void newCallInfo() { currentSave.CallStack.Add(new CallStackInfo()); } int searchLabel(string label = null) { if (label == null) return 0; if (currentScriptCache.labelmap.ContainsKey(label)) return currentScriptCache.labelmap[label]; if (currentScriptCache.parseOver) return -1; for (int i = currentScriptCache.parseLineNumber; i < currentScriptCache.lines.Length; i++) { var text = currentScriptCache.lines[i]; if (text.Length > 0 && text[0] == '*') { var labelname = text.Substring(1); bool isSave = false; if (labelname.EndsWith("|")) { labelname = labelname.Substring(0, labelname.Length - 1); isSave = true; } int j = 1; var newlabelname = labelname; while (currentScriptCache.labelmap.ContainsKey(newlabelname)) { j++; newlabelname = labelname + ":" + j.ToString(); } currentScriptCache.labelmap[newlabelname] = i; currentScriptCache.labelsaveinfo[newlabelname] = isSave; if (newlabelname == label) { currentScriptCache.parseLineNumber = i; if (i >= currentScriptCache.lines.Length - 1) currentScriptCache.parseOver = true; return i; } } } return -1; } void error(string msg) { ErrorMessage = $"Error:{msg} at {CurrentScript}, line {PrevLineNumber}, when parse {GetPrevLine()}"; UnityEngine.Debug.LogError(ErrorMessage); //skip to next line currentCall.LineNumber++; currentCall.LineOffset = 0; } } }
36.808762
125
0.384121
[ "MIT" ]
gjy1992/AVGParser
KRKR/KAGParser.cs
43,694
C#
using System.Collections.Generic; using System.Linq; namespace TestNinja.Mocking { public interface IVideoRepository { IEnumerable<Video> GetUnprocessedVideos(); } public class VideoRepository : IVideoRepository { public IEnumerable<Video> GetUnprocessedVideos() { using (var context = new VideoContext()) { var videos = (from video in context.Videos where !video.IsProcessed select video).ToList(); return videos; } } } }
22.703704
56
0.54323
[ "MIT" ]
briang123/TestNinja
TestNinja/Mocking/VideoRepository.cs
615
C#
using System; using UnityEngine; using AlphaMode = GLTF.Schema.AlphaMode; using CullMode = UnityEngine.Rendering.CullMode; namespace UnityGLTF { class MetalRoughMap : MetalRough2StandardMap { public MetalRoughMap(int MaxLOD = 1000) : base("GLTF/PbrMetallicRoughness", MaxLOD) { } public MetalRoughMap(string shaderName, int MaxLOD = 1000) : base(shaderName, MaxLOD) { } protected MetalRoughMap(Material m, int MaxLOD = 1000) : base(m, MaxLOD) { } public override int NormalTexCoord { get { return 0; } set { return; } } public override int OcclusionTexCoord { get { return 0; } set { return; } } public override int EmissiveTexCoord { get { return 0; } set { return; } } public override int BaseColorTexCoord { get { return 0; } set { return; } } public override Texture MetallicRoughnessTexture { get { return _material.GetTexture(_metallicRoughnessTextureID); } set { _material.SetTexture(_metallicRoughnessTextureID, value); _material.EnableKeyword("_METALLICGLOSSMAP"); } } public override int MetallicRoughnessTexCoord { get { return 0; } set { return; } } public override IUniformMap Clone() { var copy = new MetalRoughMap(new Material(_material)); base.Copy(copy); return copy; } } }
26.451613
97
0.551829
[ "MIT" ]
JohnCopicMS/UnityGLTF
UnityGLTF/Assets/UnityGLTF/Scripts/UniformMaps/MetalRoughMap.cs
1,642
C#
namespace BlazorLibs.Webcam { public class WebcamOptions { public int Width { get; set; } public string VideoID { get; set; } public string CanvasID { get; set; } public string PhotoID { get; set; } } }
22.545455
44
0.584677
[ "MIT" ]
thinktecture/blazor-wasm-things-to-know
IsolatedJS/Client/Webcam/WebcamOptions.cs
250
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Threading.Tasks; using Clockwise; using Microsoft.CodeAnalysis; namespace WorkspaceServer.Packaging { public interface IPackage { string Name { get; } } public interface IHaveADirectory : IPackage { DirectoryInfo Directory { get; } } public interface IHaveADirectoryAccessor : IPackage { IDirectoryAccessor Directory { get; } } public interface ICanSupportWasm : IPackage { bool CanSupportWasm { get; } } public interface ICreateWorkspace : IPackage { Task<Workspace> CreateRoslynWorkspaceAsync(Budget budget); } public interface ICreateWorkspaceForRun : IPackage, ICreateWorkspace { Task<Workspace> CreateRoslynWorkspaceForRunAsync(Budget budget); } public interface ICreateWorkspaceForLanguageServices : IPackage, ICreateWorkspace { Task<Workspace> CreateRoslynWorkspaceForLanguageServicesAsync(Budget budget); } }
25.955556
101
0.713185
[ "MIT" ]
AzureMentor/try
WorkspaceServer/Packaging/IPackage.cs
1,168
C#
using System; using System.Diagnostics.Tracing; using Thor.Core; using Thor.Core.Abstractions; using Thor.Core.Transmission.Abstractions; namespace Thor.Hosting.AspNetCore.FunctionalTest.EventSources { [EventSource(Name = "AspNetCore-FunctionalTest")] [System.CodeDom.Compiler.GeneratedCodeAttribute("thor-generator", "1.0.0")] public sealed class ValuesEventSources : EventSourceBase , IValuesEventSources { private ValuesEventSources() { } public static IValuesEventSources Log { get; } = new ValuesEventSources(); [NonEvent] public void RetrieveObject(int id) { if (IsEnabled()) { RetrieveObject(Application.Id, ActivityStack.Id, id); } } [Event(1, Level = EventLevel.Informational, Message = "Retrieve value for object {2}", Version = 1)] private void RetrieveObject(int applicationId, Guid activityId, int id) { WriteCore(1, applicationId, activityId, id); } [NonEvent] public void RetrieveObjectInfo(int id, RequestInformation info) { if (IsEnabled()) { var attachmentId = AttachmentId.NewId(); RetrieveObjectInfo(Application.Id, ActivityStack.Id, attachmentId, id); AttachmentDispatcher.Instance.Dispatch( AttachmentFactory.Create(attachmentId, "info", info) ); } } [Event(2, Level = EventLevel.Informational, Message = "Retrieve value for object {3} with information", Version = 1)] private void RetrieveObjectInfo(int applicationId, Guid activityId, string attachmentId, int id) { WriteCore(2, applicationId, activityId, attachmentId, id); } [NonEvent] private unsafe void WriteCore(int eventId, int applicationId, Guid activityId, int a) { if (IsEnabled()) { const short dataCount = 3; EventData* data = stackalloc EventData[dataCount]; data[0].DataPointer = (IntPtr)(&applicationId); data[0].Size = 4; data[1].DataPointer = (IntPtr)(&activityId); data[1].Size = 16; data[2].DataPointer = (IntPtr)(&a); data[2].Size = 4; WriteEventCore(eventId, dataCount, data); } } [NonEvent] private unsafe void WriteCore(int eventId, int applicationId, Guid activityId, string a, int b) { if (IsEnabled()) { StringExtensions.SetToEmptyIfNull(ref a); fixed (char* aBytes = a) { const short dataCount = 4; EventData* data = stackalloc EventData[dataCount]; data[0].DataPointer = (IntPtr)(&applicationId); data[0].Size = 4; data[1].DataPointer = (IntPtr)(&activityId); data[1].Size = 16; data[2].DataPointer = (IntPtr)(aBytes); data[2].Size = ((a.Length + 1) * 2); data[3].DataPointer = (IntPtr)(&b); data[3].Size = 4; WriteEventCore(eventId, dataCount, data); } } } } }
34.19
125
0.542849
[ "MIT" ]
ChilliCream/LoggingCore
src/Clients/test/AspNetCore.FunctionalTest/EventSources/ValuesEventSources.cs
3,419
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 cloud9-2017-09-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Cloud9.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Cloud9.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ForbiddenException Object /// </summary> public class ForbiddenExceptionUnmarshaller : IErrorResponseUnmarshaller<ForbiddenException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ForbiddenException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public ForbiddenException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse) { context.Read(); ForbiddenException unmarshalledObject = new ForbiddenException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static ForbiddenExceptionUnmarshaller _instance = new ForbiddenExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ForbiddenExceptionUnmarshaller Instance { get { return _instance; } } } }
34.6
130
0.66644
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Cloud9/Generated/Model/Internal/MarshallTransformations/ForbiddenExceptionUnmarshaller.cs
2,941
C#
using System; using DataParser.Models; using System.Collections.Generic; using FormulasCollection.Helpers; using PinnacleWrapper.Enums; namespace DataParser.DefaultRealization { internal class EventFactory { private string lineId; private int matchPeriod; private long? leagueId; private string matchDateTime; public EventFactory(string lineId, int matchPeriod, long? leagueId, string matchDateTime) { this.lineId = lineId; this.matchPeriod = matchPeriod; this.leagueId = leagueId; this.matchDateTime = matchDateTime; } internal IEnumerable<EventWithTotalDictionary> CreateEventsWithTotal(string totalType, string totalValue, TeamType team, SideType? sideType, BetType? betType) { switch (matchPeriod) { case 0: return new[]{ new EventWithTotalDictionary { LineId = lineId, TotalType = totalType, TotalValue = totalValue, MatchDateTime = matchDateTime, LeagueId = leagueId, MatchPeriod = matchPeriod, TeamType = team, SideType = sideType, BetType = betType } }; case 1: case 2: return new[]{ new EventWithTotalDictionary { LineId = lineId, TotalType = totalType.ExtendType("H",matchPeriod), TotalValue = totalValue, MatchDateTime = matchDateTime, LeagueId = leagueId, MatchPeriod = matchPeriod, TeamType = team, SideType = sideType, BetType = betType } , new EventWithTotalDictionary { LineId = lineId, TotalType = totalType.ExtendType("P",matchPeriod), TotalValue = totalValue, MatchDateTime = matchDateTime, LeagueId = leagueId, MatchPeriod = matchPeriod, TeamType = team, SideType = sideType, BetType = betType }, new EventWithTotalDictionary { LineId = lineId, TotalType = totalType.ExtendType("Q",matchPeriod), TotalValue = totalValue, MatchDateTime = matchDateTime, LeagueId = leagueId, MatchPeriod = matchPeriod, TeamType = team, SideType = sideType, BetType = betType } , new EventWithTotalDictionary { LineId = lineId, TotalType = totalType.ExtendType("G",matchPeriod), TotalValue = totalValue, MatchDateTime = matchDateTime, LeagueId = leagueId, MatchPeriod = matchPeriod, TeamType = team, SideType = sideType, BetType = betType }, new EventWithTotalDictionary { LineId = lineId, TotalType = totalType.ExtendType("S",matchPeriod), TotalValue = totalValue, MatchDateTime = matchDateTime, LeagueId = leagueId, MatchPeriod = matchPeriod, TeamType = team, SideType = sideType, BetType = betType }, new EventWithTotalDictionary { LineId = lineId, TotalType = totalType.ExtendType("PR",matchPeriod), TotalValue = totalValue, MatchDateTime = matchDateTime, LeagueId = leagueId, MatchPeriod = matchPeriod, TeamType = team, SideType = sideType, BetType = betType }}; default: return new List<EventWithTotalDictionary>(); } } } }
40.861538
95
0.390625
[ "MIT" ]
Bohdan127/ArDependency
UniversalSolution/DataParser/DefaultRealization/EventFactory.cs
5,314
C#
//////////////////////////////// // // Copyright 2021 Battelle Energy Alliance, LLC // // //////////////////////////////// using System; using System.Collections.Generic; using System.Configuration; using System.IdentityModel.Tokens; using System.Linq; using System.Net; using System.Net.Mail; using System.Web; using CSETWeb_Api.BusinessLogic.Helpers; using CSETWeb_Api.Helpers; using CSETWeb_Api.Models; namespace CSETWeb_Api.BusinessLogic { /// <summary> /// Manages all email notifications. /// NOTE IMPORTANT YOU MUST SET THE CONFIGURATION MANAGER /// before calling this class. /// /// See the Global.asax.cs file for the implementation currently. /// </summary> public class NotificationManager { /// <summary> /// The client application that is in use. /// </summary> private string Scope; /// <summary> /// Display names for supported client applications, keyed by code/scope. /// </summary> private Dictionary<string, string> appDisplayName = new Dictionary<string, string>(); private static IConfigurationManager config; private static IConfigurationManager ConfigurationManager { get { if (config == null) throw new ApplicationException("You must set the configuration manager before calling this class"); return config; } set { config = value; } } public static void SetConfigurationManager(IConfigurationManager manager) { ConfigurationManager = manager; } /// <summary> /// Creates an instance of NotificationManager that /// uses the scope embedded in the JWT. /// </summary> public NotificationManager() { TokenManager tm = new TokenManager(); this.Scope = tm.Payload("scope"); Initialize(); } /// <summary> /// Creates an instance of NotificationManager with a /// specified scope/appCode. /// </summary> /// <param name="appCode"></param> public NotificationManager(string appCode) { this.Scope = appCode; Initialize(); } /// <summary> /// Performs initialization common to any instantiation. /// </summary> private void Initialize() { // Populate the app display names. this.appDisplayName.Add("CSET", "CSET"); this.appDisplayName.Add("ACET", "ACET"); } /// <summary> /// Sends an email to the recipient inviting them an Assessment. /// The content for this email is not defined by a template on the back end because the /// user might have customized the subject and/or body in the browser. /// /// See class level note (top of the file) /// </summary> public void InviteToAssessment(ContactCreateParameters contact) { string bodyHtml = ResourceHelper.GetEmbeddedResource(@"App_Data\assessmentInviteTemplate_" + this.Scope +".html"); // Build the name if supplied. string contactName = string.Empty; if (!string.IsNullOrEmpty(contact.FirstName) || !string.IsNullOrEmpty(contact.FirstName)) { contactName = (contact.FirstName + " " + contact.LastName).Trim() + ","; } bodyHtml = bodyHtml.Replace("{{name}}", contactName); bodyHtml = bodyHtml.Replace("{{subject}}", contact.Subject); bodyHtml = bodyHtml.Replace("{{body}}", contact.Body.Replace("\r\n", "<br/>").Replace("\r", "<br/>").Replace("\n", "<br/>")); bodyHtml = bodyHtml.Replace("{{id}}", contact.AssessmentId.ToString()); bodyHtml = bodyHtml.Replace("{{rootUrl}}", Utilities.GetClientHost()); MailMessage message = new MailMessage(); message.Subject = contact.Subject; message.Body = bodyHtml; message.IsBodyHtml = true; message.To.Add(new MailAddress(contact.PrimaryEmail)); message.From = new MailAddress( ConfigurationManager.GetAppSetting("Sender Email"), ConfigurationManager.GetAppSetting("Sender Display Name")); SendMail(message); } /// <summary> /// Sends an email to the recipient containing their temporary password. /// See class level note (top of the file) /// </summary> /// <param name="email"></param> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="password"></param> public void SendPasswordEmail(string email, string firstName, string lastName, string password) { string bodyHtml = ResourceHelper.GetEmbeddedResource(@"App_Data\passwordCreationTemplate_" + this.Scope + ".html"); bodyHtml = bodyHtml.Replace("{{name}}", firstName + " " + lastName); bodyHtml = bodyHtml.Replace("{{password}}", password); bodyHtml = bodyHtml.Replace("{{rootUrl}}", Utilities.GetClientHost()); MailMessage message = new MailMessage(); message.Subject = "New " + appDisplayName[this.Scope] + " account creation"; message.Body = bodyHtml; message.To.Add(new MailAddress(email)); message.From = new MailAddress( ConfigurationManager.GetAppSetting("Sender Email"), ConfigurationManager.GetAppSetting("Sender Display Name")); message.IsBodyHtml = true; SendMail(message); } /// <summary> /// Sends an email to the invitee containing their temporary password. /// See class level note (top of the file) /// </summary> /// <param name="email"></param> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="password"></param> public void SendInviteePassword(string email, string firstName, string lastName, string password) { string templateFile = @"App_Data\invitedPasswordCreationTemplate_" + this.Scope + ".html"; string bodyHtml = ResourceHelper.GetEmbeddedResource(templateFile); bodyHtml = bodyHtml.Replace("{{name}}", firstName + " " + lastName); bodyHtml = bodyHtml.Replace("{{password}}", password); bodyHtml = bodyHtml.Replace("{{rootUrl}}", Utilities.GetClientHost()); MailMessage message = new MailMessage(); message.Subject = "You are invited to " + appDisplayName[this.Scope]; message.Body = bodyHtml; message.To.Add(new MailAddress(email)); message.From = new MailAddress( ConfigurationManager.GetAppSetting("Sender Email"), ConfigurationManager.GetAppSetting("Sender Display Name")); message.IsBodyHtml = true; SendMail(message); } /// <summary> /// Sends an email to the recipient containing their newly-reset password. /// See class level note (top of the file) /// </summary> /// <param name="email"></param> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="password"></param> /// <param name="subject"></param> public void SendPasswordResetEmail(string email, string firstName, string lastName, string password, string subject) { string bodyHtml = ResourceHelper.GetEmbeddedResource(@"App_Data\passwordResetTemplate_" + this.Scope + ".html"); string name = (firstName + " " + lastName).Trim(); if (string.IsNullOrEmpty(name)) name = email; bodyHtml = bodyHtml.Replace("{{name}}", name); bodyHtml = bodyHtml.Replace("{{password}}", password); bodyHtml = bodyHtml.Replace("{{rootUrl}}", Utilities.GetClientHost()); MailMessage message = new MailMessage(); message.Subject = subject; message.Body = bodyHtml; message.To.Add(new MailAddress(email)); message.From = new MailAddress( ConfigurationManager.GetAppSetting("Sender Email"), ConfigurationManager.GetAppSetting("Sender Display Name")); message.IsBodyHtml = true; SendMail(message); } /// <summary> /// Sends a MailMessage using the configured SmtpClient. /// See class level note (top of the file) /// </summary> /// <param name="mail">MailMessage mail = new MailMessage("you@yourcompany.com", "user@hotmail.com");</param> public void SendMail(MailMessage mail) { #if DEBUG // Override the recipient if configured for debug string debugRecipient = ConfigurationManager.GetAppSetting("DEBUG EMAIL RECIPIENT"); if (!string.IsNullOrWhiteSpace(debugRecipient)) { mail.To.RemoveAt(0); mail.To.Add(new MailAddress(debugRecipient)); } #endif // apply stylesheet string inlineStylesheet = ResourceHelper.GetEmbeddedResource(@"App_Data\inlineStylesheet.html"); mail.Body = mail.Body.Replace("{{inline-stylesheet}}", inlineStylesheet); SmtpClient client = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.Network, Host = ConfigurationManager.GetAppSetting("SMTP Host"), Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SMTP Port"]), UseDefaultCredentials = false }; bool.TryParse(ConfigurationManager.GetAppSetting("SMTP SSL"), out bool ssl); client.EnableSsl = ssl; var smtpUsername = ConfigurationManager.GetAppSetting("SMTP Username"); var smtpPassword = ConfigurationManager.GetAppSetting("SMTP Password"); if (smtpUsername != null) { client.Credentials = new NetworkCredential(smtpUsername, smtpPassword); } try { client.Send(mail); } catch (Exception exc) { CsetLogManager.Instance.LogErrorMessage("Exception thrown in NotificationManager.SendMail(): {0}", exc.ToString()); throw exc; } } /// <summary> /// Sends a test email. /// </summary> public void SendTestEmail(string recip) { // only send the email if configured to do so (unpublished app setting) bool allowed = false; string allowSetting = ConfigurationManager.GetAppSetting("Allow Test Email"); if (allowSetting == null || !bool.TryParse(allowSetting, out allowed)) { if (!allowed) { throw new Exception("Not configured to send test emails"); } } MailMessage m = new MailMessage(); m.Subject = appDisplayName[this.Scope] + " Test Message"; m.Body = string.Format("Testing email server {0} on port {1}", ConfigurationManager.GetAppSetting("SMTP Host"), System.Configuration.ConfigurationManager.AppSettings["SMTP Port"]); m.To.Add(new MailAddress(recip)); m.From = new MailAddress( ConfigurationManager.GetAppSetting("Sender Email"), ConfigurationManager.GetAppSetting("Sender Display Name")); this.SendMail(m); } } }
38.514658
137
0.582713
[ "MIT" ]
itcms/cset
CSETWebApi/CSETWeb_Api/BusinessLogic/BusinessManagers/NotificationManager.cs
11,824
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace CodePlusXaml.WinPhone81 { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { private TransitionCollection transitions; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity deferral.Complete(); } } }
39.029412
126
0.610588
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter07/FS/CodePlusXaml/CodePlusXaml/CodePlusXaml.WinPhone81/App.xaml.cs
5,310
C#
namespace GraduatedCylinder { /// <summary> /// Units of Energy that are currently supported, Joules is the Base Unit. /// </summary> public enum EnergyUnit { /// <summary> /// Joules, This is the Base Unit /// </summary> BaseUnit = Joules, /// <summary> /// Joules, This is the Base Unit /// </summary> [UnitAbbreviation("J")] [Scale(1.0)] Joules = 0, /// <summary> /// Newton x Meters /// </summary> [UnitAbbreviation("Nm")] [Scale(1.0)] NewtonMeters = 1, /// <summary> /// Watt x Seconds /// </summary> [UnitAbbreviation("Ws")] [Scale(1.0)] WattSeconds = 2, /// <summary> /// Calories /// </summary> [UnitAbbreviation("cal")] [Scale(4.1868)] Calories = 3, /// <summary> /// Kilogram Force x Meters /// </summary> [UnitAbbreviation("kgfm")] [Scale(9.80665)] KilogramForceMeters = 4, /// <summary> /// KiloJoules, 1000 Joules /// </summary> [UnitAbbreviation("kJ")] [Scale(1000.0)] Kilojoules = 5, /// <summary> /// Watts x Hours /// </summary> [UnitAbbreviation("Wh")] [Scale(3600.0)] WattHours = 6, /// <summary> /// KiloCalories, 1000 Calories /// </summary> [UnitAbbreviation("kcal")] [Scale(4186.8)] KiloCalories = 7, /// <summary> /// KiloWatt x Hours /// </summary> [UnitAbbreviation("kWh")] [Scale(3600000.0)] KilowattHours = 8, /// <summary> /// British Thermal Units /// </summary> [UnitAbbreviation("BTU")] [Scale(1055.056)] BritishThermalUnit = 9 } }
23.578313
82
0.451201
[ "MIT" ]
EddieGarmon/GraduatedCylinder
Source/GraduatedCylinder/GraduatedCylinder/[Dimensions-Typed]/SI derived/EnergyUnit.cs
1,957
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.AwsNative.EC2.Outputs { [OutputType] public sealed class NetworkInsightsAnalysisAnalysisRouteTableRoute { public readonly string? DestinationCidr; public readonly string? DestinationPrefixListId; public readonly string? EgressOnlyInternetGatewayId; public readonly string? GatewayId; public readonly string? InstanceId; public readonly string? NatGatewayId; public readonly string? NetworkInterfaceId; public readonly string? Origin; public readonly string? TransitGatewayId; public readonly string? VpcPeeringConnectionId; [OutputConstructor] private NetworkInsightsAnalysisAnalysisRouteTableRoute( string? destinationCidr, string? destinationPrefixListId, string? egressOnlyInternetGatewayId, string? gatewayId, string? instanceId, string? natGatewayId, string? networkInterfaceId, string? origin, string? transitGatewayId, string? vpcPeeringConnectionId) { DestinationCidr = destinationCidr; DestinationPrefixListId = destinationPrefixListId; EgressOnlyInternetGatewayId = egressOnlyInternetGatewayId; GatewayId = gatewayId; InstanceId = instanceId; NatGatewayId = natGatewayId; NetworkInterfaceId = networkInterfaceId; Origin = origin; TransitGatewayId = transitGatewayId; VpcPeeringConnectionId = vpcPeeringConnectionId; } } }
31.080645
81
0.67151
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/EC2/Outputs/NetworkInsightsAnalysisAnalysisRouteTableRoute.cs
1,927
C#
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information. using System; using System.Collections.Generic; using ClangSharp.Interop; namespace ClangSharp { public sealed class TemplateTypeParmDecl : TypeDecl { private readonly Lazy<IReadOnlyList<Expr>> _associatedConstraints; private readonly Lazy<Type> _defaultArgument; internal TemplateTypeParmDecl(CXCursor handle) : base(handle, CXCursorKind.CXCursor_TemplateTypeParameter, CX_DeclKind.CX_DeclKind_TemplateTypeParm) { _associatedConstraints = new Lazy<IReadOnlyList<Expr>>(() => { var associatedConstraintCount = Handle.NumAssociatedConstraints; var associatedConstraints = new List<Expr>(associatedConstraintCount); for (var i = 0; i < associatedConstraintCount; i++) { var parameter = TranslationUnit.GetOrCreate<Expr>(Handle.GetAssociatedConstraint(unchecked((uint)i))); associatedConstraints.Add(parameter); } return associatedConstraints; }); _defaultArgument = new Lazy<Type>(() => TranslationUnit.GetOrCreate<Type>(Handle.DefaultArgType)); } public IReadOnlyList<Expr> AssociatedConstraints => _associatedConstraints.Value; public Type DefaultArgument => _defaultArgument.Value; public bool DefaultArgumentWasInherited => Handle.HasInheritedDefaultArg; public int Depth => Handle.TemplateTypeParmDepth; public int Index => Handle.TemplateTypeParmIndex; public bool HasDefaultArgument => Handle.HasDefaultArg; public bool IsExpandedParameterPack => Handle.IsExpandedParameterPack; public bool IsPackExpansion => Handle.IsPackExpansion; public bool IsParameterPack => Handle.IsParameterPack; } }
39.56
169
0.695147
[ "MIT" ]
Color-Of-Code/ClangSharp
sources/ClangSharp/Cursors/Decls/TemplateTypeParmDecl.cs
1,978
C#
using System.Linq; using System.Threading.Tasks; using Ardalis.Specification; using CleanArchitecture.Core.ProjectAggregate; using CleanArchitecture.Core.Services; using CleanArchitecture.SharedKernel.Interfaces; using Moq; using Xunit; namespace CleanArchitecture.UnitTests.Core.Services { public class ToDoItemSearchService_GetAllIncompleteItems { private Mock<IRepository<ToDoItem>> _mockRepo = new Mock<IRepository<ToDoItem>>(); private ToDoItemSearchService _searchService; public ToDoItemSearchService_GetAllIncompleteItems() { _searchService = new ToDoItemSearchService(_mockRepo.Object); } [Fact] public async Task ReturnsInvalidGivenNullSearchString() { var result = await _searchService.GetAllIncompleteItemsAsync(null); Assert.Equal(Ardalis.Result.ResultStatus.Invalid, result.Status); Assert.Equal("searchString is required.", result.ValidationErrors.First().ErrorMessage); } [Fact] public async Task ReturnsErrorGivenDataAccessException() { string expectedErrorMessage = "Database not there."; _mockRepo.Setup(r => r.ListAsync(It.IsAny<ISpecification<ToDoItem>>())) .ThrowsAsync(new System.Exception(expectedErrorMessage)); var result = await _searchService.GetAllIncompleteItemsAsync("something"); Assert.Equal(Ardalis.Result.ResultStatus.Error, result.Status); Assert.Equal(expectedErrorMessage, result.Errors.First()); } [Fact] public async Task ReturnsListGivenSearchString() { var result = await _searchService.GetAllIncompleteItemsAsync("foo"); Assert.Equal(Ardalis.Result.ResultStatus.Ok, result.Status); } } }
34.660377
100
0.691345
[ "MIT" ]
bohdan-skrypka/architecture-ardalis-CleanArchitecture
CleanArchitecture/tests/CleanArchitecture.UnitTests/Core/Services/ToDoItemSearchService_GetAllIncompleteItems.cs
1,839
C#
// Copyright 2019 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.TimeZones; using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; namespace NodaTime.Tools.ValidateHistoricalNzd { class Program { private static async Task<int> Main() { var httpClient = new HttpClient(); var allUrlsText = await httpClient.GetStringAsync("https://nodatime.org/tzdb/index.txt"); var urls = allUrlsText.Replace("\r", "").Split("\n", StringSplitOptions.RemoveEmptyEntries); bool success = true; foreach (var url in urls) { success &= await ValidateAsync(httpClient, url); } return success ? 0 : 1; } private static async Task<bool> ValidateAsync(HttpClient httpClient, string url) { try { Console.WriteLine($"Validating {url}"); byte[] data = await httpClient.GetByteArrayAsync(url); var source = TzdbDateTimeZoneSource.FromStream(new MemoryStream(data)); source.Validate(); return true; } catch (Exception e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); return false; } } } }
32.021739
104
0.568228
[ "Apache-2.0" ]
0xced/nodatime
src/NodaTime.Tools.ValidateHistoricalNzd/Program.cs
1,475
C#
namespace Fesb.Hydrocontest.Domain.ValueObjects { public class Potentiometer { public double Left { get; } public double Right { get; } public Potentiometer ( double left, double right ) { Left = left; Right = right; } public static bool operator ==(Potentiometer first, Potentiometer second) => first.Left == second.Left && first.Right == second.Right; public static bool operator !=(Potentiometer first, Potentiometer second) => !(first == second); } }
24.72
104
0.545307
[ "MIT" ]
ratokuzmanic/FESB.Hydrocontest
Fesb.Hydrocontest.Domain/ValueObjects/Potentiometer.cs
620
C#
using System.Data.SqlClient; namespace Namster.Jobs.ElasticSync.Services { public class DbService { public SqlConnection GetDbConnection(string connection) { var conn = new SqlConnection(connection); return conn; } } }
20.071429
63
0.626335
[ "MIT" ]
ucdavis/Namster
src/Namster.Jobs.ElasticSync/Services/DbService.cs
283
C#
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Pex.Framework; namespace EvaluationTests.Annotations { public static class Evaluation { /// <summary> /// Symbol used to conditionally add contract hints. /// </summary> public const string ContractsHintsSymbol = "EVALUATION_CC_HINTS"; /// <remarks> /// During the contract checking, the precondition is propagated to the call site as an assertion. /// </remarks> public static void ValidAssert(bool condition) { Contract.Requires(condition); } /// <summary> /// Valid assertion skipped in tests. /// </summary> /// <remarks> /// During the contract checking, the precondition is propagated to the call site as an assertion. /// </remarks> public static void SkippedValidAssert(bool condition) { Contract.Requires(condition); } /// <remarks> /// During the contract checking, the precondition is propagated to the call site as an assertion. /// </remarks> public static void InvalidAssert(bool condition) { Contract.Requires(condition); } /// <summary> /// Invalid assertion skipped in tests. /// </summary> /// <remarks> /// During the contract checking, the precondition is propagated to the call site as an assertion. /// </remarks> public static void SkippedInvalidAssert(bool condition) { Contract.Requires(condition); } /// <remarks> /// This precondition is satisfied only if the call site is not reachable. /// </remarks> public static void ValidUnreachable() { Contract.Requires(false); } /// <remarks> /// This precondition is satisfied only if the call site is not reachable. /// </remarks> public static void SkippedValidUnreachable() { Contract.Requires(false); } /// <remarks> /// This precondition is satisfied only if the call site is not reachable. /// </remarks> public static void InvalidUnreachable() { Contract.Requires(false); } /// <remarks> /// This precondition is satisfied only if the call site is not reachable. /// </remarks> public static void SkippedInvalidUnreachable() { Contract.Requires(false); } } }
30.179775
106
0.586374
[ "Apache-2.0" ]
TomatorCZ/AskTheCode
test/inputs/csharp/EvaluationTests/Annotations/Evaluation.cs
2,688
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 appmesh-2019-01-25.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.AppMesh.Model { /// <summary> /// An object that represents the path to rewrite. /// </summary> public partial class HttpGatewayRoutePathRewrite { private string _exact; /// <summary> /// Gets and sets the property Exact. /// <para> /// The exact path to rewrite. /// </para> /// </summary> [AWSProperty(Min=1, Max=255)] public string Exact { get { return this._exact; } set { this._exact = value; } } // Check to see if Exact property is set internal bool IsSetExact() { return this._exact != null; } } }
27.362069
105
0.640202
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/AppMesh/Generated/Model/HttpGatewayRoutePathRewrite.cs
1,587
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.CloudDirectory; using Amazon.CloudDirectory.Model; namespace Amazon.PowerShell.Cmdlets.CDIR { /// <summary> /// Lists schema major versions applied to a directory. If <code>SchemaArn</code> is provided, /// lists the minor version.<br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration. /// </summary> [Cmdlet("Get", "CDIRAppliedSchemaArn")] [OutputType("System.String")] [AWSCmdlet("Calls the Amazon Cloud Directory ListAppliedSchemaArns API operation.", Operation = new[] {"ListAppliedSchemaArns"}, SelectReturnType = typeof(Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse))] [AWSCmdletOutput("System.String or Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse", "This cmdlet returns a collection of System.String objects.", "The service call response (type Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class GetCDIRAppliedSchemaArnCmdlet : AmazonCloudDirectoryClientCmdlet, IExecutor { #region Parameter DirectoryArn /// <summary> /// <para> /// <para>The ARN of the directory you are listing.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String DirectoryArn { get; set; } #endregion #region Parameter SchemaArn /// <summary> /// <para> /// <para>The response for <code>ListAppliedSchemaArns</code> when this parameter is used will /// list all minor version ARNs for a major version.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String SchemaArn { get; set; } #endregion #region Parameter MaxResult /// <summary> /// <para> /// <para>The maximum number of results to retrieve.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("MaxResults")] public System.Int32? MaxResult { get; set; } #endregion #region Parameter NextToken /// <summary> /// <para> /// <para>The pagination token.</para> /// </para> /// <para> /// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call. /// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls. /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String NextToken { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'SchemaArns'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse). /// Specifying the name of a property of type Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "SchemaArns"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the DirectoryArn parameter. /// The -PassThru parameter is deprecated, use -Select '^DirectoryArn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^DirectoryArn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter NoAutoIteration /// <summary> /// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple /// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken /// as the start point. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter NoAutoIteration { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse, GetCDIRAppliedSchemaArnCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.DirectoryArn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.DirectoryArn = this.DirectoryArn; #if MODULAR if (this.DirectoryArn == null && ParameterWasBound(nameof(this.DirectoryArn))) { WriteWarning("You are passing $null as a value for parameter DirectoryArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.MaxResult = this.MaxResult; context.NextToken = this.NextToken; context.SchemaArn = this.SchemaArn; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent; #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute // create request and set iteration invariants var request = new Amazon.CloudDirectory.Model.ListAppliedSchemaArnsRequest(); if (cmdletContext.DirectoryArn != null) { request.DirectoryArn = cmdletContext.DirectoryArn; } if (cmdletContext.MaxResult != null) { request.MaxResults = cmdletContext.MaxResult.Value; } if (cmdletContext.SchemaArn != null) { request.SchemaArn = cmdletContext.SchemaArn; } // Initialize loop variant and commence piping var _nextToken = cmdletContext.NextToken; var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken)); var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); do { request.NextToken = _nextToken; CmdletOutput output; try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; if (!useParameterSelect) { pipelineOutput = cmdletContext.Select(response, this); } output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; _nextToken = response.NextToken; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } ProcessOutput(output); } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken)); if (useParameterSelect) { WriteObject(cmdletContext.Select(null, this)); } return null; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse CallAWSServiceOperation(IAmazonCloudDirectory client, Amazon.CloudDirectory.Model.ListAppliedSchemaArnsRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Cloud Directory", "ListAppliedSchemaArns"); try { #if DESKTOP return client.ListAppliedSchemaArns(request); #elif CORECLR return client.ListAppliedSchemaArnsAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String DirectoryArn { get; set; } public System.Int32? MaxResult { get; set; } public System.String NextToken { get; set; } public System.String SchemaArn { get; set; } public System.Func<Amazon.CloudDirectory.Model.ListAppliedSchemaArnsResponse, GetCDIRAppliedSchemaArnCmdlet, object> Select { get; set; } = (response, cmdlet) => response.SchemaArns; } } }
46.086505
283
0.605
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/CloudDirectory/Basic/Get-CDIRAppliedSchemaArn-Cmdlet.cs
13,319
C#
using Domain; namespace Api { public class JobReportResponse { public Log[] Logs { get; set; } } }
13.222222
39
0.588235
[ "MIT" ]
rescodeio/DotNetCoreDddTemplate
Api/Api/Services/GetJobReport/JobReportResponse.cs
119
C#
namespace _12.Google { public class Pokemon { public Pokemon(string name, string element) { this.Name = name; this.Element = element; } public string Name { get; set; } public string Element { get; set; } public override string ToString() { return this.Name + " " + this.Element; } } }
21.052632
51
0.505
[ "MIT" ]
V-Uzunov/Soft-Uni-Education
07.C#OOPBasic/01.DefiningClasses/12.Google/Pokemon.cs
402
C#
/* Benjamin Lanza * F117Reader.cs * October 11th, 2018 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Net; using System.Net.Sockets; using static LibSimTelem.F117Defs; using System.Runtime.InteropServices; namespace LibSimTelem { public class F117Reader : TelemReader { /* Event handler declarations */ public delegate void PacketReceived(object sender, F117ReceivedEventArgs args); public event PacketReceived PacketReceivedEvent; /* Fields */ private int port; private string ip; private int timeout; private volatile bool isRunning = false; private static Mutex flagMtx = new Mutex(); private Thread receiverThread; /* Constructor */ public F117Reader(int port = DEFAULT_PORT, string ip = DEFAULT_IP, int timeout = DEFAULT_TIMEOUT) { this.port = port; this.ip = ip; this.timeout = timeout; } /* Starts listening for data */ public bool Start(params object[] args) { /* Returns false if Start() has previously been called */ flagMtx.WaitOne(); if (isRunning) { flagMtx.ReleaseMutex(); return false; } else { isRunning = true; flagMtx.ReleaseMutex(); } /* Starts the receiving thread and returns true */ receiverThread = new Thread(ThreadRoutine); receiverThread.Start(); return true; } /* Signals the receiver thread to stop and cleans up */ public bool Stop() { /* Returns false if the program isn't already running */ flagMtx.WaitOne(); if (!isRunning) { flagMtx.ReleaseMutex(); return false; } else { isRunning = false; flagMtx.ReleaseMutex(); } /* Waits for the receiver thread to join and returns true */ receiverThread.Join(); return true; } /* Receives packets and raises events continuously on a thread */ private void ThreadRoutine() { /* Sets up UDP connection objects */ UdpClient client = new UdpClient(port); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port); client.Client.ReceiveTimeout = timeout; /* Loops until broken by the isRunning flag */ while (true) { /* Break if isRunning is false */ flagMtx.WaitOne(); if(!isRunning) { flagMtx.ReleaseMutex(); break; } else { flagMtx.ReleaseMutex(); } byte[] data; /* Try to get data from the socket and restart the loop on timeout */ try { data = client.Receive(ref ep); } catch (SocketException e) { continue; } /* Restart the loop if the packet is invalid */ if(!IsValidPacketData(ref data)) continue; /* Create arguments object for triggering event */ F117ReceivedEventArgs args = new F117ReceivedEventArgs(ParsePacket(ref data)); /* Raise event */ RaisePacketReceived(args); } client.Close(); } /* Raises a PacketReceivedEvent if someone has subscribed to it */ private void RaisePacketReceived(F117ReceivedEventArgs args) { PacketReceivedEvent?.Invoke(this, args); } /* Returns true if the passed byte array is the same size as a UDPPacket */ private bool IsValidPacketData(ref byte[] bytes) { return (bytes.Length == PACKET_SIZE); } /* Parses a packet from the given bytes */ private UDPPacket ParsePacket(ref byte[] bytes) { UDPPacket ret; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { ret = Marshal.PtrToStructure<UDPPacket>(handle.AddrOfPinnedObject()); } finally { handle.Free(); } return ret; } } /* F117ReceivedEventArgs class definition */ public class F117ReceivedEventArgs : EventArgs { public UDPPacket packet; public F117ReceivedEventArgs(UDPPacket packet) { this.packet = packet; } } }
31.527397
95
0.560721
[ "MIT" ]
btlanza/LibSimTelem
LibSimTelem/F117Reader.cs
4,605
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; public class CloseContextMenu : MonoBehaviour { void OnGUI() { if (Event.current.type == EventType.MouseDown && !RectTransformUtility.RectangleContainsScreenPoint( gameObject.GetComponent<RectTransform>(), Input.mousePosition, null)) { Destroy(gameObject); } } }
25.722222
63
0.568035
[ "CC0-1.0" ]
Fuskalachi/Village-God
Assets/Scripts/UI/ContextMenu/CloseContextMenu.cs
465
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26 { using HL7; /// <summary> /// OPL_O37_PATIENT_VISIT_PRIOR (Group) - /// </summary> public interface OPL_O37_PATIENT_VISIT_PRIOR : HL7V26Layout { /// <summary> /// PV1 /// </summary> Segment<PV1> PV1 { get; } /// <summary> /// PV2 /// </summary> Segment<PV2> PV2 { get; } } }
25.333333
105
0.583882
[ "Apache-2.0" ]
AreebaAroosh/Machete
src/Machete.HL7Schema/Generated/V26/Groups/OPL_O37_PATIENT_VISIT_PRIOR.cs
608
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using System.Collections.Generic; namespace Aliyun.Acs.Baas.Model.V20180731 { public class DescribeOrganizationMembersResponse : AcsResponse { private string requestId; private bool? success; private int? errorCode; private List<DescribeOrganizationMembers_DescribeOrganizationMembers> result; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public int? ErrorCode { get { return errorCode; } set { errorCode = value; } } public List<DescribeOrganizationMembers_DescribeOrganizationMembers> Result { get { return result; } set { result = value; } } public class DescribeOrganizationMembers_DescribeOrganizationMembers { private string id; private string name; private string consortiumId; private string consortiumName; private string domain; private string description; private string joinedTime; private string state; public string Id { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public string ConsortiumId { get { return consortiumId; } set { consortiumId = value; } } public string ConsortiumName { get { return consortiumName; } set { consortiumName = value; } } public string Domain { get { return domain; } set { domain = value; } } public string Description { get { return description; } set { description = value; } } public string JoinedTime { get { return joinedTime; } set { joinedTime = value; } } public string State { get { return state; } set { state = value; } } } } }
15.643216
80
0.575972
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-baas/Baas/Model/V20180731/DescribeOrganizationMembersResponse.cs
3,113
C#
namespace MonopolyGame.Model.Classes.Tiles { using System.Collections.Generic; using Model.Classes.Actions; using Model.Classes.Actions.Contracts; using Model.Classes.Tiles.Contracts; using Model.Common.Validators; public class TaxTile : ChoosableActionTile, IChoosableAction { public TaxTile(string name, int tax) : base(name) { this.Tax = tax; this.AddAction(new TaxAction()); } public int Tax { get; private set; } } }
25
64
0.630476
[ "MIT" ]
GAlex7/TA
03. CSharpOOP/TeamWork/Model/Classes/Tiles/TaxTile.cs
527
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.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Xunit; namespace Microsoft.Azure.Commands.Insights.Test.ScenarioTests { public class AlertsTests : RMTestBase { public AlertsTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestNewAzureRmAlertRuleWebhook() { TestsController.NewInstance.RunPsTest("Test-NewAzureRmAlertRuleWebhook"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestNewAzureRmAlertRuleEmail() { TestsController.NewInstance.RunPsTest("Test-NewAzureRmAlertRuleEmail"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAddAzureRmMetricAlertRule() { TestsController.NewInstance.RunPsTest("Test-AddAzureRmMetricAlertRule"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAddAzureRmWebtestAlertRule() { TestsController.NewInstance.RunPsTest("Test-AddAzureRmWebtestAlertRule"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestGetAzureRmAlertRule() { TestsController.NewInstance.RunPsTest("Test-GetAzureRmAlertRule"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestGetAzureRmAlertRuleByName() { TestsController.NewInstance.RunPsTest("Test-GetAzureRmAlertRuleByName"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestRemoveAzureRmAlertRule() { TestsController.NewInstance.RunPsTest("Test-RemoveAzureRmAlertRule"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestGetAzureRmAlertHistory() { TestsController.NewInstance.RunPsTest("Test-GetAzureRmAlertHistory"); } } }
37.270588
153
0.630051
[ "MIT" ]
AzureDataBox/azure-powershell
src/ResourceManager/Insights/Commands.Insights.Test/ScenarioTests/AlertsTests.cs
3,086
C#
using CrisisCheckinMobile.iOS; using CrisisCheckinMobile.SaveLoad; using System; using System.IO; using Xamarin.Forms; [assembly: Dependency (typeof (SaveAndLoad_iOS))] namespace CrisisCheckinMobile.iOS { public class SaveAndLoad_iOS : ISaveAndLoad { public SaveAndLoad_iOS() {} public void SaveText(string filename, string text) { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var filePath = Path.Combine(documentsPath, filename); System.IO.File.WriteAllText(filePath, text); } public string LoadText(string filename) { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var filePath = Path.Combine(documentsPath, filename); return System.IO.File.ReadAllText(filePath); } } }
27.964286
85
0.776501
[ "Apache-2.0" ]
jplwood/crisischeckin
crisischeckin/CrisisCheckinMobile/CrisisCheckinMobile.iOS/SaveAndLoad_iOS.cs
783
C#
using System.Collections.Generic; using System.IO; namespace OpenVIII { public partial class Kernel_bin { /// <summary> /// Menu Abilities Data /// </summary> /// <see cref="https://github.com/alexfilth/doomtrain/wiki/Menu-abilities"/> public class Menu_abilities :Ability { public new const int count = 24; public new const int id = 17; public override string ToString() => Name; public byte Index { get; private set; } public byte Start { get; private set; } public byte End { get; private set; } public override void Read(BinaryReader br, int i) { Icon = Icons.ID.Ability_Menu; Name = Memory.Strings.Read(Strings.FileID.KERNEL, id, i * 2); //0x0000 2 bytes Offset to name Description = Memory.Strings.Read(Strings.FileID.KERNEL, id, i * 2 + 1); //0x0002 2 bytes Offset to description br.BaseStream.Seek(4, SeekOrigin.Current); AP = br.ReadByte(); //0x0004 1 byte AP Required to learn ability Index = br.ReadByte(); //0x0005 1 byte Index to m00X files in menu.fs //(first 3 sections are treated as special cases) Start = br.ReadByte(); //0x0006 1 byte Start offset End = br.ReadByte(); //0x0007 1 byte End offset } public static Dictionary<Abilities,Menu_abilities> Read(BinaryReader br) { Dictionary<Abilities, Menu_abilities> ret = new Dictionary<Abilities, Menu_abilities>(count); for (int i = 0; i < count; i++) { var tmp = new Menu_abilities(); tmp.Read(br, i); ret[(Abilities)(i+(int)Abilities.Haggle)] = tmp; } return ret; } } } }
37.109091
109
0.513964
[ "MIT" ]
MattLisson/OpenVIII
Core/Kernel/Kernel_bin.Menu_abilities.cs
2,043
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DiamondBehavior : MonoBehaviour { Vector3 rotate = new Vector3(0, 1, 0); public GameObject diamond; private void Awake() { //Activate(true); } // Update is called once per frame void Update() { transform.eulerAngles += rotate; } public void Activate(bool active) { //diamond.SetActive(active); } }
19.826087
46
0.64693
[ "MIT" ]
pointoflight/indoor_nav
IndoorNavigation/Assets/Scripts/Source/DiamondBehavior.cs
458
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.Dns.Models { /// <summary> Parameters supplied to update a record set. </summary> internal partial class RecordSetUpdateParameters { /// <summary> Initializes a new instance of RecordSetUpdateParameters. </summary> internal RecordSetUpdateParameters() { } /// <summary> Specifies information about the record set being updated. </summary> public RecordSet RecordSet { get; } } }
27.909091
90
0.685668
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/dns/Azure.ResourceManager.Dns/src/Generated/Models/RecordSetUpdateParameters.cs
614
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 datasync-2018-11-09.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Net; using Amazon.DataSync.Model; using Amazon.DataSync.Model.Internal.MarshallTransformations; using Amazon.DataSync.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.DataSync { /// <summary> /// Implementation for accessing DataSync /// /// AWS DataSync /// <para> /// AWS DataSync is a managed data transfer service that makes it simpler for you to automate /// moving data between on-premises storage and Amazon Simple Storage Service (Amazon /// S3) or Amazon Elastic File System (Amazon EFS). /// </para> /// /// <para> /// This API interface reference for AWS DataSync contains documentation for a programming /// interface that you can use to manage AWS DataSync. /// </para> /// </summary> public partial class AmazonDataSyncClient : AmazonServiceClient, IAmazonDataSync { private static IServiceMetadata serviceMetadata = new AmazonDataSyncMetadata(); private IDataSyncPaginatorFactory _paginators; /// <summary> /// Paginators for the service /// </summary> public IDataSyncPaginatorFactory Paginators { get { if (this._paginators == null) { this._paginators = new DataSyncPaginatorFactory(this); } return this._paginators; } } #region Constructors /// <summary> /// Constructs AmazonDataSyncClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonDataSyncClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonDataSyncConfig()) { } /// <summary> /// Constructs AmazonDataSyncClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonDataSyncClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonDataSyncConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDataSyncClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonDataSyncClient Configuration Object</param> public AmazonDataSyncClient(AmazonDataSyncConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonDataSyncClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonDataSyncClient(AWSCredentials credentials) : this(credentials, new AmazonDataSyncConfig()) { } /// <summary> /// Constructs AmazonDataSyncClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonDataSyncClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonDataSyncConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDataSyncClient with AWS Credentials and an /// AmazonDataSyncClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonDataSyncClient Configuration Object</param> public AmazonDataSyncClient(AWSCredentials credentials, AmazonDataSyncConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonDataSyncClient 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 AmazonDataSyncClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonDataSyncConfig()) { } /// <summary> /// Constructs AmazonDataSyncClient 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 AmazonDataSyncClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonDataSyncConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonDataSyncClient with AWS Access Key ID, AWS Secret Key and an /// AmazonDataSyncClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonDataSyncClient Configuration Object</param> public AmazonDataSyncClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonDataSyncConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonDataSyncClient 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 AmazonDataSyncClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDataSyncConfig()) { } /// <summary> /// Constructs AmazonDataSyncClient 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 AmazonDataSyncClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonDataSyncConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonDataSyncClient with AWS Access Key ID, AWS Secret Key and an /// AmazonDataSyncClient 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 AmazonDataSyncClient Configuration Object</param> public AmazonDataSyncClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonDataSyncConfig 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 CancelTaskExecution /// <summary> /// Cancels execution of a task. /// /// /// <para> /// When you cancel a task execution, the transfer of some files is abruptly interrupted. /// The contents of files that are transferred to the destination might be incomplete /// or inconsistent with the source files. However, if you start a new task execution /// on the same task and you allow the task execution to complete, file content on the /// destination is complete and consistent. This applies to other unexpected failures /// that interrupt a task execution. In all of these cases, AWS DataSync successfully /// complete the transfer when you start the next task execution. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CancelTaskExecution service method.</param> /// /// <returns>The response from the CancelTaskExecution service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CancelTaskExecution">REST API Reference for CancelTaskExecution Operation</seealso> public virtual CancelTaskExecutionResponse CancelTaskExecution(CancelTaskExecutionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CancelTaskExecutionRequestMarshaller.Instance; options.ResponseUnmarshaller = CancelTaskExecutionResponseUnmarshaller.Instance; return Invoke<CancelTaskExecutionResponse>(request, options); } /// <summary> /// Cancels execution of a task. /// /// /// <para> /// When you cancel a task execution, the transfer of some files is abruptly interrupted. /// The contents of files that are transferred to the destination might be incomplete /// or inconsistent with the source files. However, if you start a new task execution /// on the same task and you allow the task execution to complete, file content on the /// destination is complete and consistent. This applies to other unexpected failures /// that interrupt a task execution. In all of these cases, AWS DataSync successfully /// complete the transfer when you start the next task execution. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CancelTaskExecution service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CancelTaskExecution service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CancelTaskExecution">REST API Reference for CancelTaskExecution Operation</seealso> public virtual Task<CancelTaskExecutionResponse> CancelTaskExecutionAsync(CancelTaskExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CancelTaskExecutionRequestMarshaller.Instance; options.ResponseUnmarshaller = CancelTaskExecutionResponseUnmarshaller.Instance; return InvokeAsync<CancelTaskExecutionResponse>(request, options, cancellationToken); } #endregion #region CreateAgent /// <summary> /// Activates an AWS DataSync agent that you have deployed on your host. The activation /// process associates your agent with your account. In the activation process, you specify /// information such as the AWS Region that you want to activate the agent in. You activate /// the agent in the AWS Region where your target locations (in Amazon S3 or Amazon EFS) /// reside. Your tasks are created in this AWS Region. /// /// /// <para> /// You can activate the agent in a VPC (virtual private cloud) or provide the agent access /// to a VPC endpoint so you can run tasks without going over the public Internet. /// </para> /// /// <para> /// You can use an agent for more than one location. If a task uses multiple agents, all /// of them need to have status AVAILABLE for the task to run. If you use multiple agents /// for a source location, the status of all the agents must be AVAILABLE for the task /// to run. /// </para> /// /// <para> /// Agents are automatically updated by AWS on a regular basis, using a mechanism that /// ensures minimal interruption to your tasks. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAgent service method.</param> /// /// <returns>The response from the CreateAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateAgent">REST API Reference for CreateAgent Operation</seealso> public virtual CreateAgentResponse CreateAgent(CreateAgentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateAgentResponseUnmarshaller.Instance; return Invoke<CreateAgentResponse>(request, options); } /// <summary> /// Activates an AWS DataSync agent that you have deployed on your host. The activation /// process associates your agent with your account. In the activation process, you specify /// information such as the AWS Region that you want to activate the agent in. You activate /// the agent in the AWS Region where your target locations (in Amazon S3 or Amazon EFS) /// reside. Your tasks are created in this AWS Region. /// /// /// <para> /// You can activate the agent in a VPC (virtual private cloud) or provide the agent access /// to a VPC endpoint so you can run tasks without going over the public Internet. /// </para> /// /// <para> /// You can use an agent for more than one location. If a task uses multiple agents, all /// of them need to have status AVAILABLE for the task to run. If you use multiple agents /// for a source location, the status of all the agents must be AVAILABLE for the task /// to run. /// </para> /// /// <para> /// Agents are automatically updated by AWS on a regular basis, using a mechanism that /// ensures minimal interruption to your tasks. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAgent service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateAgent">REST API Reference for CreateAgent Operation</seealso> public virtual Task<CreateAgentResponse> CreateAgentAsync(CreateAgentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateAgentResponseUnmarshaller.Instance; return InvokeAsync<CreateAgentResponse>(request, options, cancellationToken); } #endregion #region CreateLocationEfs /// <summary> /// Creates an endpoint for an Amazon EFS file system. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationEfs service method.</param> /// /// <returns>The response from the CreateLocationEfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationEfs">REST API Reference for CreateLocationEfs Operation</seealso> public virtual CreateLocationEfsResponse CreateLocationEfs(CreateLocationEfsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationEfsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationEfsResponseUnmarshaller.Instance; return Invoke<CreateLocationEfsResponse>(request, options); } /// <summary> /// Creates an endpoint for an Amazon EFS file system. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationEfs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateLocationEfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationEfs">REST API Reference for CreateLocationEfs Operation</seealso> public virtual Task<CreateLocationEfsResponse> CreateLocationEfsAsync(CreateLocationEfsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationEfsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationEfsResponseUnmarshaller.Instance; return InvokeAsync<CreateLocationEfsResponse>(request, options, cancellationToken); } #endregion #region CreateLocationFsxWindows /// <summary> /// Creates an endpoint for an Amazon FSx for Windows file system. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationFsxWindows service method.</param> /// /// <returns>The response from the CreateLocationFsxWindows service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationFsxWindows">REST API Reference for CreateLocationFsxWindows Operation</seealso> public virtual CreateLocationFsxWindowsResponse CreateLocationFsxWindows(CreateLocationFsxWindowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationFsxWindowsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationFsxWindowsResponseUnmarshaller.Instance; return Invoke<CreateLocationFsxWindowsResponse>(request, options); } /// <summary> /// Creates an endpoint for an Amazon FSx for Windows file system. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationFsxWindows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateLocationFsxWindows service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationFsxWindows">REST API Reference for CreateLocationFsxWindows Operation</seealso> public virtual Task<CreateLocationFsxWindowsResponse> CreateLocationFsxWindowsAsync(CreateLocationFsxWindowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationFsxWindowsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationFsxWindowsResponseUnmarshaller.Instance; return InvokeAsync<CreateLocationFsxWindowsResponse>(request, options, cancellationToken); } #endregion #region CreateLocationNfs /// <summary> /// Defines a file system on a Network File System (NFS) server that can be read from /// or written to. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationNfs service method.</param> /// /// <returns>The response from the CreateLocationNfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationNfs">REST API Reference for CreateLocationNfs Operation</seealso> public virtual CreateLocationNfsResponse CreateLocationNfs(CreateLocationNfsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationNfsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationNfsResponseUnmarshaller.Instance; return Invoke<CreateLocationNfsResponse>(request, options); } /// <summary> /// Defines a file system on a Network File System (NFS) server that can be read from /// or written to. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationNfs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateLocationNfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationNfs">REST API Reference for CreateLocationNfs Operation</seealso> public virtual Task<CreateLocationNfsResponse> CreateLocationNfsAsync(CreateLocationNfsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationNfsRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationNfsResponseUnmarshaller.Instance; return InvokeAsync<CreateLocationNfsResponse>(request, options, cancellationToken); } #endregion #region CreateLocationObjectStorage /// <summary> /// Creates an endpoint for a self-managed object storage bucket. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationObjectStorage service method.</param> /// /// <returns>The response from the CreateLocationObjectStorage service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationObjectStorage">REST API Reference for CreateLocationObjectStorage Operation</seealso> public virtual CreateLocationObjectStorageResponse CreateLocationObjectStorage(CreateLocationObjectStorageRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationObjectStorageRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationObjectStorageResponseUnmarshaller.Instance; return Invoke<CreateLocationObjectStorageResponse>(request, options); } /// <summary> /// Creates an endpoint for a self-managed object storage bucket. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationObjectStorage service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateLocationObjectStorage service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationObjectStorage">REST API Reference for CreateLocationObjectStorage Operation</seealso> public virtual Task<CreateLocationObjectStorageResponse> CreateLocationObjectStorageAsync(CreateLocationObjectStorageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationObjectStorageRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationObjectStorageResponseUnmarshaller.Instance; return InvokeAsync<CreateLocationObjectStorageResponse>(request, options, cancellationToken); } #endregion #region CreateLocationS3 /// <summary> /// Creates an endpoint for an Amazon S3 bucket. /// /// /// <para> /// For AWS DataSync to access a destination S3 bucket, it needs an AWS Identity and Access /// Management (IAM) role that has the required permissions. You can set up the required /// permissions by creating an IAM policy that grants the required permissions and attaching /// the policy to the role. An example of such a policy is shown in the examples section. /// </para> /// /// <para> /// For more information, see https://docs.aws.amazon.com/datasync/latest/userguide/working-with-locations.html#create-s3-location /// in the <i>AWS DataSync User Guide.</i> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationS3 service method.</param> /// /// <returns>The response from the CreateLocationS3 service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationS3">REST API Reference for CreateLocationS3 Operation</seealso> public virtual CreateLocationS3Response CreateLocationS3(CreateLocationS3Request request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationS3RequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationS3ResponseUnmarshaller.Instance; return Invoke<CreateLocationS3Response>(request, options); } /// <summary> /// Creates an endpoint for an Amazon S3 bucket. /// /// /// <para> /// For AWS DataSync to access a destination S3 bucket, it needs an AWS Identity and Access /// Management (IAM) role that has the required permissions. You can set up the required /// permissions by creating an IAM policy that grants the required permissions and attaching /// the policy to the role. An example of such a policy is shown in the examples section. /// </para> /// /// <para> /// For more information, see https://docs.aws.amazon.com/datasync/latest/userguide/working-with-locations.html#create-s3-location /// in the <i>AWS DataSync User Guide.</i> /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationS3 service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateLocationS3 service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationS3">REST API Reference for CreateLocationS3 Operation</seealso> public virtual Task<CreateLocationS3Response> CreateLocationS3Async(CreateLocationS3Request request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationS3RequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationS3ResponseUnmarshaller.Instance; return InvokeAsync<CreateLocationS3Response>(request, options, cancellationToken); } #endregion #region CreateLocationSmb /// <summary> /// Defines a file system on a Server Message Block (SMB) server that can be read from /// or written to. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationSmb service method.</param> /// /// <returns>The response from the CreateLocationSmb service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationSmb">REST API Reference for CreateLocationSmb Operation</seealso> public virtual CreateLocationSmbResponse CreateLocationSmb(CreateLocationSmbRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationSmbRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationSmbResponseUnmarshaller.Instance; return Invoke<CreateLocationSmbResponse>(request, options); } /// <summary> /// Defines a file system on a Server Message Block (SMB) server that can be read from /// or written to. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateLocationSmb service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateLocationSmb service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationSmb">REST API Reference for CreateLocationSmb Operation</seealso> public virtual Task<CreateLocationSmbResponse> CreateLocationSmbAsync(CreateLocationSmbRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateLocationSmbRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateLocationSmbResponseUnmarshaller.Instance; return InvokeAsync<CreateLocationSmbResponse>(request, options, cancellationToken); } #endregion #region CreateTask /// <summary> /// Creates a task. A task is a set of two locations (source and destination) and a set /// of Options that you use to control the behavior of a task. If you don't specify Options /// when you create a task, AWS DataSync populates them with service defaults. /// /// /// <para> /// When you create a task, it first enters the CREATING state. During CREATING AWS DataSync /// attempts to mount the on-premises Network File System (NFS) location. The task transitions /// to the AVAILABLE state without waiting for the AWS location to become mounted. If /// required, AWS DataSync mounts the AWS location before each task execution. /// </para> /// /// <para> /// If an agent that is associated with a source (NFS) location goes offline, the task /// transitions to the UNAVAILABLE status. If the status of the task remains in the CREATING /// status for more than a few minutes, it means that your agent might be having trouble /// mounting the source NFS file system. Check the task's ErrorCode and ErrorDetail. Mount /// issues are often caused by either a misconfigured firewall or a mistyped NFS server /// host name. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateTask service method.</param> /// /// <returns>The response from the CreateTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateTask">REST API Reference for CreateTask Operation</seealso> public virtual CreateTaskResponse CreateTask(CreateTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateTaskResponseUnmarshaller.Instance; return Invoke<CreateTaskResponse>(request, options); } /// <summary> /// Creates a task. A task is a set of two locations (source and destination) and a set /// of Options that you use to control the behavior of a task. If you don't specify Options /// when you create a task, AWS DataSync populates them with service defaults. /// /// /// <para> /// When you create a task, it first enters the CREATING state. During CREATING AWS DataSync /// attempts to mount the on-premises Network File System (NFS) location. The task transitions /// to the AVAILABLE state without waiting for the AWS location to become mounted. If /// required, AWS DataSync mounts the AWS location before each task execution. /// </para> /// /// <para> /// If an agent that is associated with a source (NFS) location goes offline, the task /// transitions to the UNAVAILABLE status. If the status of the task remains in the CREATING /// status for more than a few minutes, it means that your agent might be having trouble /// mounting the source NFS file system. Check the task's ErrorCode and ErrorDetail. Mount /// issues are often caused by either a misconfigured firewall or a mistyped NFS server /// host name. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateTask service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateTask">REST API Reference for CreateTask Operation</seealso> public virtual Task<CreateTaskResponse> CreateTaskAsync(CreateTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = CreateTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateTaskResponseUnmarshaller.Instance; return InvokeAsync<CreateTaskResponse>(request, options, cancellationToken); } #endregion #region DeleteAgent /// <summary> /// Deletes an agent. To specify which agent to delete, use the Amazon Resource Name (ARN) /// of the agent in your request. The operation disassociates the agent from your AWS /// account. However, it doesn't delete the agent virtual machine (VM) from your on-premises /// environment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAgent service method.</param> /// /// <returns>The response from the DeleteAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DeleteAgent">REST API Reference for DeleteAgent Operation</seealso> public virtual DeleteAgentResponse DeleteAgent(DeleteAgentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteAgentResponseUnmarshaller.Instance; return Invoke<DeleteAgentResponse>(request, options); } /// <summary> /// Deletes an agent. To specify which agent to delete, use the Amazon Resource Name (ARN) /// of the agent in your request. The operation disassociates the agent from your AWS /// account. However, it doesn't delete the agent virtual machine (VM) from your on-premises /// environment. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteAgent service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DeleteAgent">REST API Reference for DeleteAgent Operation</seealso> public virtual Task<DeleteAgentResponse> DeleteAgentAsync(DeleteAgentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteAgentResponseUnmarshaller.Instance; return InvokeAsync<DeleteAgentResponse>(request, options, cancellationToken); } #endregion #region DeleteLocation /// <summary> /// Deletes the configuration of a location used by AWS DataSync. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteLocation service method.</param> /// /// <returns>The response from the DeleteLocation service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DeleteLocation">REST API Reference for DeleteLocation Operation</seealso> public virtual DeleteLocationResponse DeleteLocation(DeleteLocationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteLocationRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteLocationResponseUnmarshaller.Instance; return Invoke<DeleteLocationResponse>(request, options); } /// <summary> /// Deletes the configuration of a location used by AWS DataSync. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteLocation service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteLocation service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DeleteLocation">REST API Reference for DeleteLocation Operation</seealso> public virtual Task<DeleteLocationResponse> DeleteLocationAsync(DeleteLocationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteLocationRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteLocationResponseUnmarshaller.Instance; return InvokeAsync<DeleteLocationResponse>(request, options, cancellationToken); } #endregion #region DeleteTask /// <summary> /// Deletes a task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteTask service method.</param> /// /// <returns>The response from the DeleteTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DeleteTask">REST API Reference for DeleteTask Operation</seealso> public virtual DeleteTaskResponse DeleteTask(DeleteTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteTaskResponseUnmarshaller.Instance; return Invoke<DeleteTaskResponse>(request, options); } /// <summary> /// Deletes a task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteTask service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DeleteTask">REST API Reference for DeleteTask Operation</seealso> public virtual Task<DeleteTaskResponse> DeleteTaskAsync(DeleteTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteTaskResponseUnmarshaller.Instance; return InvokeAsync<DeleteTaskResponse>(request, options, cancellationToken); } #endregion #region DescribeAgent /// <summary> /// Returns metadata such as the name, the network interfaces, and the status (that is, /// whether the agent is running or not) for an agent. To specify which agent to describe, /// use the Amazon Resource Name (ARN) of the agent in your request. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeAgent service method.</param> /// /// <returns>The response from the DescribeAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeAgent">REST API Reference for DescribeAgent Operation</seealso> public virtual DescribeAgentResponse DescribeAgent(DescribeAgentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeAgentResponseUnmarshaller.Instance; return Invoke<DescribeAgentResponse>(request, options); } /// <summary> /// Returns metadata such as the name, the network interfaces, and the status (that is, /// whether the agent is running or not) for an agent. To specify which agent to describe, /// use the Amazon Resource Name (ARN) of the agent in your request. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeAgent service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeAgent">REST API Reference for DescribeAgent Operation</seealso> public virtual Task<DescribeAgentResponse> DescribeAgentAsync(DescribeAgentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeAgentResponseUnmarshaller.Instance; return InvokeAsync<DescribeAgentResponse>(request, options, cancellationToken); } #endregion #region DescribeLocationEfs /// <summary> /// Returns metadata, such as the path information about an Amazon EFS location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationEfs service method.</param> /// /// <returns>The response from the DescribeLocationEfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationEfs">REST API Reference for DescribeLocationEfs Operation</seealso> public virtual DescribeLocationEfsResponse DescribeLocationEfs(DescribeLocationEfsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationEfsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationEfsResponseUnmarshaller.Instance; return Invoke<DescribeLocationEfsResponse>(request, options); } /// <summary> /// Returns metadata, such as the path information about an Amazon EFS location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationEfs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLocationEfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationEfs">REST API Reference for DescribeLocationEfs Operation</seealso> public virtual Task<DescribeLocationEfsResponse> DescribeLocationEfsAsync(DescribeLocationEfsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationEfsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationEfsResponseUnmarshaller.Instance; return InvokeAsync<DescribeLocationEfsResponse>(request, options, cancellationToken); } #endregion #region DescribeLocationFsxWindows /// <summary> /// Returns metadata, such as the path information about an Amazon FSx for Windows location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationFsxWindows service method.</param> /// /// <returns>The response from the DescribeLocationFsxWindows service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationFsxWindows">REST API Reference for DescribeLocationFsxWindows Operation</seealso> public virtual DescribeLocationFsxWindowsResponse DescribeLocationFsxWindows(DescribeLocationFsxWindowsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationFsxWindowsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationFsxWindowsResponseUnmarshaller.Instance; return Invoke<DescribeLocationFsxWindowsResponse>(request, options); } /// <summary> /// Returns metadata, such as the path information about an Amazon FSx for Windows location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationFsxWindows service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLocationFsxWindows service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationFsxWindows">REST API Reference for DescribeLocationFsxWindows Operation</seealso> public virtual Task<DescribeLocationFsxWindowsResponse> DescribeLocationFsxWindowsAsync(DescribeLocationFsxWindowsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationFsxWindowsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationFsxWindowsResponseUnmarshaller.Instance; return InvokeAsync<DescribeLocationFsxWindowsResponse>(request, options, cancellationToken); } #endregion #region DescribeLocationNfs /// <summary> /// Returns metadata, such as the path information, about an NFS location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationNfs service method.</param> /// /// <returns>The response from the DescribeLocationNfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationNfs">REST API Reference for DescribeLocationNfs Operation</seealso> public virtual DescribeLocationNfsResponse DescribeLocationNfs(DescribeLocationNfsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationNfsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationNfsResponseUnmarshaller.Instance; return Invoke<DescribeLocationNfsResponse>(request, options); } /// <summary> /// Returns metadata, such as the path information, about an NFS location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationNfs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLocationNfs service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationNfs">REST API Reference for DescribeLocationNfs Operation</seealso> public virtual Task<DescribeLocationNfsResponse> DescribeLocationNfsAsync(DescribeLocationNfsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationNfsRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationNfsResponseUnmarshaller.Instance; return InvokeAsync<DescribeLocationNfsResponse>(request, options, cancellationToken); } #endregion #region DescribeLocationObjectStorage /// <summary> /// Returns metadata about a self-managed object storage server location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationObjectStorage service method.</param> /// /// <returns>The response from the DescribeLocationObjectStorage service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationObjectStorage">REST API Reference for DescribeLocationObjectStorage Operation</seealso> public virtual DescribeLocationObjectStorageResponse DescribeLocationObjectStorage(DescribeLocationObjectStorageRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationObjectStorageRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationObjectStorageResponseUnmarshaller.Instance; return Invoke<DescribeLocationObjectStorageResponse>(request, options); } /// <summary> /// Returns metadata about a self-managed object storage server location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationObjectStorage service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLocationObjectStorage service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationObjectStorage">REST API Reference for DescribeLocationObjectStorage Operation</seealso> public virtual Task<DescribeLocationObjectStorageResponse> DescribeLocationObjectStorageAsync(DescribeLocationObjectStorageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationObjectStorageRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationObjectStorageResponseUnmarshaller.Instance; return InvokeAsync<DescribeLocationObjectStorageResponse>(request, options, cancellationToken); } #endregion #region DescribeLocationS3 /// <summary> /// Returns metadata, such as bucket name, about an Amazon S3 bucket location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationS3 service method.</param> /// /// <returns>The response from the DescribeLocationS3 service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationS3">REST API Reference for DescribeLocationS3 Operation</seealso> public virtual DescribeLocationS3Response DescribeLocationS3(DescribeLocationS3Request request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationS3RequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationS3ResponseUnmarshaller.Instance; return Invoke<DescribeLocationS3Response>(request, options); } /// <summary> /// Returns metadata, such as bucket name, about an Amazon S3 bucket location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationS3 service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLocationS3 service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationS3">REST API Reference for DescribeLocationS3 Operation</seealso> public virtual Task<DescribeLocationS3Response> DescribeLocationS3Async(DescribeLocationS3Request request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationS3RequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationS3ResponseUnmarshaller.Instance; return InvokeAsync<DescribeLocationS3Response>(request, options, cancellationToken); } #endregion #region DescribeLocationSmb /// <summary> /// Returns metadata, such as the path and user information about an SMB location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationSmb service method.</param> /// /// <returns>The response from the DescribeLocationSmb service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationSmb">REST API Reference for DescribeLocationSmb Operation</seealso> public virtual DescribeLocationSmbResponse DescribeLocationSmb(DescribeLocationSmbRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationSmbRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationSmbResponseUnmarshaller.Instance; return Invoke<DescribeLocationSmbResponse>(request, options); } /// <summary> /// Returns metadata, such as the path and user information about an SMB location. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLocationSmb service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLocationSmb service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationSmb">REST API Reference for DescribeLocationSmb Operation</seealso> public virtual Task<DescribeLocationSmbResponse> DescribeLocationSmbAsync(DescribeLocationSmbRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeLocationSmbRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeLocationSmbResponseUnmarshaller.Instance; return InvokeAsync<DescribeLocationSmbResponse>(request, options, cancellationToken); } #endregion #region DescribeTask /// <summary> /// Returns metadata about a task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTask service method.</param> /// /// <returns>The response from the DescribeTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeTask">REST API Reference for DescribeTask Operation</seealso> public virtual DescribeTaskResponse DescribeTask(DescribeTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTaskResponseUnmarshaller.Instance; return Invoke<DescribeTaskResponse>(request, options); } /// <summary> /// Returns metadata about a task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTask service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeTask">REST API Reference for DescribeTask Operation</seealso> public virtual Task<DescribeTaskResponse> DescribeTaskAsync(DescribeTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTaskResponseUnmarshaller.Instance; return InvokeAsync<DescribeTaskResponse>(request, options, cancellationToken); } #endregion #region DescribeTaskExecution /// <summary> /// Returns detailed metadata about a task that is being executed. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTaskExecution service method.</param> /// /// <returns>The response from the DescribeTaskExecution service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeTaskExecution">REST API Reference for DescribeTaskExecution Operation</seealso> public virtual DescribeTaskExecutionResponse DescribeTaskExecution(DescribeTaskExecutionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTaskExecutionRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTaskExecutionResponseUnmarshaller.Instance; return Invoke<DescribeTaskExecutionResponse>(request, options); } /// <summary> /// Returns detailed metadata about a task that is being executed. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTaskExecution service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTaskExecution service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeTaskExecution">REST API Reference for DescribeTaskExecution Operation</seealso> public virtual Task<DescribeTaskExecutionResponse> DescribeTaskExecutionAsync(DescribeTaskExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = DescribeTaskExecutionRequestMarshaller.Instance; options.ResponseUnmarshaller = DescribeTaskExecutionResponseUnmarshaller.Instance; return InvokeAsync<DescribeTaskExecutionResponse>(request, options, cancellationToken); } #endregion #region ListAgents /// <summary> /// Returns a list of agents owned by an AWS account in the AWS Region specified in the /// request. The returned list is ordered by agent Amazon Resource Name (ARN). /// /// /// <para> /// By default, this operation returns a maximum of 100 agents. This operation supports /// pagination that enables you to optionally reduce the number of agents returned in /// a response. /// </para> /// /// <para> /// If you have more agents than are returned in a response (that is, the response returns /// only a truncated list of your agents), the response contains a marker that you can /// specify in your next request to fetch the next page of agents. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAgents service method.</param> /// /// <returns>The response from the ListAgents service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListAgents">REST API Reference for ListAgents Operation</seealso> public virtual ListAgentsResponse ListAgents(ListAgentsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListAgentsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListAgentsResponseUnmarshaller.Instance; return Invoke<ListAgentsResponse>(request, options); } /// <summary> /// Returns a list of agents owned by an AWS account in the AWS Region specified in the /// request. The returned list is ordered by agent Amazon Resource Name (ARN). /// /// /// <para> /// By default, this operation returns a maximum of 100 agents. This operation supports /// pagination that enables you to optionally reduce the number of agents returned in /// a response. /// </para> /// /// <para> /// If you have more agents than are returned in a response (that is, the response returns /// only a truncated list of your agents), the response contains a marker that you can /// specify in your next request to fetch the next page of agents. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAgents service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAgents service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListAgents">REST API Reference for ListAgents Operation</seealso> public virtual Task<ListAgentsResponse> ListAgentsAsync(ListAgentsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListAgentsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListAgentsResponseUnmarshaller.Instance; return InvokeAsync<ListAgentsResponse>(request, options, cancellationToken); } #endregion #region ListLocations /// <summary> /// Returns a list of source and destination locations. /// /// /// <para> /// If you have more locations than are returned in a response (that is, the response /// returns only a truncated list of your agents), the response contains a token that /// you can specify in your next request to fetch the next page of locations. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListLocations service method.</param> /// /// <returns>The response from the ListLocations service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListLocations">REST API Reference for ListLocations Operation</seealso> public virtual ListLocationsResponse ListLocations(ListLocationsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListLocationsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListLocationsResponseUnmarshaller.Instance; return Invoke<ListLocationsResponse>(request, options); } /// <summary> /// Returns a list of source and destination locations. /// /// /// <para> /// If you have more locations than are returned in a response (that is, the response /// returns only a truncated list of your agents), the response contains a token that /// you can specify in your next request to fetch the next page of locations. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListLocations service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListLocations service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListLocations">REST API Reference for ListLocations Operation</seealso> public virtual Task<ListLocationsResponse> ListLocationsAsync(ListLocationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListLocationsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListLocationsResponseUnmarshaller.Instance; return InvokeAsync<ListLocationsResponse>(request, options, cancellationToken); } #endregion #region ListTagsForResource /// <summary> /// Returns all the tags associated with a specified resource. /// </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 DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/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> /// Returns all the tags associated with a specified resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTagsForResource service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso> public virtual Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance; return InvokeAsync<ListTagsForResourceResponse>(request, options, cancellationToken); } #endregion #region ListTaskExecutions /// <summary> /// Returns a list of executed tasks. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTaskExecutions service method.</param> /// /// <returns>The response from the ListTaskExecutions service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListTaskExecutions">REST API Reference for ListTaskExecutions Operation</seealso> public virtual ListTaskExecutionsResponse ListTaskExecutions(ListTaskExecutionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTaskExecutionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTaskExecutionsResponseUnmarshaller.Instance; return Invoke<ListTaskExecutionsResponse>(request, options); } /// <summary> /// Returns a list of executed tasks. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTaskExecutions service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTaskExecutions service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListTaskExecutions">REST API Reference for ListTaskExecutions Operation</seealso> public virtual Task<ListTaskExecutionsResponse> ListTaskExecutionsAsync(ListTaskExecutionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTaskExecutionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTaskExecutionsResponseUnmarshaller.Instance; return InvokeAsync<ListTaskExecutionsResponse>(request, options, cancellationToken); } #endregion #region ListTasks /// <summary> /// Returns a list of all the tasks. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTasks service method.</param> /// /// <returns>The response from the ListTasks service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListTasks">REST API Reference for ListTasks Operation</seealso> public virtual ListTasksResponse ListTasks(ListTasksRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListTasksRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTasksResponseUnmarshaller.Instance; return Invoke<ListTasksResponse>(request, options); } /// <summary> /// Returns a list of all the tasks. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTasks service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTasks service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/ListTasks">REST API Reference for ListTasks Operation</seealso> public virtual Task<ListTasksResponse> ListTasksAsync(ListTasksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListTasksRequestMarshaller.Instance; options.ResponseUnmarshaller = ListTasksResponseUnmarshaller.Instance; return InvokeAsync<ListTasksResponse>(request, options, cancellationToken); } #endregion #region StartTaskExecution /// <summary> /// Starts a specific invocation of a task. A <code>TaskExecution</code> value represents /// an individual run of a task. Each task can have at most one <code>TaskExecution</code> /// at a time. /// /// /// <para> /// <code>TaskExecution</code> has the following transition phases: INITIALIZING | PREPARING /// | TRANSFERRING | VERIFYING | SUCCESS/FAILURE. /// </para> /// /// <para> /// For detailed information, see the Task Execution section in the Components and Terminology /// topic in the <i>AWS DataSync User Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartTaskExecution service method.</param> /// /// <returns>The response from the StartTaskExecution service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/StartTaskExecution">REST API Reference for StartTaskExecution Operation</seealso> public virtual StartTaskExecutionResponse StartTaskExecution(StartTaskExecutionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = StartTaskExecutionRequestMarshaller.Instance; options.ResponseUnmarshaller = StartTaskExecutionResponseUnmarshaller.Instance; return Invoke<StartTaskExecutionResponse>(request, options); } /// <summary> /// Starts a specific invocation of a task. A <code>TaskExecution</code> value represents /// an individual run of a task. Each task can have at most one <code>TaskExecution</code> /// at a time. /// /// /// <para> /// <code>TaskExecution</code> has the following transition phases: INITIALIZING | PREPARING /// | TRANSFERRING | VERIFYING | SUCCESS/FAILURE. /// </para> /// /// <para> /// For detailed information, see the Task Execution section in the Components and Terminology /// topic in the <i>AWS DataSync User Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartTaskExecution service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartTaskExecution service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/StartTaskExecution">REST API Reference for StartTaskExecution Operation</seealso> public virtual Task<StartTaskExecutionResponse> StartTaskExecutionAsync(StartTaskExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = StartTaskExecutionRequestMarshaller.Instance; options.ResponseUnmarshaller = StartTaskExecutionResponseUnmarshaller.Instance; return InvokeAsync<StartTaskExecutionResponse>(request, options, cancellationToken); } #endregion #region TagResource /// <summary> /// Applies a key-value pair to an AWS resource. /// </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 DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/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> /// Applies a key-value pair to an AWS resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TagResource service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/TagResource">REST API Reference for TagResource Operation</seealso> public virtual Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return InvokeAsync<TagResourceResponse>(request, options, cancellationToken); } #endregion #region UntagResource /// <summary> /// Removes a tag from an AWS resource. /// </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 DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/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> /// Removes a tag from an AWS resource. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UntagResource service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return InvokeAsync<UntagResourceResponse>(request, options, cancellationToken); } #endregion #region UpdateAgent /// <summary> /// Updates the name of an agent. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAgent service method.</param> /// /// <returns>The response from the UpdateAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/UpdateAgent">REST API Reference for UpdateAgent Operation</seealso> public virtual UpdateAgentResponse UpdateAgent(UpdateAgentRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateAgentResponseUnmarshaller.Instance; return Invoke<UpdateAgentResponse>(request, options); } /// <summary> /// Updates the name of an agent. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateAgent service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateAgent service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/UpdateAgent">REST API Reference for UpdateAgent Operation</seealso> public virtual Task<UpdateAgentResponse> UpdateAgentAsync(UpdateAgentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateAgentRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateAgentResponseUnmarshaller.Instance; return InvokeAsync<UpdateAgentResponse>(request, options, cancellationToken); } #endregion #region UpdateTask /// <summary> /// Updates the metadata associated with a task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateTask service method.</param> /// /// <returns>The response from the UpdateTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/UpdateTask">REST API Reference for UpdateTask Operation</seealso> public virtual UpdateTaskResponse UpdateTask(UpdateTaskRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateTaskResponseUnmarshaller.Instance; return Invoke<UpdateTaskResponse>(request, options); } /// <summary> /// Updates the metadata associated with a task. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateTask service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateTask service method, as returned by DataSync.</returns> /// <exception cref="Amazon.DataSync.Model.InternalException"> /// This exception is thrown when an error occurs in the AWS DataSync service. /// </exception> /// <exception cref="Amazon.DataSync.Model.InvalidRequestException"> /// This exception is thrown when the client submits a malformed request. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/UpdateTask">REST API Reference for UpdateTask Operation</seealso> public virtual Task<UpdateTaskResponse> UpdateTaskAsync(UpdateTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateTaskRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateTaskResponseUnmarshaller.Instance; return InvokeAsync<UpdateTaskResponse>(request, options, cancellationToken); } #endregion } }
54.450777
230
0.67017
[ "Apache-2.0" ]
atpyatt/aws-sdk-net
sdk/src/Services/DataSync/Generated/_bcl45/AmazonDataSyncClient.cs
115,599
C#
using System; using System.Net; using Independentsoft.Exchange; namespace Sample { class Program { static void Main(string[] args) { NetworkCredential credential = new NetworkCredential("username", "password"); Service service = new Service("https://myserver/ews/Exchange.asmx", credential); try { Message message = new Message(); message.Subject = "Test"; message.Body = new Body("Body text"); message.ToRecipients.Add(new Mailbox("John@mydomain.com")); message.CcRecipients.Add(new Mailbox("Mark@mydomain.com")); ItemId itemId = service.CreateItem(message); ItemInfoResponse response = service.CopyItem(itemId, StandardFolder.Inbox); ItemId newItemId = response.Items[0].ItemId; } catch (ServiceRequestException ex) { Console.WriteLine("Error: " + ex.Message); Console.WriteLine("Error: " + ex.XmlMessage); Console.Read(); } catch (WebException ex) { Console.WriteLine("Error: " + ex.Message); Console.Read(); } } } }
30.97619
92
0.532667
[ "MIT" ]
age-killer/Electronic-invoice-document-processing
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/CopyItem/Program.cs
1,301
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Display; using RDotNet; using ESRI.ArcGIS.esriSystem; //spdep, and maptools packages in R are required namespace VisUncertainty { public partial class frmBivariateSignificance : Form { private MainForm m_pForm; private IActiveView m_pActiveView; private clsSnippet m_pSnippet; private BivariateQuandrantSymbols[] m_pQuadrantSymbols; private IFeatureClass m_pFClass; private IFeatureLayer m_pFLayer; public frmBivariateSignificance() { try { InitializeComponent(); m_pForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm; m_pActiveView = m_pForm.axMapControl1.ActiveView; for (int i = 0; i < m_pForm.axMapControl1.LayerCount; i++) { IFeatureLayer pFeatureLayer = (IFeatureLayer)m_pActiveView.FocusMap.get_Layer(i); if (pFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon) //Only polygon to make spatial weight matrix 10/9/15 HK cboTargetLayer.Items.Add(m_pForm.axMapControl1.get_Layer(i).Name); } m_pSnippet = new clsSnippet(); MakingSymbols(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } } private class BivariateQuandrantSymbols { public int R; public int G; public int B; public string Label; public string Value; public double Angle; } private void MakingSymbols() { m_pQuadrantSymbols = new BivariateQuandrantSymbols[5]; for (int i = 0; i < 5; i++) m_pQuadrantSymbols[i] = new BivariateQuandrantSymbols(); m_pQuadrantSymbols[0].R = 228; m_pQuadrantSymbols[0].G = 26; m_pQuadrantSymbols[0].B = 28; m_pQuadrantSymbols[0].Label = "H*=H*"; m_pQuadrantSymbols[0].Value = "High-High"; m_pQuadrantSymbols[0].Angle = 270; m_pQuadrantSymbols[1].R = 152; m_pQuadrantSymbols[1].G = 78; m_pQuadrantSymbols[1].B = 163; m_pQuadrantSymbols[1].Label = "H*=L*"; m_pQuadrantSymbols[1].Value = "High-Low"; m_pQuadrantSymbols[1].Angle = 180; m_pQuadrantSymbols[2].R = 77; m_pQuadrantSymbols[2].G = 175; m_pQuadrantSymbols[2].B = 74; m_pQuadrantSymbols[2].Label = "L*=H*"; m_pQuadrantSymbols[2].Value = "Low-High"; m_pQuadrantSymbols[2].Angle = 0; m_pQuadrantSymbols[3].R = 55; m_pQuadrantSymbols[3].G = 126; m_pQuadrantSymbols[3].B = 184; m_pQuadrantSymbols[3].Label = "L*=L*"; m_pQuadrantSymbols[3].Value = "Low-Low"; m_pQuadrantSymbols[3].Angle = 90; m_pQuadrantSymbols[4].R = 255; m_pQuadrantSymbols[4].G = 255; m_pQuadrantSymbols[4].B = 255; m_pQuadrantSymbols[4].Label = "Not sig.*"; m_pQuadrantSymbols[4].Value = "not sig."; m_pQuadrantSymbols[4].Angle = 0; } private void UpdateMapLables() { if (cboMeasure.Text == "Lee's L") { if (chkDiagZero.Checked) { m_pQuadrantSymbols[0].Label = "H*=H*"; m_pQuadrantSymbols[1].Label = "H*=L*"; m_pQuadrantSymbols[2].Label = "L*=H*"; m_pQuadrantSymbols[3].Label = "L*=L*"; } else { m_pQuadrantSymbols[0].Label = "H0=H0"; m_pQuadrantSymbols[1].Label = "H0=L0"; m_pQuadrantSymbols[2].Label = "L0=H0"; m_pQuadrantSymbols[3].Label = "L0=L0"; } } else if (cboMeasure.Text == "Local Pearson") { m_pQuadrantSymbols[0].Label = "H=H"; m_pQuadrantSymbols[1].Label = "H=L"; m_pQuadrantSymbols[2].Label = "L=H"; m_pQuadrantSymbols[3].Label = "L=L"; } } private void UpdateListview(ListView pListView, IFeatureClass pFeatureClass) { try { pListView.Items.Clear(); pListView.BeginUpdate(); int intNFlds = 1; string[] strFldNames = null; string[] strLvNames = null; string strOutputFldNM = string.Empty; string strOutput = string.Empty; if (cboMeasure.Text == "Lee's L") { if (chkDiagZero.Checked) { strOutput = "Lee's L* Sig"; } else strOutput = "Lee's L0 Sig"; strOutputFldNM = "L_sig"; } else if (cboMeasure.Text == "Local Pearson") { strOutput = "Local Pearson"; strOutputFldNM = "R_sig"; } if (strOutputFldNM == null) return; strFldNames = new string[intNFlds]; strFldNames[0] = strOutputFldNM; strLvNames = new string[intNFlds]; strLvNames[0] = strOutput; string[] strNewNames = UpdateFldNames(strFldNames, pFeatureClass); for (int i = 0; i < intNFlds; i++) { ListViewItem lvi = new ListViewItem(strLvNames[i]); lvi.UseItemStyleForSubItems = false; lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, strNewNames[i])); pListView.Items.Add(lvi); } pListView.EndUpdate(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } } private string[] UpdateFldNames(string[] strFldNMs, IFeatureClass pFeatureClass) { try { int intMax = 0; for (int j = 0; j < strFldNMs.Length; j++) { string strNM = strFldNMs[j]; int i = 1; while (pFeatureClass.FindField(strNM) != -1) { strNM = strFldNMs[j] + "_" + i.ToString(); i++; } if (i > intMax) intMax = i; } string[] strReturnNMs = new string[strFldNMs.Length]; for (int j = 0; j < strFldNMs.Length; j++) { if (intMax == 1) strReturnNMs[j] = strFldNMs[j]; else strReturnNMs[j] = strFldNMs[j] + "_" + (intMax - 1).ToString(); } return strReturnNMs; } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return null; } } private void cboTargetLayer_SelectedIndexChanged(object sender, EventArgs e) { try { string strLayerName = cboTargetLayer.Text; int intLIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strLayerName); ILayer pLayer = m_pForm.axMapControl1.get_Layer(intLIndex); m_pFLayer = pLayer as IFeatureLayer; m_pFClass = m_pFLayer.FeatureClass; IFields fields = m_pFClass.Fields; cboFldnm1.Text = ""; cboFldnm2.Text = ""; cboFldnm1.Items.Clear(); cboFldnm2.Items.Clear(); for (int i = 0; i < fields.FieldCount; i++) { if (m_pSnippet.FindNumberFieldType(fields.get_Field(i))) { cboFldnm1.Items.Add(fields.get_Field(i).Name); cboFldnm2.Items.Add(fields.get_Field(i).Name); } } UpdateListview(lvFields, m_pFClass); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } } private void cboMeasure_SelectedIndexChanged(object sender, EventArgs e) { UpdateListview(lvFields, m_pFClass); UpdateMapLables(); if (cboMeasure.Text == "Local Pearson") { chkDiagZero.Enabled = false; cboMethod.Text = "randomization"; cboMethod.Items.Clear(); cboMethod.Items.Add("randomization"); cboMethod.Items.Add("normality"); } else { chkDiagZero.Enabled = true; cboMethod.Text = "total"; cboMethod.Items.Clear(); cboMethod.Items.Add("total"); cboMethod.Items.Add("conditional"); } } private void chkDiagZero_CheckedChanged(object sender, EventArgs e) { UpdateListview(lvFields, m_pFClass); UpdateMapLables(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnRun_Click(object sender, EventArgs e) { if (cboFldnm1.Text == "" || cboFldnm2.Text == "") { MessageBox.Show("Please select target field"); return; } frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Processing:"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; pfrmProgress.Show(); REngine pEngine = m_pForm.pEngine; int nFeature = m_pFClass.FeatureCount(null); IFeatureCursor pFCursor = m_pFClass.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Get index for independent and dependent variables //Get variable index string strVarNM1 = (string)cboFldnm1.SelectedItem; string strVarNM2 = (string)cboFldnm2.SelectedItem; int intVarIdx1 = m_pFClass.FindField(strVarNM1); int intVarIdx2 = m_pFClass.FindField(strVarNM2); int intFIDIdx = m_pFClass.FindField(m_pFClass.OIDFieldName); //Store Variable at Array double[] arrVar1 = new double[nFeature]; double[] arrVar2 = new double[nFeature]; int[] arrFID = new int[nFeature]; int i = 0; while (pFeature != null) { arrVar1[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx1)); arrVar2[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx2)); arrFID[i] = Convert.ToInt32(pFeature.get_Value(intFIDIdx)); i++; pFeature = pFCursor.NextFeature(); } pFCursor.Flush(); //Plot command for R StringBuilder plotCommmand = new StringBuilder(); string strStartPath = m_pForm.strPath; string pathr = strStartPath.Replace(@"\", @"/"); pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_LARRY.R')"); pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_neighbor.R')"); pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_SASbi.R')"); //Get the file path and name to create spatial weight matrix string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer); if (strNameR == null) return; //Create spatial weight matrix in R pEngine.Evaluate("library(spdep); library(maptools)"); pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); //pEngine.Evaluate("sample.nb <- poly2nb(sample.shp, queen=FALSE)"); pEngine.Evaluate("sample.nb <- poly2nb(sample.shp)"); NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1); pEngine.SetSymbol("sample.v1", vecVar1); NumericVector vecVar2 = pEngine.CreateNumericVector(arrVar2); pEngine.SetSymbol("sample.v2", vecVar2); string strNonZero = null; if (chkDiagZero.Checked) strNonZero = "FALSE"; else strNonZero = "TRUE"; string strSigLv = nudSigLv.Value.ToString(); string[] strSPQuadrants = null; //double[] adblVar1 = null; //double[] adblVar2 = null; //NumericVector vecCoeff = null; if (cboMeasure.Text == "Lee's L") { pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', sig.level=c(" + strSigLv + "), method='" + cboMethod.Text + "', alternative='" + txtAlternative.Text + "', diag.zero = " + strNonZero + ")"); //pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', sig.level=c(" + strSigLv + "), method='total', alternative='two.sided', diag.zero = " + strNonZero + ")"); strSPQuadrants = pEngine.Evaluate("as.character(sample.result[[6]])").AsCharacter().ToArray(); } else if (cboMeasure.Text == "Local Pearson") { pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.pearson(sample.v1, sample.v2, 1:length(sample.nb), sig.level=c(" + strSigLv + ", 0.01), method='" + cboMethod.Text + "', alternative='" + txtAlternative.Text + "')"); //pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.pearson(sample.v1, sample.v2, 1:length(sample.nb), sig.level=c(" + strSigLv + "), method='total', alternative='two.sided')"); strSPQuadrants = pEngine.Evaluate("as.character(sample.result[[6]])").AsCharacter().ToArray(); } //Save Output on SHP //Add Target fields to store results in the shapefile // Keep loop for (int j = 0; j < 1; j++) { string strfldName = lvFields.Items[j].SubItems[1].Text; if (m_pFClass.FindField(strfldName) == -1) { IField newField = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)newField; fieldEdit.Name_2 = strfldName; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; m_pFClass.AddField(newField); } } //Update Field pFCursor = m_pFClass.Update(null, false); pFeature = pFCursor.NextFeature(); string strSpQuadFldName = lvFields.Items[0].SubItems[1].Text; int intSpQuadFldIdx = m_pFClass.FindField(strSpQuadFldName); int featureIdx = 0; while (pFeature != null) { pFeature.set_Value(intSpQuadFldIdx, strSPQuadrants[featureIdx]); pFCursor.UpdateFeature(pFeature); pFeature = pFCursor.NextFeature(); featureIdx++; } pFCursor.Flush(); if (chkMap.Checked) { ITable pTable = (ITable)m_pFClass; IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass(); pUniqueValueRenderer.FieldCount = 1; pUniqueValueRenderer.set_Field(0, strSpQuadFldName); if (cboMaptype.Text == "choropleth map") { ISimpleFillSymbol pSymbol; IQueryFilter pQFilter = new QueryFilterClass(); int intTotalCount = 0; string strLabel = null; for (int j = 0; j < 5; j++) { pSymbol = new SimpleFillSymbolClass(); pSymbol.Style = esriSimpleFillStyle.esriSFSSolid; pSymbol.Color = m_pSnippet.getRGB(m_pQuadrantSymbols[j].R, m_pQuadrantSymbols[j].G, m_pQuadrantSymbols[j].B); pQFilter.WhereClause = strSpQuadFldName + " = '" + m_pQuadrantSymbols[j].Value + "'"; intTotalCount = pTable.RowCount(pQFilter); strLabel = m_pQuadrantSymbols[j].Label + " (" + intTotalCount.ToString() + ")"; pUniqueValueRenderer.AddValue(m_pQuadrantSymbols[j].Value, null, (ISymbol)pSymbol); pUniqueValueRenderer.set_Label(m_pQuadrantSymbols[j].Value, strLabel); } pUniqueValueRenderer.UseDefaultSymbol = false; } else if (cboMaptype.Text == "point map") { ICharacterMarkerSymbol pSymbol; stdole.IFontDisp stdFontCls = ((stdole.IFontDisp)(new stdole.StdFont())); stdFontCls.Name = "ESRI NIMA VMAP1&2 PT"; stdFontCls.Size = 10; IQueryFilter pQFilter = new QueryFilterClass(); int intTotalCount = 0; string strLabel = null; for (int j = 0; j < 4; j++) { ////Without hallo //pSymbol = new CharacterMarkerSymbolClass(); //pSymbol.CharacterIndex = 248; ////pSymbol.Color = m_pSnippet.getRGB(m_pQuadrantSymbols[j].R, m_pQuadrantSymbols[j].G, m_pQuadrantSymbols[j].B); //pSymbol.Size = 10; //pSymbol.Font = stdFontCls; //pSymbol.Angle = m_pQuadrantSymbols[j].Angle; //With hallo pSymbol = new CharacterMarkerSymbolClass(); pSymbol.CharacterIndex = 248; //pSymbol.Color = m_pSnippet.getRGB(m_pQuadrantSymbols[j].R, m_pQuadrantSymbols[j].G, m_pQuadrantSymbols[j].B); pSymbol.Size = 10; pSymbol.Font = stdFontCls; pSymbol.Angle = m_pQuadrantSymbols[j].Angle; //Create a Fill Symbol for the Mask ISimpleFillSymbol smpFill = new SimpleFillSymbol(); smpFill.Color = m_pSnippet.getRGB(0, 0, 0); smpFill.Style = esriSimpleFillStyle.esriSFSSolid; //Create a MultiLayerMarkerSymbol IMultiLayerMarkerSymbol multiLyrMrk = new MultiLayerMarkerSymbol(); //Add the simple marker to the MultiLayer multiLyrMrk.AddLayer(pSymbol); //Create a Mask for the MultiLayerMarkerSymbol IMask mrkMask = (IMask)multiLyrMrk; mrkMask.MaskSymbol = smpFill; mrkMask.MaskStyle = esriMaskStyle.esriMSHalo; mrkMask.MaskSize = 0.5; ///to here pQFilter.WhereClause = strSpQuadFldName + " = '" + m_pQuadrantSymbols[j].Value + "'"; intTotalCount = pTable.RowCount(pQFilter); strLabel = m_pQuadrantSymbols[j].Label + " (" + intTotalCount.ToString() + ")"; pUniqueValueRenderer.AddValue(m_pQuadrantSymbols[j].Value, null, (ISymbol)pSymbol); pUniqueValueRenderer.set_Label(m_pQuadrantSymbols[j].Value, strLabel); } pUniqueValueRenderer.UseDefaultSymbol = false; } IFeatureLayer pNewFLayer = new FeatureLayerClass(); pNewFLayer.FeatureClass = m_pFClass; pNewFLayer.Name = "Bivariate Spatial Significant Quadrant"; IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer; pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer; m_pActiveView.FocusMap.AddLayer(pGFLayer); m_pActiveView.Refresh(); m_pForm.axTOCControl1.Update(); } pfrmProgress.Close(); } } }
40.926499
288
0.526159
[ "MIT" ]
hyeongmokoo/SAAR
VisUncertainty/frmBivariateSignificance.cs
21,161
C#