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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
// *** 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.DataBoxEdge.Latest
{
/// <summary>
/// Compute role.
/// </summary>
public partial class Role : Pulumi.CustomResource
{
/// <summary>
/// Role type.
/// </summary>
[Output("kind")]
public Output<string> Kind { get; private set; } = null!;
/// <summary>
/// The object name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The hierarchical type of the object.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Role resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Role(string name, RoleArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:databoxedge/latest:Role", name, args ?? new RoleArgs(), MakeResourceOptions(options, ""))
{
}
private Role(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:databoxedge/latest:Role", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190301:Role"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190701:Role"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190801:Role"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20200501preview:Role"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Role resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Role Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Role(name, id, options);
}
}
public sealed class RoleArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The device name.
/// </summary>
[Input("deviceName", required: true)]
public Input<string> DeviceName { get; set; } = null!;
/// <summary>
/// Role type.
/// </summary>
[Input("kind", required: true)]
public Input<string> Kind { get; set; } = null!;
/// <summary>
/// The role name.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// The resource group name.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public RoleArgs()
{
}
}
}
| 36.810345 | 123 | 0.573302 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/DataBoxEdge/Latest/Role.cs | 4,270 | C# |
#pragma checksum "D:\KodServer\VisualStudioProjeleri\AwesomeLibrary\AwesomeLibrary\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "922116FA75967B9DCBC3E2EBD93742FB"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Microsoft.Phone.Controls;
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace AwesomeLibrary {
public partial class MainPage : Microsoft.Phone.Controls.PhoneApplicationPage {
internal System.Windows.Controls.Grid LayoutRoot;
internal System.Windows.Controls.StackPanel TitlePanel;
internal System.Windows.Controls.TextBlock lblCategories;
internal System.Windows.Controls.Grid ContentPanel;
internal System.Windows.Controls.ListBox lstCategories;
internal System.Windows.Controls.ScrollViewer svCategories;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/Awesome%20Library;component/MainPage.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
this.TitlePanel = ((System.Windows.Controls.StackPanel)(this.FindName("TitlePanel")));
this.lblCategories = ((System.Windows.Controls.TextBlock)(this.FindName("lblCategories")));
this.ContentPanel = ((System.Windows.Controls.Grid)(this.FindName("ContentPanel")));
this.lstCategories = ((System.Windows.Controls.ListBox)(this.FindName("lstCategories")));
this.svCategories = ((System.Windows.Controls.ScrollViewer)(this.FindName("svCategories")));
}
}
}
| 39.178082 | 174 | 0.663287 | [
"Apache-2.0"
] | coderserdar/AwesomeLibrary | SourceCode/AwesomeLibrary/obj/Debug/MainPage.g.i.cs | 2,862 | 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 cloudformation-2010-05-15.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.CloudFormation.Model
{
/// <summary>
/// This is the response object from the UpdateTerminationProtection operation.
/// </summary>
public partial class UpdateTerminationProtectionResponse : AmazonWebServiceResponse
{
private string _stackId;
/// <summary>
/// Gets and sets the property StackId.
/// <para>
/// The unique ID of the stack.
/// </para>
/// </summary>
public string StackId
{
get { return this._stackId; }
set { this._stackId = value; }
}
// Check to see if StackId property is set
internal bool IsSetStackId()
{
return this._stackId != null;
}
}
} | 29.214286 | 112 | 0.659535 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/CloudFormation/Generated/Model/UpdateTerminationProtectionResponse.cs | 1,636 | C# |
using System;
namespace NullPointer.ManualNullCheck
{
class CallHierarchy
{
public void Run() => A();
void A() => B(null);
void B(string s) => C(s);
void C(string s) => D(s);
void D(string s) => E(s);
void E(string s) => F(s);
void F(string s) => Console.WriteLine(s.Length);
}
}
| 20.647059 | 56 | 0.509972 | [
"Apache-2.0"
] | ufcpp/UfcppSample | Chapters/NullableReferenceTypes/NullPointer/ManualNullCheck/CallHierarchy.cs | 353 | C# |
/*
* MIT License
*Copyright (c) 2021 咖啡与网络(java-and-net)
*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 Sunny.UI;
using SYS.Application;
using SYS.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SYS.FormUI
{
public partial class FrmChangeAdminPwd : UIForm
{
public FrmChangeAdminPwd()
{
InitializeComponent();
}
private void FrmChangeAdminPwd_Load(object sender, EventArgs e)
{
}
private void btnUpdPwd_Click(object sender, EventArgs e)
{
Admin admin = new Admin() { AdminAccount = AdminInfo.Account, AdminPassword = txtNewPwd.Text.Trim() };
bool tf = new AdminService().UpdateNewPwdByOldPwd(admin);
if (tf == false)
{
UIMessageBox.Show("服务器繁忙,修改失败!", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
return;
}
UIMessageBox.Show("修改成功,系统将在稍后退出,请使用新密码进行登录系统!", "系统提示", UIStyle.Green, UIMessageBoxButtons.OK);
FrmBackgroundSystem.closeform();
this.Close();
return;
}
private void txtOldPwd_TextChanged(object sender, EventArgs e)
{
if (txtOldPwd.TextLength < 6)
{
lgCheckOldPwd.Visible = true;
lgCheckOldPwd.OnColor = Color.Red;
}
}
private void txtOldPwd_Validated(object sender, EventArgs e)
{
//校验旧密码是否正确
Admin admin = new Admin() { AdminAccount = AdminInfo.Account, AdminPassword = txtOldPwd.Text.Trim() };
var result = new AdminService().SelectMangerByPass(admin);
if (result != null)
{
lgCheckOldPwd.Visible = true;
lgCheckOldPwd.OnColor = Color.Green;
lblOldMsg.ForeColor = Color.Green;
lblOldMsg.Text = "旧密码符合,请继续填写新密码!";
txtNewPwd.ReadOnly = false;
txtNewPwd.Validated += new EventHandler(txtNewPwd_Validated);
}
else
{
lgCheckOldPwd.Visible = true;
lgCheckOldPwd.OnColor = Color.Red;
lblOldMsg.ForeColor = Color.Red;
lblOldMsg.Text = "旧密码有误,请重试!";
txtNewPwd.ReadOnly = true;
txtNewPwd.Validated -= new EventHandler(txtNewPwd_Validated);
}
}
private void txtNewPwd_Validated(object sender, EventArgs e)
{
string pattern = @"^[A-Za-z0-9]+$";
Regex regex = new Regex(pattern);
if (regex.IsMatch(txtNewPwd.Text.Trim()) && txtNewPwd.TextLength > 8)
{
lblNewMsg.ForeColor = Color.Green;
lblNewMsg.Text = "密码长度及格式符合要求!";
lgCheckNewPwd.Visible = true;
lgCheckNewPwd.OnColor = Color.Green;
return;
}
else
{
lblNewMsg.ForeColor = Color.Red;
lblNewMsg.Text = "密码长度及格式不符合要求,请检查!";
lgCheckNewPwd.Visible = true;
txtNewPwd.Focus();
lgCheckNewPwd.OnColor = Color.Red;
return;
}
}
}
}
| 34.438462 | 114 | 0.605093 | [
"MIT"
] | NF-TopSky-Team/TopskyHotelManagerSystem | SYS.FormUI/AppFunction/FrmChangeAdminPwd.cs | 4,707 | C# |
using Bit.Owin.Contracts;
using Microsoft.AspNetCore.Builder;
using System;
namespace Bit.Owin.Middlewares
{
public class AspNetCoreSingleSignOnClientMiddlewareConfiguration : SingleSignOnClientMiddlewareConfiguration, IAspNetCoreMiddlewareConfiguration
{
public virtual MiddlewarePosition MiddlewarePosition => MiddlewarePosition.BeforeOwinMiddlewares;
public virtual void Configure(IApplicationBuilder aspNetCoreApp)
{
if (aspNetCoreApp == null)
throw new ArgumentNullException(nameof(aspNetCoreApp));
aspNetCoreApp.UseOwinApp(UseJwtBearerAuthentication);
}
}
} | 34.263158 | 148 | 0.751152 | [
"MIT"
] | phan9413/bitframework | src/Server/Bit.Server.Owin/Middlewares/AspNetCoreSingleSignOnClientMiddlewareConfiguration.cs | 653 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <auto-generated>
// Generated using OBeautifulCode.CodeGen.ModelObject (1.0.171.0)
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Database.Domain.Test
{
using global::System;
using global::System.CodeDom.Compiler;
using global::System.Collections.Concurrent;
using global::System.Collections.Generic;
using global::System.Collections.ObjectModel;
using global::System.Diagnostics.CodeAnalysis;
using global::System.Globalization;
using global::System.Linq;
using global::System.Reflection;
using global::FakeItEasy;
using global::OBeautifulCode.Assertion.Recipes;
using global::OBeautifulCode.AutoFakeItEasy;
using global::OBeautifulCode.CodeGen.ModelObject.Recipes;
using global::OBeautifulCode.Equality.Recipes;
using global::OBeautifulCode.Math.Recipes;
using global::OBeautifulCode.Reflection.Recipes;
using global::OBeautifulCode.Representation.System;
using global::OBeautifulCode.Serialization;
using global::OBeautifulCode.Serialization.Recipes;
using global::OBeautifulCode.Type;
using global::Xunit;
using static global::System.FormattableString;
public static partial class PutWithIdAndReturnInternalRecordIdOpTIdTObjectTest
{
private static readonly StringRepresentationTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>> StringRepresentationTestScenarios = new StringRepresentationTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>()
.AddScenario(() =>
new StringRepresentationTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "Default Code Generated Scenario",
SystemUnderTestExpectedStringRepresentationFunc = () =>
{
var systemUnderTest = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new SystemUnderTestExpectedStringRepresentation<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
SystemUnderTest = systemUnderTest,
ExpectedStringRepresentation = Invariant($"Naos.Database.Domain.PutWithIdAndReturnInternalRecordIdOp<Version, Version>: Id = {systemUnderTest.Id?.ToString() ?? "<null>"}, ObjectToPut = {systemUnderTest.ObjectToPut?.ToString() ?? "<null>"}, Tags = {systemUnderTest.Tags?.ToString() ?? "<null>"}, ExistingRecordStrategy = {systemUnderTest.ExistingRecordStrategy.ToString() ?? "<null>"}, RecordRetentionCount = {systemUnderTest.RecordRetentionCount?.ToString(CultureInfo.InvariantCulture) ?? "<null>"}, VersionMatchStrategy = {systemUnderTest.VersionMatchStrategy.ToString() ?? "<null>"}."),
};
return result;
},
});
private static readonly ConstructorArgumentValidationTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>> ConstructorArgumentValidationTestScenarios = new ConstructorArgumentValidationTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>()
.AddScenario(() =>
new ConstructorArgumentValidationTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "constructor should throw ArgumentNullException when parameter 'id' is null scenario",
ConstructionFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
null,
referenceObject.ObjectToPut,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy);
return result;
},
ExpectedExceptionType = typeof(ArgumentNullException),
ExpectedExceptionMessageContains = new[] { "id", },
})
.AddScenario(() =>
new ConstructorArgumentValidationTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "constructor should throw ArgumentNullException when parameter 'objectToPut' is null scenario",
ConstructionFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
null,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy);
return result;
},
ExpectedExceptionType = typeof(ArgumentNullException),
ExpectedExceptionMessageContains = new[] { "objectToPut", },
})
.AddScenario(() =>
new ConstructorArgumentValidationTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "constructor should throw ArgumentNullException when parameter 'tags' is null scenario",
ConstructionFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
null,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy);
return result;
},
ExpectedExceptionType = typeof(ArgumentNullException),
ExpectedExceptionMessageContains = new[] { "tags", },
})
.AddScenario(() =>
new ConstructorArgumentValidationTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "constructor should throw ArgumentException when parameter 'tags' is an empty enumerable scenario",
ConstructionFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
new List<NamedValue<string>>(),
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy);
return result;
},
ExpectedExceptionType = typeof(ArgumentException),
ExpectedExceptionMessageContains = new[] { "tags", "is an empty enumerable", },
})
.AddScenario(() =>
new ConstructorArgumentValidationTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "constructor should throw ArgumentException when parameter 'tags' contains a null element scenario",
ConstructionFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
new NamedValue<string>[0].Concat(referenceObject.Tags).Concat(new NamedValue<string>[] { null }).Concat(referenceObject.Tags).ToList(),
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy);
return result;
},
ExpectedExceptionType = typeof(ArgumentException),
ExpectedExceptionMessageContains = new[] { "tags", "contains at least one null element", },
});
private static readonly ConstructorPropertyAssignmentTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>> ConstructorPropertyAssignmentTestScenarios = new ConstructorPropertyAssignmentTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>()
.AddScenario(() =>
new ConstructorPropertyAssignmentTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "Id should return same 'id' parameter passed to constructor when getting",
SystemUnderTestExpectedPropertyValueFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new SystemUnderTestExpectedPropertyValue<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
SystemUnderTest = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy),
ExpectedPropertyValue = referenceObject.Id,
};
return result;
},
PropertyName = "Id",
})
.AddScenario(() =>
new ConstructorPropertyAssignmentTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "ObjectToPut should return same 'objectToPut' parameter passed to constructor when getting",
SystemUnderTestExpectedPropertyValueFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new SystemUnderTestExpectedPropertyValue<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
SystemUnderTest = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy),
ExpectedPropertyValue = referenceObject.ObjectToPut,
};
return result;
},
PropertyName = "ObjectToPut",
})
.AddScenario(() =>
new ConstructorPropertyAssignmentTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "Tags should return same 'tags' parameter passed to constructor when getting",
SystemUnderTestExpectedPropertyValueFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new SystemUnderTestExpectedPropertyValue<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
SystemUnderTest = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy),
ExpectedPropertyValue = referenceObject.Tags,
};
return result;
},
PropertyName = "Tags",
})
.AddScenario(() =>
new ConstructorPropertyAssignmentTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "ExistingRecordStrategy should return same 'existingRecordStrategy' parameter passed to constructor when getting",
SystemUnderTestExpectedPropertyValueFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new SystemUnderTestExpectedPropertyValue<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
SystemUnderTest = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy),
ExpectedPropertyValue = referenceObject.ExistingRecordStrategy,
};
return result;
},
PropertyName = "ExistingRecordStrategy",
})
.AddScenario(() =>
new ConstructorPropertyAssignmentTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "RecordRetentionCount should return same 'recordRetentionCount' parameter passed to constructor when getting",
SystemUnderTestExpectedPropertyValueFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new SystemUnderTestExpectedPropertyValue<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
SystemUnderTest = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy),
ExpectedPropertyValue = referenceObject.RecordRetentionCount,
};
return result;
},
PropertyName = "RecordRetentionCount",
})
.AddScenario(() =>
new ConstructorPropertyAssignmentTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "VersionMatchStrategy should return same 'versionMatchStrategy' parameter passed to constructor when getting",
SystemUnderTestExpectedPropertyValueFunc = () =>
{
var referenceObject = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var result = new SystemUnderTestExpectedPropertyValue<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
SystemUnderTest = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
referenceObject.Id,
referenceObject.ObjectToPut,
referenceObject.Tags,
referenceObject.ExistingRecordStrategy,
referenceObject.RecordRetentionCount,
referenceObject.VersionMatchStrategy),
ExpectedPropertyValue = referenceObject.VersionMatchStrategy,
};
return result;
},
PropertyName = "VersionMatchStrategy",
});
private static readonly PutWithIdAndReturnInternalRecordIdOp<Version, Version> ReferenceObjectForEquatableTestScenarios = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
private static readonly EquatableTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>> EquatableTestScenarios = new EquatableTestScenarios<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>()
.AddScenario(() =>
new EquatableTestScenario<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>
{
Name = "Default Code Generated Scenario",
ReferenceObject = ReferenceObjectForEquatableTestScenarios,
ObjectsThatAreEqualToButNotTheSameAsReferenceObject = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>[]
{
new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
ReferenceObjectForEquatableTestScenarios.Id,
ReferenceObjectForEquatableTestScenarios.ObjectToPut,
ReferenceObjectForEquatableTestScenarios.Tags,
ReferenceObjectForEquatableTestScenarios.ExistingRecordStrategy,
ReferenceObjectForEquatableTestScenarios.RecordRetentionCount,
ReferenceObjectForEquatableTestScenarios.VersionMatchStrategy),
},
ObjectsThatAreNotEqualToReferenceObject = new PutWithIdAndReturnInternalRecordIdOp<Version, Version>[]
{
new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>().Whose(_ => !_.Id.IsEqualTo(ReferenceObjectForEquatableTestScenarios.Id)).Id,
ReferenceObjectForEquatableTestScenarios.ObjectToPut,
ReferenceObjectForEquatableTestScenarios.Tags,
ReferenceObjectForEquatableTestScenarios.ExistingRecordStrategy,
ReferenceObjectForEquatableTestScenarios.RecordRetentionCount,
ReferenceObjectForEquatableTestScenarios.VersionMatchStrategy),
new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
ReferenceObjectForEquatableTestScenarios.Id,
A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>().Whose(_ => !_.ObjectToPut.IsEqualTo(ReferenceObjectForEquatableTestScenarios.ObjectToPut)).ObjectToPut,
ReferenceObjectForEquatableTestScenarios.Tags,
ReferenceObjectForEquatableTestScenarios.ExistingRecordStrategy,
ReferenceObjectForEquatableTestScenarios.RecordRetentionCount,
ReferenceObjectForEquatableTestScenarios.VersionMatchStrategy),
new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
ReferenceObjectForEquatableTestScenarios.Id,
ReferenceObjectForEquatableTestScenarios.ObjectToPut,
A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>().Whose(_ => !_.Tags.IsEqualTo(ReferenceObjectForEquatableTestScenarios.Tags)).Tags,
ReferenceObjectForEquatableTestScenarios.ExistingRecordStrategy,
ReferenceObjectForEquatableTestScenarios.RecordRetentionCount,
ReferenceObjectForEquatableTestScenarios.VersionMatchStrategy),
new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
ReferenceObjectForEquatableTestScenarios.Id,
ReferenceObjectForEquatableTestScenarios.ObjectToPut,
ReferenceObjectForEquatableTestScenarios.Tags,
A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>().Whose(_ => !_.ExistingRecordStrategy.IsEqualTo(ReferenceObjectForEquatableTestScenarios.ExistingRecordStrategy)).ExistingRecordStrategy,
ReferenceObjectForEquatableTestScenarios.RecordRetentionCount,
ReferenceObjectForEquatableTestScenarios.VersionMatchStrategy),
new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
ReferenceObjectForEquatableTestScenarios.Id,
ReferenceObjectForEquatableTestScenarios.ObjectToPut,
ReferenceObjectForEquatableTestScenarios.Tags,
ReferenceObjectForEquatableTestScenarios.ExistingRecordStrategy,
A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>().Whose(_ => !_.RecordRetentionCount.IsEqualTo(ReferenceObjectForEquatableTestScenarios.RecordRetentionCount)).RecordRetentionCount,
ReferenceObjectForEquatableTestScenarios.VersionMatchStrategy),
new PutWithIdAndReturnInternalRecordIdOp<Version, Version>(
ReferenceObjectForEquatableTestScenarios.Id,
ReferenceObjectForEquatableTestScenarios.ObjectToPut,
ReferenceObjectForEquatableTestScenarios.Tags,
ReferenceObjectForEquatableTestScenarios.ExistingRecordStrategy,
ReferenceObjectForEquatableTestScenarios.RecordRetentionCount,
A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>().Whose(_ => !_.VersionMatchStrategy.IsEqualTo(ReferenceObjectForEquatableTestScenarios.VersionMatchStrategy)).VersionMatchStrategy),
},
ObjectsThatAreNotOfTheSameTypeAsReferenceObject = new object[]
{
A.Dummy<object>(),
A.Dummy<string>(),
A.Dummy<int>(),
A.Dummy<int?>(),
A.Dummy<Guid>(),
A.Dummy<BlockRecordHandlingOp>(),
A.Dummy<CancelBlockedRecordHandlingOp>(),
A.Dummy<CancelHandleRecordExecutionRequestOp>(),
A.Dummy<CancelRunningHandleRecordExecutionOp>(),
A.Dummy<CompleteRunningHandleRecordExecutionOp>(),
A.Dummy<StandardCreateStreamOp>(),
A.Dummy<StandardDeleteStreamOp>(),
A.Dummy<DoesAnyExistByIdOp<Version>>(),
A.Dummy<FailRunningHandleRecordExecutionOp>(),
A.Dummy<GetAllRecordsByIdOp<Version>>(),
A.Dummy<GetAllRecordsMetadataByIdOp<Version>>(),
A.Dummy<GetAllResourceLocatorsOp>(),
A.Dummy<GetHandlingHistoryOfRecordOp>(),
A.Dummy<GetHandlingStatusOfRecordByInternalRecordIdOp>(),
A.Dummy<GetHandlingStatusOfRecordsByIdOp>(),
A.Dummy<GetHandlingStatusOfRecordsByIdOp<Version>>(),
A.Dummy<GetHandlingStatusOfRecordSetByTagOp>(),
A.Dummy<GetLatestObjectByIdOp<Version, Version>>(),
A.Dummy<GetLatestObjectByTagOp<Version>>(),
A.Dummy<GetLatestObjectOp<Version>>(),
A.Dummy<GetLatestRecordByIdOp<Version, Version>>(),
A.Dummy<GetLatestRecordByIdOp<Version>>(),
A.Dummy<GetLatestRecordMetadataByIdOp<Version>>(),
A.Dummy<GetLatestRecordOp<Version>>(),
A.Dummy<GetNextUniqueLongOp>(),
A.Dummy<GetResourceLocatorByIdOp<Version>>(),
A.Dummy<GetResourceLocatorForUniqueIdentifierOp>(),
A.Dummy<GetStreamFromRepresentationOp>(),
A.Dummy<GetStreamFromRepresentationOp<FileStreamRepresentation, MemoryReadWriteStream>>(),
A.Dummy<HandleRecordOp>(),
A.Dummy<HandleRecordOp<Version>>(),
A.Dummy<HandleRecordWithIdOp<Version, Version>>(),
A.Dummy<HandleRecordWithIdOp<Version>>(),
A.Dummy<PruneBeforeInternalRecordDateOp>(),
A.Dummy<PruneBeforeInternalRecordIdOp>(),
A.Dummy<PutAndReturnInternalRecordIdOp<Version>>(),
A.Dummy<PutOp<Version>>(),
A.Dummy<PutWithIdOp<Version, Version>>(),
A.Dummy<RetryFailedHandleRecordExecutionOp>(),
A.Dummy<SelfCancelRunningHandleRecordExecutionOp>(),
A.Dummy<StandardDoesAnyExistByIdOp>(),
A.Dummy<StandardGetAllRecordsByIdOp>(),
A.Dummy<StandardGetAllRecordsMetadataByIdOp>(),
A.Dummy<StandardGetDistinctStringSerializedIdsOp>(),
A.Dummy<StandardGetLatestRecordByIdOp>(),
A.Dummy<StandardGetLatestRecordByTagOp>(),
A.Dummy<StandardGetLatestRecordMetadataByIdOp>(),
A.Dummy<StandardGetLatestRecordOp>(),
A.Dummy<StandardGetNextUniqueLongOp>(),
A.Dummy<StandardGetRecordByInternalRecordIdOp>(),
A.Dummy<StandardPutRecordOp>(),
A.Dummy<ThrowIfResourceUnavailableOp>(),
A.Dummy<StandardTryHandleRecordOp>(),
A.Dummy<TryHandleRecordOp<Version>>(),
A.Dummy<TryHandleRecordWithIdOp<Version, Version>>(),
A.Dummy<TryHandleRecordWithIdOp<Version>>(),
},
});
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Structural
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___Should_implement_IModel_of_PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___When_reflecting()
{
// Arrange
var type = typeof(PutWithIdAndReturnInternalRecordIdOp<Version, Version>);
var expectedModelMethods = typeof(IModel<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>).GetInterfaceDeclaredAndImplementedMethods();
var expectedModelMethodHashes = expectedModelMethods.Select(_ => _.GetSignatureHash());
// Act
var actualInterfaces = type.GetInterfaces();
var actualModelMethods = type.GetMethodsFiltered(MemberRelationships.DeclaredOrInherited, MemberOwners.Instance, MemberAccessModifiers.Public).ToList();
var actualModelMethodHashes = actualModelMethods.Select(_ => _.GetSignatureHash());
// Assert
actualInterfaces.AsTest().Must().ContainElement(typeof(IModel<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>));
expectedModelMethodHashes.Except(actualModelMethodHashes).AsTest().Must().BeEmptyEnumerable();
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___Should_be_attributed_with_Serializable____When_reflecting()
{
// Arrange
var type = typeof(PutWithIdAndReturnInternalRecordIdOp<Version, Version>);
// Act
var actualAttributes = type.GetCustomAttributes(typeof(SerializableAttribute), false);
// Assert
actualAttributes.AsTest().Must().NotBeEmptyEnumerable();
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class StringRepresentation
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void ToString___Should_generate_friendly_string_representation_of_object___When_called()
{
var scenarios = StringRepresentationTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.SystemUnderTest.ToString();
// Assert
actual.AsTest().Must().BeEqualTo(scenario.ExpectedStringRepresentation, because: scenario.Id);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Constructing
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Constructor___Should_throw___When_parameters_are_not_valid()
{
var scenarios = ConstructorArgumentValidationTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = Record.Exception(scenario.ConstructionFunc);
// Assert
actual.AsTest().Must().BeOfType(scenario.ExpectedExceptionType, because: scenario.Id);
foreach(var expected in scenario.ExpectedExceptionMessageContains ?? new List<string>())
{
actual.Message.AsTest().Must().ContainString(expected, because: scenario.Id);
}
if (scenario.ExpectedExceptionMessageEquals != null)
{
actual.Message.AsTest().Must().BeEqualTo(scenario.ExpectedExceptionMessageEquals, because: scenario.Id);
}
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "referenceObject")]
public static void Properties___Should_be_assigned_by_constructor_to_expected_value___When_getting()
{
var scenarios = ConstructorPropertyAssignmentTestScenarios.ValidateAndPrepareForTesting();
var asTestMethodInfo = typeof(WorkflowExtensions).GetMethodFiltered(nameof(WorkflowExtensions.AsTest));
var beEqualToMethodInfo = typeof(Verifications).GetMethodFiltered(nameof(Verifications.BeEqualTo));
foreach (var scenario in scenarios)
{
// Arrange
if ((scenario.PropertyName == ConstructorPropertyAssignmentTestScenario.NoPropertiesAssignedInConstructorScenarioPropertyName) || (scenario.PropertyName == ConstructorPropertyAssignmentTestScenario.ForceGeneratedTestsToPassAndWriteMyOwnScenarioPropertyName))
{
continue;
}
// Act
var actual = scenario.Property.GetValue(scenario.SystemUnderTest);
// Assert
// When the scenario specifies CompareActualToExpectedUsing.DefaultStrategy, ValidateAndPrepareForTesting()
// will check if ExpectedPropertyValue == null. If so, it sets CompareActualToExpectedUsing = ReferenceEquality.
// If not, then it checks the runtime type of ExpectedPropertyValue and if it's a value type,
// then it sets CompareActualToExpectedUsing = ValueEquality, otherwise it uses ValueEquality.
// So a boxed value type is handled properly (using ValueEquality instead of ReferenceEquality).
if (scenario.CompareActualToExpectedUsing == CompareActualToExpectedUsing.ValueEquality)
{
// The below reflection code is used in lieu of the following single line of code
// so that equality is determined based on the property type instead of using
// OBeautifulCode.Equality.Recipes.ObjectEqualityComparer, which will return false
// when the objects being compared have different runtime types. For example, if
// the property type is IReadOnlyCollection<string> and we are comparing an empty array
// an empty List, the assertion below would fail inappropriately.
// actual.AsTest().Must().BeEqualTo(scenario.ExpectedPropertyValue, because: scenario.Id);
var propertyType = scenario.Property.PropertyType;
var asTestMethodInfoToInvoke = asTestMethodInfo.MakeGenericMethod(propertyType);
var assertionTracker = asTestMethodInfoToInvoke.Invoke(null, new[] { actual, Type.Missing });
assertionTracker.Must();
var mustBeEqualToMethodInfoToInvoke = beEqualToMethodInfo.MakeGenericMethod(propertyType);
mustBeEqualToMethodInfoToInvoke.Invoke(null, new[]{ assertionTracker, scenario.ExpectedPropertyValue, scenario.Id, Type.Missing, Type.Missing });
}
else if (scenario.CompareActualToExpectedUsing == CompareActualToExpectedUsing.ReferenceEquality)
{
actual.AsTest().Must().BeSameReferenceAs(scenario.ExpectedPropertyValue, because: scenario.Id);
}
else
{
throw new NotSupportedException("This CompareActualToExpectedUsing is not supported: " + scenario.CompareActualToExpectedUsing);
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Cloning
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Clone___Should_clone_object___When_called()
{
// Arrange
var systemUnderTest = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
// Act
var actual = (PutWithIdAndReturnInternalRecordIdOp<Version, Version>)systemUnderTest.Clone();
// Assert
actual.AsTest().Must().BeEqualTo(systemUnderTest);
actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void DeepClone___Should_deep_clone_object___When_called()
{
// Arrange
var systemUnderTest = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
// Act
var actual = systemUnderTest.DeepClone();
// Assert
actual.AsTest().Must().BeEqualTo(systemUnderTest);
actual.AsTest().Must().NotBeSameReferenceAs(systemUnderTest);
if (systemUnderTest.Id == null)
{
actual.Id.AsTest().Must().BeNull();
}
else if (!actual.Id.GetType().IsValueType)
{
// When the declared type is a reference type, we still have to check the runtime type.
// The object could be a boxed value type, which will fail this asseration because
// a deep clone of a value type object is the same object.
actual.Id.AsTest().Must().NotBeSameReferenceAs(systemUnderTest.Id);
}
if (systemUnderTest.ObjectToPut == null)
{
actual.ObjectToPut.AsTest().Must().BeNull();
}
else if (!actual.ObjectToPut.GetType().IsValueType)
{
// When the declared type is a reference type, we still have to check the runtime type.
// The object could be a boxed value type, which will fail this asseration because
// a deep clone of a value type object is the same object.
actual.ObjectToPut.AsTest().Must().NotBeSameReferenceAs(systemUnderTest.ObjectToPut);
}
if (systemUnderTest.Tags == null)
{
actual.Tags.AsTest().Must().BeNull();
}
else if (!actual.Tags.GetType().IsValueType)
{
// When the declared type is a reference type, we still have to check the runtime type.
// The object could be a boxed value type, which will fail this asseration because
// a deep clone of a value type object is the same object.
actual.Tags.AsTest().Must().NotBeSameReferenceAs(systemUnderTest.Tags);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Serialization
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcBsonSerializer()
{
// Arrange
var expected = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.String };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcBsonSerializer()
{
// Arrange
var expected = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var serializationConfigurationType = SerializationConfigurationTypes.BsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.Binary };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaBsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_string_using_ObcJsonSerializer()
{
// Arrange
var expected = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.String };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Deserialize___Should_roundtrip_object___When_serializing_to_and_deserializing_from_bytes_using_ObcJsonSerializer()
{
// Arrange
var expected = A.Dummy<PutWithIdAndReturnInternalRecordIdOp<Version, Version>>();
var serializationConfigurationType = SerializationConfigurationTypes.JsonSerializationConfigurationType.ConcreteSerializationConfigurationDerivativeType;
var serializationFormats = new[] { SerializationFormat.Binary };
var appDomainScenarios = AppDomainScenarios.RoundtripInCurrentAppDomain | AppDomainScenarios.SerializeInCurrentAppDomainAndDeserializeInNewAppDomain;
// Act, Assert
expected.RoundtripSerializeViaJsonWithBeEqualToAssertion(serializationConfigurationType, serializationFormats, appDomainScenarios);
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Equality
{
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_true___When_both_sides_of_operator_are_null()
{
// Arrange
PutWithIdAndReturnInternalRecordIdOp<Version, Version> systemUnderTest1 = null;
PutWithIdAndReturnInternalRecordIdOp<Version, Version> systemUnderTest2 = null;
// Act
var actual = systemUnderTest1 == systemUnderTest2;
// Assert
actual.AsTest().Must().BeTrue();
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_false___When_one_side_of_operator_is_null_and_the_other_side_is_not_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
PutWithIdAndReturnInternalRecordIdOp<Version, Version> systemUnderTest = null;
// Act
var actual1 = systemUnderTest == scenario.ReferenceObject;
var actual2 = scenario.ReferenceObject == systemUnderTest;
// Assert
actual1.AsTest().Must().BeFalse(because: scenario.Id);
actual2.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_true___When_same_object_is_on_both_sides_of_operator()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
#pragma warning disable CS1718 // Comparison made to same variable
var actual = scenario.ReferenceObject == scenario.ReferenceObject;
#pragma warning restore CS1718 // Comparison made to same variable
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_false___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList();
var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList();
var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void EqualsOperator___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject == _).ToList();
var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ == scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id);
actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_false___When_both_sides_of_operator_are_null()
{
// Arrange
PutWithIdAndReturnInternalRecordIdOp<Version, Version> systemUnderTest1 = null;
PutWithIdAndReturnInternalRecordIdOp<Version, Version> systemUnderTest2 = null;
// Act
var actual = systemUnderTest1 != systemUnderTest2;
// Assert
actual.AsTest().Must().BeFalse();
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_true___When_one_side_of_operator_is_null_and_the_other_side_is_not_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
PutWithIdAndReturnInternalRecordIdOp<Version, Version> systemUnderTest = null;
// Act
var actual1 = systemUnderTest != scenario.ReferenceObject;
var actual2 = scenario.ReferenceObject != systemUnderTest;
// Assert
actual1.AsTest().Must().BeTrue(because: scenario.Id);
actual2.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_false___When_same_object_is_on_both_sides_of_operator()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
#pragma warning disable CS1718 // Comparison made to same variable
var actual = scenario.ReferenceObject != scenario.ReferenceObject;
#pragma warning restore CS1718 // Comparison made to same variable
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_derive_from_the_same_type_but_are_not_of_the_same_type()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList();
var actuals2 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id);
actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_true___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList();
var actuals2 = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeTrue(because: scenario.Id);
actuals2.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void NotEqualsOperator___Should_return_false___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject != _).ToList();
var actuals2 = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _ != scenario.ReferenceObject).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_OperationBase___Should_return_false___When_parameter_other_is_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
OperationBase systemUnderTest = null;
// Act
var actual = scenario.ReferenceObject.Equals((OperationBase)systemUnderTest);
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_OperationBase___Should_return_true___When_parameter_other_is_same_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals((OperationBase)scenario.ReferenceObject);
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_OperationBase___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_OperationBase___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_OperationBase___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((OperationBase)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_ReturningOperationBase_of_Nullable_of_long___Should_return_false___When_parameter_other_is_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
ReturningOperationBase<long?> systemUnderTest = null;
// Act
var actual = scenario.ReferenceObject.Equals((ReturningOperationBase<long?>)systemUnderTest);
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_ReturningOperationBase_of_Nullable_of_long___Should_return_true___When_parameter_other_is_same_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals((ReturningOperationBase<long?>)scenario.ReferenceObject);
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_ReturningOperationBase_of_Nullable_of_long___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<long?>)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_ReturningOperationBase_of_Nullable_of_long___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<long?>)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_ReturningOperationBase_of_Nullable_of_long___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((ReturningOperationBase<long?>)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___Should_return_false___When_parameter_other_is_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange
PutWithIdAndReturnInternalRecordIdOp<Version, Version> systemUnderTest = null;
// Act
var actual = scenario.ReferenceObject.Equals(systemUnderTest);
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___Should_return_true___When_parameter_other_is_same_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals(scenario.ReferenceObject);
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___Should_return_false___When_parameter_other_is_derived_from_the_same_type_but_is_not_of_the_same_type_as_this_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_PutWithIdAndReturnInternalRecordIdOp_of_Version_Version___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals(_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_false___When_parameter_other_is_null()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals((object)null);
// Assert
actual.AsTest().Must().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_false___When_parameter_other_is_not_of_the_same_type()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals1 = scenario.ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
var actuals2 = scenario.ObjectsThatAreNotOfTheSameTypeAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
// Assert
actuals1.AsTest().Must().Each().BeFalse(because: scenario.Id);
actuals2.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_true___When_parameter_other_is_same_object()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actual = scenario.ReferenceObject.Equals((object)scenario.ReferenceObject);
// Assert
actual.AsTest().Must().BeTrue(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_false___When_objects_being_compared_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeFalse(because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void Equals_with_Object___Should_return_true___When_objects_being_compared_have_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => scenario.ReferenceObject.Equals((object)_)).ToList();
// Assert
actuals.AsTest().Must().Each().BeTrue(because: scenario.Id);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class Hashing
{
[Fact(Skip = "It's possible (and even probable after a few runs of this test) that two dummy, unequal models will have the same hash code. The model being tested contains at least one property who's type (or a type nested within the generic type, or a property of the IModel type) is a dictionary with keys that are not comparable or an unordered collection with elements that are not comparable. In these cases the hashing method cannot hash the elements and must resort to hashing the element count. Two dummies could easily have the same element count for such a type.")]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void GetHashCode___Should_not_be_equal_for_two_objects___When_objects_have_different_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var unexpected = scenario.ReferenceObject.GetHashCode();
var actuals = scenario.ObjectsThatAreNotEqualToReferenceObject.Select(_ => _.GetHashCode()).ToList();
// Assert
actuals.AsTest().Must().NotContainElement(unexpected, because: scenario.Id);
}
}
[Fact]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
[SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords")]
[SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1722:IdentifiersShouldNotHaveIncorrectPrefix")]
[SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static void GetHashCode___Should_be_equal_for_two_objects___When_objects_have_the_same_property_values()
{
var scenarios = EquatableTestScenarios.ValidateAndPrepareForTesting();
foreach (var scenario in scenarios)
{
// Arrange, Act
var expected = scenario.ReferenceObject.GetHashCode();
var actuals = scenario.ObjectsThatAreEqualToButNotTheSameAsReferenceObject.Select(_ => _.GetHashCode()).ToList();
// Assert
actuals.AsTest().Must().Each().BeEqualTo(expected, because: scenario.Id);
}
}
}
}
} | 67.715356 | 616 | 0.649479 | [
"MIT"
] | NaosProject/Naos.Database | Naos.Database.Domain.Test/Operations/Stream/External/Write/PutWithIdAndReturnInternalRecordIdOp{TId,TObject}Test.designer.cs | 126,562 | C# |
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Open.RangeTests;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Roslynator", "RCS1196:Call extension method as instance method.")]
public static class RangeExtensionsTests
{
[Fact]
public static void NullParam()
{
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range<int>(null));
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range<int>(null, null));
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range((IEnumerable<int>)null, 0, null));
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range(null, 0));
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range((IEnumerable<int>)null, (Func<int, double>)null));
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range(Enumerable.Empty<int>(), (Func<int, double>)null));
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range(Enumerable.Empty<int>().AsParallel(), null));
Assert.Throws<ArgumentNullException>(
() => RangeExtensions.Range(Enumerable.Empty<int>(), 0, null));
}
[Fact]
public static void MinMax()
{
Enumerable.Range(5, 20)
.Select(e => (double)e)
.Prepend(double.NaN).Prepend(double.NaN)
.Append(double.NaN).Range()
.Equals(Range.Create(5d, 24d))
.Should().BeTrue();
Enumerable.Range(5, 20000)
.Select(e => (double)e)
.Prepend(double.NaN).Prepend(double.NaN)
.Append(double.NaN).AsParallel().Range(e => e)
.Equals(Range.Create(5d, 20004d))
.Should().BeTrue();
Enumerable.Range(5, 20)
.Range(e => (double)e)
.Equals(Range.Create(5d, 24d))
.Should().BeTrue();
Enumerable.Range(5, 20)
.Range(0, e => (double)e)
.Equals(Range.Create(5d, 24d))
.Should().BeTrue();
Assert.Throws<InvalidOperationException>(
() => Enumerable.Empty<int>().Range());
Enumerable.Range(5, 20).Range(0)
.Equals(Range.Create(5, 24))
.Should().BeTrue();
Enumerable.Empty<int>().Range(0)
.Equals(Range.Create(0, 0))
.Should().BeTrue();
}
}
| 29.236111 | 116 | 0.687886 | [
"MIT"
] | Open-NET-Libraries/Open.Range | Open.Range.Tests/RangeExtensionsTests.cs | 2,107 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
#pragma warning disable 1591
namespace Silk.NET.OpenGL
{
public enum PolygonMode
{
Point = 0x1B00,
Line = 0x1B01,
Fill = 0x1B02,
}
}
| 17 | 57 | 0.644118 | [
"MIT"
] | AzyIsCool/Silk.NET | src/OpenGL/Silk.NET.OpenGL/Enums/PolygonMode.gen.cs | 340 | C# |
using Nito.AsyncEx;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Legal;
using WalletWasabi.Logging;
using WalletWasabi.Models;
namespace WalletWasabi.Services
{
public class LegalChecker : IDisposable
{
public const string LegalFolderName = "Legal";
public const string ProvisionalLegalFolderName = "Provisional";
private bool _disposedValue;
public LegalChecker(string dataDir)
{
LegalFolder = Path.Combine(dataDir, LegalFolderName);
ProvisionalLegalFolder = Path.Combine(LegalFolder, ProvisionalLegalFolderName);
}
public event EventHandler<LegalDocuments>? AgreedChanged;
public event EventHandler<LegalDocuments>? ProvisionalChanged;
/// <remarks>Lock object to guard <see cref="CurrentLegalDocument"/> and <see cref="ProvisionalLegalDocument"/> property.</remarks>
private AsyncLock LegalDocumentLock { get; } = new();
private UpdateChecker? UpdateChecker { get; set; }
public string LegalFolder { get; }
public string ProvisionalLegalFolder { get; }
public LegalDocuments? CurrentLegalDocument { get; private set; }
private LegalDocuments? ProvisionalLegalDocument { get; set; }
private TaskCompletionSource<LegalDocuments> LatestDocumentTaskCompletion { get; } = new();
public async Task InitializeAsync(UpdateChecker updateChecker)
{
UpdateChecker = updateChecker;
UpdateChecker.UpdateStatusChanged += UpdateChecker_UpdateStatusChangedAsync;
CurrentLegalDocument = await LegalDocuments.LoadAgreedAsync(LegalFolder).ConfigureAwait(false);
ProvisionalLegalDocument = await LegalDocuments.LoadAgreedAsync(ProvisionalLegalFolder).ConfigureAwait(false);
if (ProvisionalLegalDocument is { } provisional)
{
LatestDocumentTaskCompletion.TrySetResult(provisional);
}
else if (CurrentLegalDocument is { } current)
{
LatestDocumentTaskCompletion.TrySetResult(current);
}
}
public async Task<LegalDocuments> WaitAndGetLatestDocumentAsync()
{
if (TryGetNewLegalDocs(out var provisionalLegal))
{
return provisionalLegal;
}
if (CurrentLegalDocument is { } currentLegal)
{
return currentLegal;
}
return await LatestDocumentTaskCompletion.Task.ConfigureAwait(false);
}
public bool TryGetNewLegalDocs([NotNullWhen(true)] out LegalDocuments? legalDocuments)
{
legalDocuments = null;
if (ProvisionalLegalDocument is { } legal)
{
legalDocuments = legal;
return true;
}
return false;
}
private async void UpdateChecker_UpdateStatusChangedAsync(object? _, UpdateStatus updateStatus)
{
try
{
LegalDocuments? provisionalLegalDocument = null;
using (await LegalDocumentLock.LockAsync().ConfigureAwait(false))
{
// If we don't have it or there is a new one.
if (CurrentLegalDocument is null || CurrentLegalDocument.Version < updateStatus.LegalDocumentsVersion)
{
// UpdateChecker cannot be null as the event called by it.
var content = await UpdateChecker!.WasabiClient.GetLegalDocumentsAsync(CancellationToken.None).ConfigureAwait(false);
// Save it as a provisional legal document.
provisionalLegalDocument = new(updateStatus.LegalDocumentsVersion, content);
await provisionalLegalDocument.ToFileAsync(ProvisionalLegalFolder).ConfigureAwait(false);
ProvisionalLegalDocument = provisionalLegalDocument;
LatestDocumentTaskCompletion.TrySetResult(ProvisionalLegalDocument);
}
}
if (provisionalLegalDocument is { })
{
ProvisionalChanged?.Invoke(this, provisionalLegalDocument);
}
}
catch (Exception ex)
{
Logger.LogError("Could not get legal documents.", ex);
}
}
public async Task AgreeAsync()
{
using (await LegalDocumentLock.LockAsync().ConfigureAwait(false))
{
if (ProvisionalLegalDocument is not { } provisionalLegalDocument || string.IsNullOrEmpty(provisionalLegalDocument.Content))
{
throw new InvalidOperationException("Cannot agree the new legal document.");
}
await provisionalLegalDocument.ToFileAsync(LegalFolder).ConfigureAwait(false);
LegalDocuments.RemoveCandidates(ProvisionalLegalFolder);
CurrentLegalDocument = ProvisionalLegalDocument;
ProvisionalLegalDocument = null;
}
AgreedChanged?.Invoke(this, CurrentLegalDocument);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
if (UpdateChecker is { } updateChecker)
{
updateChecker.UpdateStatusChanged -= UpdateChecker_UpdateStatusChangedAsync;
}
LatestDocumentTaskCompletion.TrySetCanceled();
}
_disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
| 29.95625 | 133 | 0.748383 | [
"MIT"
] | BTCparadigm/WalletWasabi | WalletWasabi/Services/LegalChecker.cs | 4,793 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyChatRoom.Model;
namespace MyChatRoom.Service
{
/// <summary>
/// 直播室房间服务.
/// </summary>
public interface IChatRoomHouseService
{
/// <summary>
/// 取得房间列表.
/// </summary>
/// <returns></returns>
List<ChatRoomHouse> GetChatRoomHouseList();
/// <summary>
/// 取得房间信息.
/// </summary>
/// <param name="houseCode"></param>
/// <returns></returns>
ChatRoomHouse GetChatRoomHouse(string houseCode);
/// <summary>
/// 文字直播室房间列表.
/// </summary>
/// <returns></returns>
List<ChatRoomHouse> GetTextChatRoomHouseList();
/// <summary>
/// 视频直播室房间列表.
/// </summary>
/// <returns></returns>
List<ChatRoomHouse> GetVideoChatRoomHouseList();
}
}
| 17.357143 | 57 | 0.542181 | [
"MIT"
] | wangzhiqing999/my-csharp-project | MyChatRoom.Service/Service/IChatRoomHouseService.cs | 1,048 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
namespace Azure.ResourceManager.Sql.Models
{
/// <summary> Contains the information necessary to perform a resource move (rename). </summary>
public partial class ResourceMoveDefinition
{
/// <summary> Initializes a new instance of ResourceMoveDefinition. </summary>
/// <param name="id"> The target ID for the resource. </param>
/// <exception cref="ArgumentNullException"> <paramref name="id"/> is null. </exception>
public ResourceMoveDefinition(string id)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
Id = id;
}
/// <summary> The target ID for the resource. </summary>
public string Id { get; }
}
}
| 28.875 | 100 | 0.615801 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/ResourceMoveDefinition.cs | 924 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Mvp24Hours.Core.Contract.Infrastructure.Pipe;
using Mvp24Hours.Infrastructure.Pipe;
using ProductAPI.Application.Logic;
using ProductAPI.Core.Contract.Logic;
using ProductAPI.Core.Contract.Pipeline.Builders.Products;
using ProductAPI.MakeUpAPI.Application.Builders.Products;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ProductAPI.WebAPI.Extensions
{
/// <summary>
///
/// </summary>
public static class ServiceBuilderExtensions
{
/// <summary>
///
/// </summary>
public static IServiceCollection AddMyServices(this IServiceCollection services)
{
// product
services.AddScoped<IProductService, ProductService>();
// builder product - pipeline
services.AddScoped<IGetByIdProductBuilder, GetByIdProductBuilder>();
services.AddScoped<IListProductBuilder, ListProductBuilder>();
return services;
}
/// <summary>
///
/// </summary>
public static IServiceCollection AddPipelines(this IServiceCollection services)
{
services.AddTransient<IPipelineAsync, PipelineAsync>();
return services;
}
/// <summary>
///
/// </summary>
public static IServiceCollection AddDocumentation(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Product API", Version = "v1" });
//c.DocumentFilter<CustomSwaggerFilter>();
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n
Enter 'Bearer' [space] and then your token in the text input below.
\r\n\r\nExample: 'Bearer 12345abcdef'",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
return services;
}
}
}
| 35.221053 | 95 | 0.550807 | [
"MIT"
] | kallebelins/mvp24hours-poc-netcore-vue | src/product-api/ProductAPI.WebAPI/Extensions/ServiceBuilderExtensions.cs | 3,348 | C# |
namespace SpellforceDataEditor.special_forms
{
partial class ModCreatorForm
{
/// <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.ButtonFinish = new System.Windows.Forms.Button();
this.PanelInfo = new System.Windows.Forms.Panel();
this.LabelModInfo = new System.Windows.Forms.Label();
this.LabelBytecodeInfo = new System.Windows.Forms.Label();
this.LabelAssetsInfo = new System.Windows.Forms.Label();
this.LabelDataInfo = new System.Windows.Forms.Label();
this.ButtonChooseAssets = new System.Windows.Forms.Button();
this.OpenAssetDirectory = new System.Windows.Forms.FolderBrowserDialog();
this.ButtonInfo = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.StatusBar = new System.Windows.Forms.StatusStrip();
this.StatusText = new System.Windows.Forms.ToolStripStatusLabel();
this.TextBoxFileName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.PanelInfo.SuspendLayout();
this.StatusBar.SuspendLayout();
this.SuspendLayout();
//
// ButtonFinish
//
this.ButtonFinish.Location = new System.Drawing.Point(230, 390);
this.ButtonFinish.Name = "ButtonFinish";
this.ButtonFinish.Size = new System.Drawing.Size(75, 23);
this.ButtonFinish.TabIndex = 1;
this.ButtonFinish.Text = "Create mod";
this.ButtonFinish.UseVisualStyleBackColor = true;
this.ButtonFinish.Click += new System.EventHandler(this.ButtonFinish_Click);
//
// PanelInfo
//
this.PanelInfo.Controls.Add(this.LabelModInfo);
this.PanelInfo.Controls.Add(this.LabelBytecodeInfo);
this.PanelInfo.Controls.Add(this.LabelAssetsInfo);
this.PanelInfo.Controls.Add(this.LabelDataInfo);
this.PanelInfo.Location = new System.Drawing.Point(12, 73);
this.PanelInfo.Name = "PanelInfo";
this.PanelInfo.Size = new System.Drawing.Size(293, 310);
this.PanelInfo.TabIndex = 2;
//
// LabelModInfo
//
this.LabelModInfo.AutoEllipsis = true;
this.LabelModInfo.Location = new System.Drawing.Point(3, 109);
this.LabelModInfo.Name = "LabelModInfo";
this.LabelModInfo.Size = new System.Drawing.Size(287, 176);
this.LabelModInfo.TabIndex = 5;
this.LabelModInfo.Text = "label1";
//
// LabelBytecodeInfo
//
this.LabelBytecodeInfo.AutoSize = true;
this.LabelBytecodeInfo.Location = new System.Drawing.Point(3, 285);
this.LabelBytecodeInfo.Name = "LabelBytecodeInfo";
this.LabelBytecodeInfo.Size = new System.Drawing.Size(35, 13);
this.LabelBytecodeInfo.TabIndex = 4;
this.LabelBytecodeInfo.Text = "label1";
//
// LabelAssetsInfo
//
this.LabelAssetsInfo.AutoSize = true;
this.LabelAssetsInfo.Location = new System.Drawing.Point(3, 58);
this.LabelAssetsInfo.Name = "LabelAssetsInfo";
this.LabelAssetsInfo.Size = new System.Drawing.Size(35, 13);
this.LabelAssetsInfo.TabIndex = 3;
this.LabelAssetsInfo.Text = "label1";
//
// LabelDataInfo
//
this.LabelDataInfo.AutoSize = true;
this.LabelDataInfo.Location = new System.Drawing.Point(3, 9);
this.LabelDataInfo.Name = "LabelDataInfo";
this.LabelDataInfo.Size = new System.Drawing.Size(35, 13);
this.LabelDataInfo.TabIndex = 2;
this.LabelDataInfo.Text = "label1";
//
// ButtonChooseAssets
//
this.ButtonChooseAssets.Location = new System.Drawing.Point(12, 44);
this.ButtonChooseAssets.Name = "ButtonChooseAssets";
this.ButtonChooseAssets.Size = new System.Drawing.Size(130, 23);
this.ButtonChooseAssets.TabIndex = 0;
this.ButtonChooseAssets.Text = "Choose assets directory";
this.ButtonChooseAssets.UseVisualStyleBackColor = true;
this.ButtonChooseAssets.Click += new System.EventHandler(this.ButtonChooseAssets_Click);
//
// ButtonInfo
//
this.ButtonInfo.Location = new System.Drawing.Point(175, 44);
this.ButtonInfo.Name = "ButtonInfo";
this.ButtonInfo.Size = new System.Drawing.Size(130, 23);
this.ButtonInfo.TabIndex = 5;
this.ButtonInfo.Text = "Add mod information";
this.ButtonInfo.UseVisualStyleBackColor = true;
this.ButtonInfo.Click += new System.EventHandler(this.ButtonInfo_Click);
//
// ButtonCancel
//
this.ButtonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.ButtonCancel.Location = new System.Drawing.Point(12, 389);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(75, 23);
this.ButtonCancel.TabIndex = 6;
this.ButtonCancel.Text = "Cancel";
this.ButtonCancel.UseVisualStyleBackColor = true;
//
// StatusBar
//
this.StatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.StatusText});
this.StatusBar.Location = new System.Drawing.Point(0, 421);
this.StatusBar.Name = "StatusBar";
this.StatusBar.Size = new System.Drawing.Size(317, 22);
this.StatusBar.TabIndex = 7;
this.StatusBar.Text = "statusStrip1";
//
// StatusText
//
this.StatusText.Name = "StatusText";
this.StatusText.Size = new System.Drawing.Size(39, 17);
this.StatusText.Text = "Ready";
//
// TextBoxFileName
//
this.TextBoxFileName.Location = new System.Drawing.Point(97, 12);
this.TextBoxFileName.Name = "TextBoxFileName";
this.TextBoxFileName.Size = new System.Drawing.Size(100, 20);
this.TextBoxFileName.TabIndex = 8;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(15, 15);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(76, 13);
this.label1.TabIndex = 9;
this.label1.Text = "Mod file name:";
//
// ModCreatorForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.ButtonCancel;
this.ClientSize = new System.Drawing.Size(317, 443);
this.Controls.Add(this.label1);
this.Controls.Add(this.TextBoxFileName);
this.Controls.Add(this.StatusBar);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.ButtonInfo);
this.Controls.Add(this.ButtonChooseAssets);
this.Controls.Add(this.PanelInfo);
this.Controls.Add(this.ButtonFinish);
this.MaximizeBox = false;
this.Name = "ModCreatorForm";
this.Text = "Mod Creator";
this.PanelInfo.ResumeLayout(false);
this.PanelInfo.PerformLayout();
this.StatusBar.ResumeLayout(false);
this.StatusBar.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button ButtonFinish;
private System.Windows.Forms.Panel PanelInfo;
private System.Windows.Forms.Label LabelBytecodeInfo;
private System.Windows.Forms.Label LabelAssetsInfo;
private System.Windows.Forms.Label LabelDataInfo;
private System.Windows.Forms.Button ButtonChooseAssets;
private System.Windows.Forms.FolderBrowserDialog OpenAssetDirectory;
private System.Windows.Forms.Label LabelModInfo;
private System.Windows.Forms.Button ButtonInfo;
private System.Windows.Forms.Button ButtonCancel;
private System.Windows.Forms.StatusStrip StatusBar;
private System.Windows.Forms.ToolStripStatusLabel StatusText;
private System.Windows.Forms.TextBox TextBoxFileName;
private System.Windows.Forms.Label label1;
}
} | 45.933333 | 107 | 0.595895 | [
"MIT"
] | leszekd25/spellforce_data_editor | SpellforceDataEditor/special forms/ModCreatorForm.Designer.cs | 9,648 | C# |
using System;
namespace RealEstate.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 17.416667 | 70 | 0.665072 | [
"MIT"
] | rzh1999/RealEstateProject | RealEstate/Models/ErrorViewModel.cs | 209 | C# |
using System;
using System.Collections.Generic;
using Machine.Core.Services;
namespace Machine.Utility.ThreadPool
{
public class QueueOfRunnables : ThreadSafeQueue<IRunnable>, IQueue
{
public IScope CreateScope()
{
return new QueueOfRunnablesScope(this);
}
class QueueOfRunnablesScope : IScope
{
readonly QueueOfRunnables _queueOfRunnables;
public QueueOfRunnablesScope(QueueOfRunnables queueOfRunnables)
{
_queueOfRunnables = queueOfRunnables;
}
public IRunnable Dequeue()
{
return _queueOfRunnables.Dequeue();
}
public void Complete()
{
}
public void Dispose()
{
}
}
}
}
| 19.205128 | 70 | 0.618158 | [
"MIT"
] | abombss/machine | Source/Machine.Utility/Machine.Utility.ThreadPool/QueueOfRunnables.cs | 751 | C# |
using System;
using UnityEngine;
using UnityEngine.EventSystems;
public class InitializePotentialDragHandler : MonoBehaviour, IInitializePotentialDragHandler
{
public Action<GameObject, PointerEventData> onInitializePotentialDrag;
public void OnInitializePotentialDrag(PointerEventData eventData)
{
onInitializePotentialDrag?.Invoke(gameObject, eventData);
}
void OnDestroy()
{
onInitializePotentialDrag = null;
}
public static InitializePotentialDragHandler Get(GameObject go)
{
InitializePotentialDragHandler handler = go.GetComponent<InitializePotentialDragHandler>();
if (handler == null) handler = go.AddComponent<InitializePotentialDragHandler>();
return handler;
}
}
| 29.192308 | 99 | 0.750988 | [
"MIT"
] | Eternity714/UGUI.EventHandler | Assets/UGUI.EventSystemHandlers/Scripts/Runtime/InitializePotentialDragHandler.cs | 761 | C# |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace day05
{
class Program
{
static void Main(string[] args)
{
var nonStrings = File.ReadAllLines("input.txt")
.Where(l => !string.IsNullOrWhiteSpace(l))
.Select(l => new NaughtyOrNice { Input = l })
.ToList();
Part1(nonStrings);
Part2(nonStrings);
}
static void Part1(List<NaughtyOrNice> nonStrings)
{
var niceCount = nonStrings.Where(n => n.IsNice).Count();
System.Console.WriteLine($"Part 1: Found {niceCount} nice strings.");
}
static void Part2(List<NaughtyOrNice> nonStrings)
{
var niceCount = nonStrings.Where(n => n.IsNiceToo).Count();
System.Console.WriteLine($"Part 2: Found {niceCount} nice strings.");
}
}
public class NaughtyOrNice
{
public string Input { get; set; }
public bool IsNice => ContainsAtLeastThreeVowels && ContainsRepeatingLetters && !ContainsInvalidStrings;
public bool IsNiceToo => ContainsRepeatingLettersWithSpace && ContainsRepeatingCharacterPair;
public bool ContainsAtLeastThreeVowels
{
get
{
var vowels = "aeiou";
var vowelCount = 0;
foreach (var item in Input)
{
if (vowels.Contains(item)) vowelCount++;
}
return vowelCount >= 3;
}
}
public bool ContainsRepeatingLetters
{
get
{
for (int i = 1; i < Input.Length; i++)
{
if (Input[i] == Input[i - 1]) return true;
}
return false;
}
}
public bool ContainsRepeatingLettersWithSpace
{
get
{
for (int i = 2; i < Input.Length; i++)
{
if (Input[i] == Input[i - 2]) return true;
}
return false;
}
}
public bool ContainsInvalidStrings
{
get
{
bool containsInvalidChars = false;
if (Input.Contains("ab")) containsInvalidChars = true;
if (Input.Contains("cd")) containsInvalidChars = true;
if (Input.Contains("pq")) containsInvalidChars = true;
if (Input.Contains("xy")) containsInvalidChars = true;
return containsInvalidChars;
}
}
public bool ContainsRepeatingCharacterPair
{
get
{
for (int i = 0; i < Input.Length - 2; i++)
{
var test = Input.Substring(i, 2);
if (Input.Replace(test, "..").Count(c => c.Equals('.')) >= 4) return true;
}
return false;
}
}
}
}
| 29.538462 | 112 | 0.477214 | [
"MIT"
] | LittleAndi/advent-of-code-2015 | day05/Program.cs | 3,074 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using ISAAR.MSolve.FEM.Entities;
using ISAAR.MSolve.Geometry.Coordinates;
using ISAAR.MSolve.Numerical.LinearAlgebra;
//TODO: In XFEM I used dictionaries with nodes as keys, but it is less efficient and offers little extra safety, since the
// shape functions and derivatives will be used by classes that have direct access to the nodes.
namespace ISAAR.MSolve.FEM.Interpolation
{
/// <summary>
/// Stores the shape functions, 1st order derivatives with respect to the global cartesian coordinates and the Jacobian
/// of an interpolation, evaluated at a certain natural point of a finite element. These quantities are needed in many
/// places, thus passing an instance of this class is less verbose and error prone.
/// Authors: Serafeim Bakalakos
/// </summary>
public class EvalInterpolation2D
{
private readonly double[] shapeFunctions;
private readonly double[][] shapeGradientsCartesian;
public EvalInterpolation2D(double[] shapeFunctions, double[,] shapeGradientsNatural, Jacobian2D jacobian)
{
int numNodes = shapeFunctions.Length;
if (shapeGradientsNatural.GetLength(0) != numNodes) throw new ArgumentException($"There are {shapeFunctions.Length}"
+ $" evaluated shape functions, but {shapeGradientsNatural.GetLength(0)} evaluated natural shape derivatives.");
this.shapeFunctions = shapeFunctions;
this.shapeGradientsCartesian = new double[numNodes][];
for (int i = 0; i < numNodes; ++i)
{
this.shapeGradientsCartesian[i] = jacobian.TransformNaturalDerivativesToCartesian(
shapeGradientsNatural[i, 0], shapeGradientsNatural[i, 1]);
}
this.Jacobian = jacobian;
}
/// <summary>
/// The inverse Jacobian matrix of the interpolation and its determinant.
/// </summary>
public Jacobian2D Jacobian { get; }
/// <summary>
/// The shape function matrix is 2-by-2n, where n = is the number of shape functions. Row 0 corresponds to dof X, while
/// row 1 to dof Y.
/// </summary>
/// <returns></returns>
public Matrix2D BuildShapeFunctionMatrix()
{
var array2D = new double[2, 2 * shapeFunctions.Length];
for (int i = 0; i < shapeFunctions.Length; ++i)
{
array2D[0, 2 * i] = shapeFunctions[i];
array2D[1, 2 * i + 1] = shapeFunctions[i];
}
return new Matrix2D(array2D);
}
/// <summary>
/// The value of the stored shape function that corresponds to the node with local index <paramref name="nodeIdx"/>.
/// </summary>
/// <param name="nodeIdx">The local index of the node, namely its order among the nodes of the finite element.</param>
/// <returns></returns>
public double GetShapeFunction(int nodeIdx) => shapeFunctions[nodeIdx];
/// <summary>
/// The values of the stored shape function derivatives, with respect to the global cartesian coordinates, that
/// correspond to the node with local index <paramref name="nodeIdx"/>.
/// </summary>
/// <param name="nodeIdx">The local index of the node, namely its order among the nodes of the finite element.</param>
/// <returns></returns>
public IReadOnlyList<double> GetShapeGradientCartesian(int nodeIdx) => shapeGradientsCartesian[nodeIdx];
public CartesianPoint2D TransformPointNaturalToGlobalCartesian(IReadOnlyList<Node2D> nodes)
{
if (nodes.Count != shapeFunctions.Length) throw new ArgumentException(
$"There are {shapeFunctions.Length} evaluated shape functions stored, but {nodes.Count} were passed in.");
double x = 0, y = 0;
for (int i = 0; i < shapeFunctions.Length; ++i)
{
Node2D node = nodes[i];
double val = shapeFunctions[i];
x += val * node.X;
y += val * node.Y;
}
return new CartesianPoint2D(x, y);
}
}
}
| 47.188889 | 128 | 0.629856 | [
"Apache-2.0"
] | SerafeimBakalakos/MSolve | ISAAR.MSolve.FEM/Interpolation/EvalInterpolation2D.cs | 4,249 | C# |
namespace Maverick.PCF.Builder.Forms
{
partial class ShowPreviewImage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ShowPreviewImage));
this.gboxPreviewImage = new System.Windows.Forms.GroupBox();
this.pnlTypes = new System.Windows.Forms.Panel();
this.lblTypes = new System.Windows.Forms.Label();
this.btnChangePreviewImage = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.pboxPreviewImage = new System.Windows.Forms.PictureBox();
this.label3 = new System.Windows.Forms.Label();
this.lblDescription = new System.Windows.Forms.Label();
this.lblDisplayName = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.ofdPreviewImage = new System.Windows.Forms.OpenFileDialog();
this.gboxPreviewImage.SuspendLayout();
this.pnlTypes.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pboxPreviewImage)).BeginInit();
this.SuspendLayout();
//
// gboxPreviewImage
//
this.gboxPreviewImage.Controls.Add(this.pnlTypes);
this.gboxPreviewImage.Controls.Add(this.btnChangePreviewImage);
this.gboxPreviewImage.Controls.Add(this.label2);
this.gboxPreviewImage.Controls.Add(this.pboxPreviewImage);
this.gboxPreviewImage.Controls.Add(this.label3);
this.gboxPreviewImage.Controls.Add(this.lblDescription);
this.gboxPreviewImage.Controls.Add(this.lblDisplayName);
this.gboxPreviewImage.Controls.Add(this.label7);
this.gboxPreviewImage.Location = new System.Drawing.Point(12, 12);
this.gboxPreviewImage.Name = "gboxPreviewImage";
this.gboxPreviewImage.Size = new System.Drawing.Size(531, 263);
this.gboxPreviewImage.TabIndex = 7;
this.gboxPreviewImage.TabStop = false;
this.gboxPreviewImage.Text = "Preview Image";
//
// pnlTypes
//
this.pnlTypes.AutoScroll = true;
this.pnlTypes.Controls.Add(this.lblTypes);
this.pnlTypes.Location = new System.Drawing.Point(79, 83);
this.pnlTypes.Name = "pnlTypes";
this.pnlTypes.Size = new System.Drawing.Size(206, 68);
this.pnlTypes.TabIndex = 8;
//
// lblTypes
//
this.lblTypes.Dock = System.Windows.Forms.DockStyle.Fill;
this.lblTypes.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTypes.Location = new System.Drawing.Point(0, 0);
this.lblTypes.Name = "lblTypes";
this.lblTypes.Size = new System.Drawing.Size(206, 68);
this.lblTypes.TabIndex = 4;
this.lblTypes.Text = "-";
//
// btnChangePreviewImage
//
this.btnChangePreviewImage.Location = new System.Drawing.Point(368, 200);
this.btnChangePreviewImage.Name = "btnChangePreviewImage";
this.btnChangePreviewImage.Size = new System.Drawing.Size(57, 23);
this.btnChangePreviewImage.TabIndex = 7;
this.btnChangePreviewImage.Text = "Update";
this.btnChangePreviewImage.UseVisualStyleBackColor = true;
this.btnChangePreviewImage.Click += new System.EventHandler(this.btnChangePreviewImage_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Calibri", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(9, 22);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(468, 17);
this.label2.TabIndex = 1;
this.label2.Text = "This is how your control will display on the \"Add Control\" page in Model-driven a" +
"pp";
//
// pboxPreviewImage
//
this.pboxPreviewImage.Image = ((System.Drawing.Image)(resources.GetObject("pboxPreviewImage.Image")));
this.pboxPreviewImage.Location = new System.Drawing.Point(310, 59);
this.pboxPreviewImage.Name = "pboxPreviewImage";
this.pboxPreviewImage.Size = new System.Drawing.Size(170, 130);
this.pboxPreviewImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pboxPreviewImage.TabIndex = 6;
this.pboxPreviewImage.TabStop = false;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.Firebrick;
this.label3.Location = new System.Drawing.Point(9, 235);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(192, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Preview Image needs to be 17:13 ratio.";
//
// lblDescription
//
this.lblDescription.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblDescription.Location = new System.Drawing.Point(9, 161);
this.lblDescription.Name = "lblDescription";
this.lblDescription.Size = new System.Drawing.Size(276, 62);
this.lblDescription.TabIndex = 5;
this.lblDescription.Text = "-";
//
// lblDisplayName
//
this.lblDisplayName.AutoSize = true;
this.lblDisplayName.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblDisplayName.Location = new System.Drawing.Point(9, 59);
this.lblDisplayName.Name = "lblDisplayName";
this.lblDisplayName.Size = new System.Drawing.Size(40, 15);
this.lblDisplayName.TabIndex = 2;
this.lblDisplayName.Text = "label2";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(9, 83);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(39, 15);
this.label7.TabIndex = 3;
this.label7.Text = "Types:";
//
// ofdPreviewImage
//
this.ofdPreviewImage.Filter = "Image files|*.png;*.jpg;*.jpeg;*gif";
this.ofdPreviewImage.Title = "Select new Preview Image";
//
// ShowPreviewImage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(556, 287);
this.Controls.Add(this.gboxPreviewImage);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "ShowPreviewImage";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "Preview Control";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ShowPreviewImage_FormClosing);
this.gboxPreviewImage.ResumeLayout(false);
this.gboxPreviewImage.PerformLayout();
this.pnlTypes.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pboxPreviewImage)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox gboxPreviewImage;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.PictureBox pboxPreviewImage;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lblDescription;
private System.Windows.Forms.Label lblDisplayName;
private System.Windows.Forms.Label lblTypes;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Button btnChangePreviewImage;
private System.Windows.Forms.OpenFileDialog ofdPreviewImage;
private System.Windows.Forms.Panel pnlTypes;
}
} | 50.80829 | 168 | 0.613502 | [
"MIT"
] | Danz-maveRICK/PCF-CustomControlBuilder | Maverick.PCF.Builder/Forms/ShowPreviewImage.Designer.cs | 9,808 | C# |
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslynator.CSharp.Analysis.UseMethodChaining;
using Roslynator.CSharp.Syntax;
namespace Roslynator.CSharp.Refactorings
{
internal static class UseMethodChainingRefactoring
{
public static async Task<Document> RefactorAsync(
Document document,
UseMethodChainingAnalysis analysis,
ExpressionStatementSyntax expressionStatement,
CancellationToken cancellationToken)
{
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
InvocationExpressionSyntax invocationExpression = GetInvocationExpression(expressionStatement);
SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(invocationExpression);
ITypeSymbol returnType = semanticModel.GetMethodSymbol(invocationExpression, cancellationToken).ReturnType;
string name = ((IdentifierNameSyntax)UseMethodChainingAnalysis.WalkDownMethodChain(invocationInfo).Expression).Identifier.ValueText;
StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(expressionStatement);
SyntaxList<StatementSyntax> statements = statementsInfo.Statements;
int index = statements.IndexOf(expressionStatement);
string indentation = SyntaxTriviaAnalysis.GetIncreasedIndentation(expressionStatement, cancellationToken);
var sb = new StringBuilder(invocationExpression.ToString());
int j = index;
while (j < statements.Count - 1)
{
StatementSyntax statement = statements[j + 1];
if (!analysis.IsFixableStatement(statement, name, returnType, semanticModel, cancellationToken))
break;
sb.AppendLine();
sb.Append(indentation);
sb.Append(GetTextToAppend((ExpressionStatementSyntax)statement));
j++;
}
StatementSyntax lastStatement = statements[j];
SyntaxList<StatementSyntax> newStatements = statements;
while (j > index)
{
newStatements = newStatements.RemoveAt(j);
j--;
}
ExpressionSyntax newInvocationExpression = SyntaxFactory.ParseExpression(sb.ToString());
SyntaxTriviaList trailingTrivia = statementsInfo
.Parent
.DescendantTrivia(TextSpan.FromBounds(invocationExpression.Span.End, lastStatement.Span.End))
.ToSyntaxTriviaList()
.EmptyIfWhitespace()
.AddRange(lastStatement.GetTrailingTrivia());
ExpressionStatementSyntax newExpressionStatement = expressionStatement
.ReplaceNode(invocationExpression, newInvocationExpression)
.WithLeadingTrivia(expressionStatement.GetLeadingTrivia())
.WithTrailingTrivia(trailingTrivia)
.WithFormatterAndSimplifierAnnotation();
newStatements = newStatements.ReplaceAt(index, newExpressionStatement);
return await document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken).ConfigureAwait(false);
}
private static string GetTextToAppend(ExpressionStatementSyntax expressionStatement)
{
SimpleMemberInvocationExpressionInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationExpressionInfo(GetInvocationExpression(expressionStatement));
SimpleMemberInvocationExpressionInfo firstMemberInvocation = UseMethodChainingAnalysis.WalkDownMethodChain(invocationInfo);
InvocationExpressionSyntax invocationExpression = invocationInfo.InvocationExpression;
return invocationExpression
.ToString()
.Substring(firstMemberInvocation.OperatorToken.SpanStart - invocationExpression.SpanStart);
}
private static InvocationExpressionSyntax GetInvocationExpression(ExpressionStatementSyntax expressionStatement)
{
ExpressionSyntax expression = expressionStatement.Expression;
if (expression is InvocationExpressionSyntax invocationExpression)
{
return invocationExpression;
}
else
{
return SyntaxInfo.SimpleAssignmentExpressionInfo(expression).Right as InvocationExpressionSyntax;
}
}
}
} | 42.4 | 160 | 0.697703 | [
"Apache-2.0"
] | onexey/Roslynator | src/Workspaces.Common/CSharp/Refactorings/UseMethodChainingRefactoring.cs | 4,878 | 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("libcrdebug")]
[assembly: AssemblyDescription("Managed Chrome Remote Debugging interface")]
[assembly: AssemblyProduct("libcrdebug")]
[assembly: AssemblyCopyright("Copyright © Katelyn Gadd 2019")]
// 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("03fbdd16-d68f-4786-8c51-9a2d076f1a01")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 42.565217 | 84 | 0.782431 | [
"MIT"
] | sq/libcrdebug | Properties/AssemblyInfo.cs | 982 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace DotNetForce.Common.Models.Json
{
public class ErrorResult
{
[JsonProperty(PropertyName = "statusCode")]
public string? StatusCode { get; set; }
[JsonProperty(PropertyName = "message")]
public string? Message { get; set; }
[JsonProperty(PropertyName = "fields")]
public IList<string>? Fields { get; set; }
}
}
| 24.444444 | 51 | 0.643182 | [
"MIT"
] | ste80/DotNetForce | DotNetForce/Common/Models/Json/ErrorResult.cs | 442 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Nv
{
[Serializable]
[NvItemId(1310)]
[Attributes(9)]
public class PcsTxCalChan
{
[ElementsCount(16)]
[ElementType("uint16")]
[Description("")]
public ushort[] Value { get; set; }
}
}
| 19.47619 | 44 | 0.596577 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Nv/PcsTxCalChanI.cs | 409 | C# |
using System.Collections.ObjectModel;
namespace Pacman.Core.TiledMap
{
public sealed class Rectangle : IObject
{
public string Name { get; }
public string Type { get; }
public float X { get; }
public float Y { get; }
public float Height { get; }
public float Width { get; }
public ReadOnlyCollection<Property> Properties { get; }
public Rectangle(string name, string type, float x, float y, float width, float height)
: this(name, type, x, y, width, height, new())
{
}
public Rectangle(string name, string type, float x, float y, float width, float height, List<Property> properties)
{
Name = name;
Type = type;
X = x;
Y = y;
Height = height;
Width = width;
Properties = new(new List<Property>(properties));
}
}
}
| 28.484848 | 122 | 0.543617 | [
"MIT"
] | ripwin/Pacman | src/Pacman.Core/TiledMap/Rectangle.cs | 942 | C# |
namespace GUIConvertor
{
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.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
| 28.375 | 107 | 0.556828 | [
"MIT"
] | mkpetrov/Home-Work | Simple Calculations/GUIConvertor/Form1.Designer.cs | 1,137 | C# |
// Copyright © 2020 EPAM Systems, Inc. All Rights Reserved. All information contained herein is, and remains the
// property of EPAM Systems, Inc. and/or its suppliers and is protected by international intellectual
// property law. Dissemination of this information or reproduction of this material is strictly forbidden,
// unless prior written permission is obtained from EPAM Systems, Inc
using System;
using System.Linq.Expressions;
using Epam.GraphQL.Builders.Common;
using Epam.GraphQL.Configuration;
using Epam.GraphQL.Configuration.Implementations.Fields.ChildFields;
using Epam.GraphQL.Loaders;
namespace Epam.GraphQL.Builders.Loader.Implementations
{
internal class FromLoaderInlineObjectBuilder<TEntity, TChildLoader, TChildEntity, TResult, TExecutionContext> : IFromLoaderInlineObjectBuilder<TEntity, TChildEntity, TResult>
where TChildLoader : Loader<TChildEntity, TExecutionContext>, new()
where TEntity : class
where TChildEntity : class
{
internal FromLoaderInlineObjectBuilder(RelationRegistry<TExecutionContext> registry, EnumerableField<TEntity, TResult, TExecutionContext> field)
{
Registry = registry ?? throw new ArgumentNullException(nameof(registry));
Field = field;
}
protected EnumerableField<TEntity, TResult, TExecutionContext> Field { get; private set; }
protected RelationRegistry<TExecutionContext> Registry { get; }
public IFromLoaderInlineObjectBuilder<TEntity, TChildEntity, T> Select<T>(Expression<Func<TResult, T>> selector)
{
return new FromLoaderInlineObjectBuilder<TEntity, TChildLoader, TChildEntity, T, TExecutionContext>(Registry, Field.ApplySelect(selector));
}
public IFromLoaderInlineObjectBuilder<TEntity, TChildEntity, T> Select<T>(Expression<Func<TEntity, TResult, T>> selector)
{
return new FromLoaderInlineObjectBuilder<TEntity, TChildLoader, TChildEntity, T, TExecutionContext>(Registry, Field.ApplySelect(selector));
}
public virtual void SingleOrDefault(Expression<Func<TResult, bool>> predicate)
{
Field.ApplySingleOrDefault(predicate);
}
public virtual void FirstOrDefault(Expression<Func<TResult, bool>> predicate)
{
Field.ApplyFirstOrDefault(predicate);
}
public IFromLoaderInlineObjectBuilder<TEntity, TChildEntity, TResult> Where(Expression<Func<TResult, bool>> predicate)
{
Field = Field.ApplyWhere(predicate);
return this;
}
}
}
| 45.473684 | 178 | 0.726466 | [
"MIT"
] | epam/epam-graphql | src/Epam.GraphQL/Builders/Loader/Implementations/FromLoaderInlineObjectBuilder.cs | 2,595 | C# |
// This file describes the API that the generator will produce
//
// Authors:
// Geoff Norton
// Miguel de Icaza
// Aaron Bockover
//
// Copyright 2009, Novell, Inc.
// Copyright 2011, 2013, 2015 Xamarin Inc.
//
using ObjCRuntime;
using Foundation;
using CloudKit;
using CoreGraphics;
using CoreLocation;
#if !MONOMAC
using UIKit;
#endif
#if !TVOS
using Contacts;
#endif
using System;
namespace CoreLocation {
[NoTV][NoWatch]
[iOS (7,0)]
[Native] // NSInteger -> CLRegion.h
public enum CLRegionState : long {
Unknown,
Inside,
Outside
}
#if XAMCORE_4_0 // Unavailable on macOS
[NoMac]
#endif
[NoTV][NoWatch]
[iOS (7,0)]
[Native] // NSInteger -> CLRegion.h
public enum CLProximity : long {
Unknown,
Immediate,
Near,
Far
}
[ErrorDomain ("CLLocationPushServiceErrorDomain")]
[iOS (15,0), TV (15,0), MacCatalyst (15,0), Mac (12,0), Watch (8,0)]
[Native]
public enum CLLocationPushServiceError : long {
Unknown = 0,
MissingPushExtension = 1,
MissingPushServerEnvironment = 2,
MissingEntitlement = 3,
}
[NoTV]
[Watch (6,0)]
[BaseType (typeof (NSObject))]
[DisableDefaultCtor] // will crash, see CoreLocation.cs for compatibility stubs
partial interface CLHeading : NSSecureCoding, NSCopying {
[Export ("magneticHeading")]
double MagneticHeading { get; }
[Export ("trueHeading")]
double TrueHeading { get; }
[Export ("headingAccuracy")]
double HeadingAccuracy { get; }
[Export ("x")]
double X { get; }
[Export ("y")]
double Y { get; }
[Export ("z")]
double Z { get; }
[Export ("timestamp", ArgumentSemantic.Copy)]
NSDate Timestamp { get; }
}
[BaseType (typeof (NSObject))]
partial interface CLLocation : NSSecureCoding, NSCopying, CKRecordValue {
[Export ("coordinate")]
CLLocationCoordinate2D Coordinate { get; }
[Export ("altitude")]
double Altitude { get; }
[Export ("horizontalAccuracy")]
double HorizontalAccuracy { get; }
[Export ("verticalAccuracy")]
double VerticalAccuracy { get; }
[TV (13,0)] // API_UNAVAILABLE(tvos) removed in Xcode 11 beta 1
[Watch (3,0)] // __WATCHOS_PROHIBITED removed in Xcode 8 beta 3
[Export ("course")]
double Course { get; }
[Watch (6,2), TV (13,4), Mac (10,15,4), iOS (13,4)]
[Export ("courseAccuracy")]
double CourseAccuracy { get; }
[TV (13,0)] // API_UNAVAILABLE(tvos) removed in Xcode 11 beta 1
[Watch (3,0)] // __WATCHOS_PROHIBITED removed in Xcode 8 beta 3
[Export ("speed")]
double Speed { get; }
[Watch (6,2), TV (13,4), Mac (10,15,4), iOS (13,4)]
[Export ("speedAccuracy")]
double SpeedAccuracy { get; }
[Export ("timestamp", ArgumentSemantic.Copy)]
NSDate Timestamp { get; }
[Export ("initWithLatitude:longitude:")]
IntPtr Constructor (double latitude, double longitude);
[Export ("initWithCoordinate:altitude:horizontalAccuracy:verticalAccuracy:timestamp:")]
IntPtr Constructor (CLLocationCoordinate2D coordinate, double altitude, double hAccuracy, double vAccuracy, NSDate timestamp);
[Export ("distanceFromLocation:")]
double DistanceFrom (CLLocation location);
[Export ("initWithCoordinate:altitude:horizontalAccuracy:verticalAccuracy:course:speed:timestamp:")]
IntPtr Constructor (CLLocationCoordinate2D coordinate, double altitude, double hAccuracy, double vAccuracy, double course, double speed, NSDate timestamp);
[Watch (6,2), TV (13,4), Mac (10,15,4), iOS (13,4)]
[Export ("initWithCoordinate:altitude:horizontalAccuracy:verticalAccuracy:course:courseAccuracy:speed:speedAccuracy:timestamp:")]
IntPtr Constructor (CLLocationCoordinate2D coordinate, double altitude, double hAccuracy, double vAccuracy, double course, double courseAccuracy, double speed, double speedAccuracy, NSDate timestamp);
[Watch (8,0), TV (15,0), Mac (12,0), iOS (15,0), MacCatalyst (15,0)]
[Export ("initWithCoordinate:altitude:horizontalAccuracy:verticalAccuracy:course:courseAccuracy:speed:speedAccuracy:timestamp:sourceInfo:")]
IntPtr Constructor (CLLocationCoordinate2D coordinate, double altitude, double horizontalAccuracy, double verticalAccuracy, double course, double courseAccuracy, double speed, double speedAccuracy, NSDate timestamp, CLLocationSourceInformation sourceInfo);
// Apple keep changing the 'introduction' of this field (5.0->8.0->5.0) but it was not available in 6.1
// nor in 7.0 - but it works on my iPad3 running iOS 7.1
[NoTV][NoWatch]
[iOS (7,1)]
[Field ("kCLErrorUserInfoAlternateRegionKey")]
NSString ErrorUserInfoAlternateRegionKey { get; }
[Field ("kCLLocationAccuracyBestForNavigation")]
double AccurracyBestForNavigation { get; }
[Field ("kCLLocationAccuracyBest")]
double AccuracyBest { get; }
[Field ("kCLLocationAccuracyNearestTenMeters")]
double AccuracyNearestTenMeters { get; }
[Field ("kCLLocationAccuracyHundredMeters")]
double AccuracyHundredMeters { get; }
[Field ("kCLLocationAccuracyKilometer")]
double AccuracyKilometer { get; }
[Field ("kCLLocationAccuracyThreeKilometers")]
double AccuracyThreeKilometers { get; }
[Watch (7, 0), TV (14, 0), Mac (11, 0), iOS (14, 0)]
[MacCatalyst (14,0)]
[Field ("kCLLocationAccuracyReduced")]
double AccuracyReduced { get; }
[Mac (10,15)]
[iOS (8,0)]
[NullAllowed, Export ("floor", ArgumentSemantic.Copy)]
CLFloor Floor { get; }
[Watch (8,0), TV (15,0), Mac (12,0), iOS (15,0), MacCatalyst (15,0)]
[Export ("ellipsoidalAltitude")]
double EllipsoidalAltitude { get; }
[Watch (8,0), TV (15,0), Mac (12,0), iOS (15,0), MacCatalyst (15,0)]
[NullAllowed, Export ("sourceInformation")]
CLLocationSourceInformation SourceInformation { get; }
}
[Mac (10,15)]
[iOS (8,0)]
[BaseType (typeof(NSObject))]
partial interface CLFloor : NSSecureCoding, NSCopying {
[Export ("level")]
nint Level { get; }
}
[BaseType (typeof (NSObject), Delegates=new string [] {"WeakDelegate"}, Events=new Type [] {typeof (CLLocationManagerDelegate)})]
partial interface CLLocationManager {
[Wrap ("WeakDelegate")]
[Protocolize]
CLLocationManagerDelegate Delegate { get; set; }
[Export ("delegate", ArgumentSemantic.Assign)][NullAllowed]
NSObject WeakDelegate { get; set; }
[Export ("distanceFilter", ArgumentSemantic.Assign)]
double DistanceFilter { get; set; }
[Export ("desiredAccuracy", ArgumentSemantic.Assign)]
double DesiredAccuracy { get; set; }
[NullAllowed, Export ("location", ArgumentSemantic.Copy)]
CLLocation Location { get; }
// __WATCHOS_PROHIBITED removed in Xcode 8.0 beta 2, assuming it's valid for 3.0+
[Watch (3,0)]
[NoTV]
[Export ("startUpdatingLocation")]
void StartUpdatingLocation ();
[Export ("stopUpdatingLocation")]
void StopUpdatingLocation ();
[Export ("locationServicesEnabled"), Static]
bool LocationServicesEnabled { get; }
[NoTV]
[Watch (6,0), Mac (11,0)]
[Export ("headingFilter", ArgumentSemantic.Assign)]
double HeadingFilter { get; set; }
[NoTV]
[Watch (6,0), Mac (11,0)]
[Export ("startUpdatingHeading")]
void StartUpdatingHeading ();
[NoTV]
[Watch (6,0), Mac (11,0)]
[Export ("stopUpdatingHeading")]
void StopUpdatingHeading ();
[NoTV]
[Watch (6,0), Mac (11,0)]
[Export ("dismissHeadingCalibrationDisplay")]
void DismissHeadingCalibrationDisplay ();
[NoWatch][NoTV]
[Availability (Deprecated = Platform.iOS_6_0)]
[Deprecated (PlatformName.MacOSX, 11, 0, message : "Set the purpose using the NSLocationUsageDescription key in the Info.plist instead.")]
// Default property value is null but it cannot be set to that value
// it crash when a null is provided
[NullAllowed, Export ("purpose")]
string Purpose { get; set; }
[NoTV][Mac (11,0)]
[Watch (6,0)]
[Export ("headingAvailable"), Static]
bool HeadingAvailable { get; }
[NoWatch][NoTV]
[Export ("significantLocationChangeMonitoringAvailable"), Static]
bool SignificantLocationChangeMonitoringAvailable { get; }
[NoWatch][NoTV]
[Deprecated (PlatformName.iOS, 7, 0, message : "Use 'IsMonitoringAvailable' instead.")]
[Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'IsMonitoringAvailable' instead.")]
[Export ("regionMonitoringAvailable"), Static]
bool RegionMonitoringAvailable { get; }
[NoWatch][NoTV]
[Deprecated (PlatformName.iOS, 6, 0, message : "Use 'IsMonitoringAvailable' and 'AuthorizationStatus' instead.")]
[Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'IsMonitoringAvailable' and 'AuthorizationStatus' instead.")]
[Export ("regionMonitoringEnabled"), Static]
bool RegionMonitoringEnabled { get; }
[NoTV]
[Watch (6,0), Mac (11,0)]
[Export ("headingOrientation", ArgumentSemantic.Assign)]
CLDeviceOrientation HeadingOrientation { get; set; }
[NoTV]
[Watch (6,0), Mac (11,0)]
[NullAllowed, Export ("heading", ArgumentSemantic.Copy)]
CLHeading Heading { get; }
[NoWatch][NoTV]
[Export ("maximumRegionMonitoringDistance")]
double MaximumRegionMonitoringDistance { get; }
[NoWatch][NoTV]
[Export ("monitoredRegions", ArgumentSemantic.Copy)]
NSSet MonitoredRegions { get; }
[NoWatch][NoTV]
[Export ("startMonitoringSignificantLocationChanges")]
void StartMonitoringSignificantLocationChanges ();
[NoWatch][NoTV]
[Export ("stopMonitoringSignificantLocationChanges")]
void StopMonitoringSignificantLocationChanges ();
[NoWatch][NoTV][NoMac]
[Availability (Deprecated = Platform.iOS_6_0)]
[Export ("startMonitoringForRegion:desiredAccuracy:")]
void StartMonitoring (CLRegion region, double desiredAccuracy);
[NoWatch][NoTV]
[Export ("stopMonitoringForRegion:")]
void StopMonitoring (CLRegion region);
[Watch (7, 0), TV (14, 0), Mac (11, 0), iOS (14, 0)]
[MacCatalyst (14,0)]
[Export ("authorizationStatus")]
CLAuthorizationStatus AuthorizationStatus { get; }
[Deprecated (PlatformName.iOS, 14, 0, message: "Use the instance property 'AuthorizationStatus' instead.")]
[Deprecated (PlatformName.MacOSX, 11, 0, message: "Use the instance 'AuthorizationStatus' property instead.")]
[Deprecated (PlatformName.TvOS, 14, 0, message: "Use the instance property AuthorizationStatus' instead.")]
[Deprecated (PlatformName.WatchOS, 7, 0, message: "Use instance property 'AuthorizationStatus' instead.")]
[Export ("authorizationStatus")][Static]
CLAuthorizationStatus Status { get; }
[NoWatch][NoTV]
[Export ("startMonitoringForRegion:")]
void StartMonitoring (CLRegion region);
[NoTV]
[Watch (4,0), Mac (11,0)]
[Export ("activityType", ArgumentSemantic.Assign)]
CLActivityType ActivityType { get; set; }
[NoWatch][NoTV][Mac (11,0)]
[Export ("pausesLocationUpdatesAutomatically", ArgumentSemantic.Assign)]
bool PausesLocationUpdatesAutomatically { get; set; }
[NoWatch][NoTV][NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Not used anymore. Call will not have any effect.")]
[Unavailable (PlatformName.MacCatalyst)][Advice ("This API is not available when using UIKit on macOS.")]
[Export ("allowDeferredLocationUpdatesUntilTraveled:timeout:")]
void AllowDeferredLocationUpdatesUntil (double distance, double timeout);
[NoWatch][NoTV][NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Not used anymore. Call will not have any effect.")]
[Unavailable (PlatformName.MacCatalyst)][Advice ("This API is not available when using UIKit on macOS.")]
[Export ("disallowDeferredLocationUpdates")]
void DisallowDeferredLocationUpdates ();
[NoWatch][NoTV]
[Mac (10,9)]
[Deprecated (PlatformName.iOS, 13,0, message: "Not used anymore. It will always return 'false'.")]
[Deprecated (PlatformName.MacOSX, 10,15, message: "Not used anymore. It will always return 'false'.")]
[Static]
[Export ("deferredLocationUpdatesAvailable")]
bool DeferredLocationUpdatesAvailable { get; }
[Mac (10,14)]
[Field ("CLTimeIntervalMax")]
double MaxTimeInterval { get; }
[NoWatch][NoTV]
[Mac (10,10)]
[iOS (7,0), Static, Export ("isMonitoringAvailableForClass:")]
bool IsMonitoringAvailable (Class regionClass);
[NoWatch][NoTV][NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use 'RangedBeaconConstraints' instead.")]
[iOS (7,0), Export ("rangedRegions", ArgumentSemantic.Copy)]
NSSet RangedRegions { get; }
[NoWatch, NoTV, Mac (11,0), iOS (13,0)]
[Export ("rangedBeaconConstraints", ArgumentSemantic.Copy)]
NSSet<CLBeaconIdentityConstraint> RangedBeaconConstraints { get; }
[Mac (10,10)]
[NoWatch][NoTV]
[iOS (7,0), Export ("requestStateForRegion:")]
void RequestState (CLRegion region);
[NoWatch][NoTV][NoMac]
[Unavailable (PlatformName.MacCatalyst)][Advice ("This API is not available when using UIKit on macOS.")]
[Deprecated (PlatformName.iOS, 13,0, message: "Use 'StartRangingBeacons(CLBeaconIdentityConstraint)' instead.")]
[iOS (7,0), Export ("startRangingBeaconsInRegion:")]
void StartRangingBeacons (CLBeaconRegion region);
[NoWatch, NoTV, Mac (11,0), iOS (13,0)]
[Export ("startRangingBeaconsSatisfyingConstraint:")]
void StartRangingBeacons (CLBeaconIdentityConstraint constraint);
[NoWatch][NoTV][NoMac]
[Unavailable (PlatformName.MacCatalyst)][Advice ("This API is not available when using UIKit on macOS.")]
[Deprecated (PlatformName.iOS, 13,0, message: "Use 'StopRangingBeacons(CLBeaconIdentityConstraint)' instead.")]
[iOS (7,0), Export ("stopRangingBeaconsInRegion:")]
void StopRangingBeacons (CLBeaconRegion region);
[NoWatch, NoTV, Mac (11,0), iOS (13,0)]
[Export ("stopRangingBeaconsSatisfyingConstraint:")]
void StopRangingBeacons (CLBeaconIdentityConstraint constraint);
[NoWatch][NoTV]
[iOS (7,0), Mac (11,0)]
[Static]
[Export ("isRangingAvailable")]
bool IsRangingAvailable { get; }
[iOS (8,0), Mac (11,0)]
[Export ("requestWhenInUseAuthorization")]
void RequestWhenInUseAuthorization ();
[NoTV]
[iOS (8,0)]
[Mac (10,15)]
[Export ("requestAlwaysAuthorization")]
void RequestAlwaysAuthorization ();
[NoWatch][NoTV]
[iOS (8,0), Mac (11,0)]
[Export ("startMonitoringVisits")]
void StartMonitoringVisits ();
[NoWatch][NoTV]
[iOS (8,0), Mac (11,0)]
[Export ("stopMonitoringVisits")]
void StopMonitoringVisits ();
[NoTV]
[iOS (9,0), Watch (4,0), Mac (11,0)]
[Export ("allowsBackgroundLocationUpdates")]
bool AllowsBackgroundLocationUpdates { get; set; }
[NoWatch, NoTV, Mac (11,0), iOS (11,0)]
[Export ("showsBackgroundLocationIndicator")]
bool ShowsBackgroundLocationIndicator { get; set; }
[iOS (9,0)]
[Mac (10,14)]
[Export ("requestLocation")]
void RequestLocation ();
[Watch (7, 0), TV (14, 0), Mac (11, 0), iOS (14, 0)]
[MacCatalyst (14,0)]
[Export ("accuracyAuthorization")]
CLAccuracyAuthorization AccuracyAuthorization { get; }
[Async]
[Watch (7, 0), TV (14, 0), Mac (11, 0), iOS (14, 0)]
[MacCatalyst (14,0)]
[Export ("requestTemporaryFullAccuracyAuthorizationWithPurposeKey:completion:")]
void RequestTemporaryFullAccuracyAuthorization (string purposeKey, [NullAllowed] Action<NSError> completion);
[Watch (7, 0), TV (14, 0), Mac (11, 0), iOS (14, 0)]
[MacCatalyst (14,0)]
[Export ("requestTemporaryFullAccuracyAuthorizationWithPurposeKey:")]
void RequestTemporaryFullAccuracyAuthorization (string purposeKey);
[NoWatch, NoTV, Mac (11, 0), iOS (14, 0)]
[MacCatalyst (14,0)]
[Export ("authorizedForWidgetUpdates")]
bool IsAuthorizedForWidgetUpdates { [Bind ("isAuthorizedForWidgetUpdates")] get; }
[Async]
[NoWatch, NoTV, NoMac, NoMacCatalyst]
[iOS (15,0)]
[Export ("startMonitoringLocationPushesWithCompletion:")]
void StartMonitoringLocationPushes ([NullAllowed] Action<NSData, NSError> completion);
[NoWatch, NoTV, NoMac, NoMacCatalyst]
[iOS (15,0)]
[Export ("stopMonitoringLocationPushes")]
void StopMonitoringLocationPushes ();
}
[BaseType (typeof (NSObject))]
[Model]
[Protocol]
partial interface CLLocationManagerDelegate
{
[NoWatch][NoTV]
[Availability (Deprecated = Platform.iOS_6_0)]
[Export ("locationManager:didUpdateToLocation:fromLocation:"), EventArgs ("CLLocationUpdated")]
void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation);
[NoTV]
[Watch (6,0), Mac (11,0)]
[Export ("locationManager:didUpdateHeading:"), EventArgs ("CLHeadingUpdated")]
void UpdatedHeading (CLLocationManager manager, CLHeading newHeading);
#if XAMCORE_4_0 // Unavailable on macOS
[NoMac]
#endif
[NoTV]
[Watch (6,0)]
[Export ("locationManagerShouldDisplayHeadingCalibration:"), DelegateName ("CLLocationManagerEventArgs"), DefaultValue (true)]
bool ShouldDisplayHeadingCalibration (CLLocationManager manager);
[Export ("locationManager:didFailWithError:"), EventArgs ("NSError", true)]
void Failed (CLLocationManager manager, NSError error);
[NoWatch][NoTV]
[Export ("locationManager:didEnterRegion:"), EventArgs ("CLRegion")]
void RegionEntered (CLLocationManager manager, CLRegion region);
[NoWatch][NoTV]
[Export ("locationManager:didExitRegion:"), EventArgs ("CLRegion")]
void RegionLeft (CLLocationManager manager, CLRegion region);
[NoWatch][NoTV]
[Export ("locationManager:monitoringDidFailForRegion:withError:"), EventArgs ("CLRegionError")]
void MonitoringFailed (CLLocationManager manager, [NullAllowed] CLRegion region, NSError error);
[NoWatch][NoTV]
[Export ("locationManager:didStartMonitoringForRegion:"), EventArgs ("CLRegion")]
void DidStartMonitoringForRegion (CLLocationManager manager, CLRegion region);
[NoWatch][NoTV]
[Mac (10,10)]
[iOS (7,0), Export ("locationManager:didDetermineState:forRegion:"), EventArgs ("CLRegionStateDetermined")]
void DidDetermineState (CLLocationManager manager, CLRegionState state, CLRegion region);
[NoWatch][NoTV][NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use 'DidRangeBeaconsSatisfyingConstraint' instead.")]
[iOS (7,0), Export ("locationManager:didRangeBeacons:inRegion:"), EventArgs ("CLRegionBeaconsRanged")]
void DidRangeBeacons (CLLocationManager manager, CLBeacon [] beacons, CLBeaconRegion region);
[NoWatch, NoTV, Mac (11,0), iOS (13,0)]
[Export ("locationManager:didRangeBeacons:satisfyingConstraint:")]
[EventArgs ("CLRegionBeaconsConstraintRanged")]
void DidRangeBeaconsSatisfyingConstraint (CLLocationManager manager, CLBeacon[] beacons, CLBeaconIdentityConstraint beaconConstraint);
[NoWatch][NoTV][NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use 'DidFailRangingBeacons' instead.")]
[iOS (7,0), Export ("locationManager:rangingBeaconsDidFailForRegion:withError:"), EventArgs ("CLRegionBeaconsFailed")]
void RangingBeaconsDidFailForRegion (CLLocationManager manager, CLBeaconRegion region, NSError error);
[NoWatch, NoTV, Mac (11,0), iOS (13,0)]
[Export ("locationManager:didFailRangingBeaconsForConstraint:error:")]
[EventArgs ("CLRegionBeaconsConstraintFailed")]
void DidFailRangingBeacons (CLLocationManager manager, CLBeaconIdentityConstraint beaconConstraint, NSError error);
[NoWatch][NoTV]
[iOS (8,0), Mac (11,0)]
[Export ("locationManager:didVisit:"), EventArgs ("CLVisited")]
void DidVisit (CLLocationManager manager, CLVisit visit);
[Deprecated (PlatformName.iOS, 14, 0, message: "Use 'DidChangeAuthorization' instead.")]
[Deprecated (PlatformName.MacOSX, 11, 0, message: "Use 'DidChangeAuthorization' instead.")]
[Deprecated (PlatformName.TvOS, 14, 0, message: "Use 'DidChangeAuthorization' instead.")]
[Deprecated (PlatformName.WatchOS, 7, 0, message: "Use 'DidChangeAuthorization' instead.")]
[Export ("locationManager:didChangeAuthorizationStatus:"), EventArgs ("CLAuthorizationChanged")]
void AuthorizationChanged (CLLocationManager manager, CLAuthorizationStatus status);
[Export ("locationManager:didUpdateLocations:"), EventArgs ("CLLocationsUpdated")]
void LocationsUpdated (CLLocationManager manager, CLLocation[] locations);
#if XAMCORE_4_0 // Unavailable on macOS
[NoMac]
#endif
[NoWatch][NoTV]
[Export ("locationManagerDidPauseLocationUpdates:"), EventArgs ("")]
void LocationUpdatesPaused (CLLocationManager manager);
#if XAMCORE_4_0 // Unavailable on macOS
[NoMac]
#endif
[NoWatch][NoTV]
[Export ("locationManagerDidResumeLocationUpdates:"), EventArgs ("")]
void LocationUpdatesResumed (CLLocationManager manager);
[NoWatch][NoTV]
[Export ("locationManager:didFinishDeferredUpdatesWithError:"), EventArgs ("NSError", true)]
void DeferredUpdatesFinished (CLLocationManager manager, [NullAllowed] NSError error);
[Watch (7, 0), TV (14, 0), Mac (11, 0), iOS (14, 0)]
[Export ("locationManagerDidChangeAuthorization:")]
void DidChangeAuthorization (CLLocationManager manager);
}
[Static]
partial interface CLLocationDistance {
[Mac (10,14)]
[Field ("CLLocationDistanceMax")]
double MaxDistance { get; }
[Field ("kCLDistanceFilterNone")]
double FilterNone { get; }
}
[BaseType (typeof (NSObject))]
[DisableDefaultCtor] // will crash, see CoreLocation.cs for compatibility stubs
partial interface CLRegion : NSSecureCoding, NSCopying {
[NoTV]
[Deprecated (PlatformName.iOS, 7, 0, message : "Use 'CLCircularRegion' instead.")]
[Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'CLCircularRegion' instead.")]
[Export ("center")]
CLLocationCoordinate2D Center { get; }
[NoTV]
[Deprecated (PlatformName.iOS, 7, 0, message : "Use 'CLCircularRegion' instead.")]
[Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'CLCircularRegion' instead.")]
[Export ("radius")]
double Radius { get; }
[Export ("identifier")]
string Identifier { get; }
[NoTV]
[Deprecated (PlatformName.iOS, 7, 0, message : "Use 'CLCircularRegion' instead.")]
[Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'CLCircularRegion' instead.")]
[Export ("initCircularRegionWithCenter:radius:identifier:")]
IntPtr Constructor (CLLocationCoordinate2D center, double radius, string identifier);
[NoTV]
[Deprecated (PlatformName.iOS, 7, 0, message : "Use 'CLCircularRegion' instead.")]
[Deprecated (PlatformName.MacOSX, 10, 10, message : "Use 'CLCircularRegion' instead.")]
[Export ("containsCoordinate:")]
bool Contains (CLLocationCoordinate2D coordinate);
[iOS (7,0), Export ("notifyOnEntry", ArgumentSemantic.Assign)]
[Mac (10,10)]
bool NotifyOnEntry { get; set; }
[iOS (7,0), Export ("notifyOnExit", ArgumentSemantic.Assign)]
[Mac (10,10)]
bool NotifyOnExit { get; set; }
}
[BaseType (typeof (NSObject))]
[DisableDefaultCtor] // will crash, see CoreLocation.cs for compatibility stubs
interface CLPlacemark : NSSecureCoding, NSCopying {
[Deprecated (PlatformName.WatchOS, 4, 0, message: "Use 'CLPlacemark' properties to access data.")]
[Deprecated (PlatformName.iOS, 11, 0, message: "Use 'CLPlacemark' properties to access data.")]
[Deprecated (PlatformName.MacOSX, 10, 13, message: "Use 'CLPlacemark' properties to access data.")]
[NullAllowed, Export("addressDictionary", ArgumentSemantic.Copy)]
NSDictionary AddressDictionary { get; }
[NullAllowed, Export("administrativeArea")]
string AdministrativeArea { get; }
[NullAllowed, Export("subAdministrativeArea")]
string SubAdministrativeArea { get; }
[NullAllowed, Export("subLocality")]
string SubLocality { get; }
[NullAllowed, Export("locality")]
string Locality { get; }
[NullAllowed, Export("country")]
string Country { get; }
[NullAllowed, Export("postalCode")]
string PostalCode { get; }
[NullAllowed, Export("thoroughfare")]
string Thoroughfare { get; }
[NullAllowed, Export("subThoroughfare")]
string SubThoroughfare { get; }
[NullAllowed, Export ("ISOcountryCode")]
string IsoCountryCode { get; }
[NullAllowed, Export ("areasOfInterest")]
string [] AreasOfInterest { get; }
[Export ("initWithPlacemark:")]
IntPtr Constructor (CLPlacemark placemark);
[NullAllowed, Export ("inlandWater")]
string InlandWater { get; }
[NullAllowed, Export ("location", ArgumentSemantic.Copy)]
CLLocation Location { get; }
[NullAllowed, Export ("name")]
string Name { get; }
[NullAllowed, Export ("ocean")]
string Ocean { get; }
[NullAllowed, Export ("region", ArgumentSemantic.Copy)]
CLRegion Region { get; }
[NullAllowed, Export ("timeZone")]
[iOS (9,0), Mac(10,11)]
NSTimeZone TimeZone { get; }
#if !TVOS
// From CLPlacemark (ContactsAdditions) category.
[Watch (4,0), NoTV, Mac (10,13), iOS (11,0)]
[NullAllowed, Export ("postalAddress")]
CNPostalAddress PostalAddress { get; }
#endif
}
[Mac (10,10)]
[iOS (7,0), BaseType (typeof (CLRegion))]
#if MONOMAC
[DisableDefaultCtor]
#endif
partial interface CLCircularRegion {
[Export ("initWithCenter:radius:identifier:")]
IntPtr Constructor (CLLocationCoordinate2D center, double radius, string identifier);
[Export ("center")]
CLLocationCoordinate2D Center { get; }
[Export ("radius")]
double Radius { get; }
[Export ("containsCoordinate:")]
bool ContainsCoordinate (CLLocationCoordinate2D coordinate);
}
[NoWatch][Mac (11,0)][NoTV]
[iOS (7,0), BaseType (typeof (CLRegion))]
[DisableDefaultCtor] // nil-Handle on iOS8 if 'init' is used
partial interface CLBeaconRegion {
[NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use the 'Create' method or the constructor using 'CLBeaconIdentityConstraint' instead.")]
[Export ("initWithProximityUUID:identifier:")]
IntPtr Constructor (NSUuid proximityUuid, string identifier);
[NoMac]
[iOS (13,0)]
[Internal] // signature conflict with deprecated API
[Export ("initWithUUID:identifier:")]
IntPtr _Constructor (NSUuid uuid, string identifier);
[NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use the 'Create' method or the constructor using 'CLBeaconIdentityConstraint' instead.")]
[Export ("initWithProximityUUID:major:identifier:")]
IntPtr Constructor (NSUuid proximityUuid, ushort major, string identifier);
[iOS (13,0)]
[Internal] // signature conflict with deprecated API
[Export ("initWithUUID:major:identifier:")]
IntPtr _Constructor (NSUuid uuid, ushort major, string identifier);
[NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use the 'Create' method or the constructor using 'CLBeaconIdentityConstraint' instead.")]
[Export ("initWithProximityUUID:major:minor:identifier:")]
IntPtr Constructor (NSUuid proximityUuid, ushort major, ushort minor, string identifier);
[iOS (13,0)]
[Internal] // signature conflict with deprecated API
[Export ("initWithUUID:major:minor:identifier:")]
IntPtr _Constructor (NSUuid uuid, ushort major, ushort minor, string identifier);
[iOS (13,0)]
[Export ("initWithBeaconIdentityConstraint:identifier:")]
IntPtr Constructor (CLBeaconIdentityConstraint beaconIdentityConstraint, string identifier);
[Export ("peripheralDataWithMeasuredPower:")]
NSMutableDictionary GetPeripheralData ([NullAllowed] NSNumber measuredPower);
[NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use 'Uuid' instead.")]
[Export ("proximityUUID", ArgumentSemantic.Copy)]
NSUuid ProximityUuid { get; }
[iOS (13,0)]
[Export ("UUID", ArgumentSemantic.Copy)]
NSUuid Uuid { get; }
[NullAllowed, Export ("major", ArgumentSemantic.Copy)]
NSNumber Major { get; }
[NullAllowed, Export ("minor", ArgumentSemantic.Copy)]
NSNumber Minor { get; }
[Export ("notifyEntryStateOnDisplay", ArgumentSemantic.Assign)]
bool NotifyEntryStateOnDisplay { get; set; }
[iOS (13,0)]
[Export ("beaconIdentityConstraint", ArgumentSemantic.Copy)]
CLBeaconIdentityConstraint BeaconIdentityConstraint { get; }
}
[NoWatch][Mac (11,0)][NoTV]
[iOS (7,0), BaseType (typeof (NSObject))]
partial interface CLBeacon : NSCopying, NSSecureCoding {
[NoMac]
[Deprecated (PlatformName.iOS, 13,0, message: "Use 'Uuid' instead.")]
[Export ("proximityUUID", ArgumentSemantic.Copy)]
NSUuid ProximityUuid { get; }
[iOS (13,0)]
[Export ("UUID", ArgumentSemantic.Copy)]
NSUuid Uuid { get; }
[Export ("major", ArgumentSemantic.Copy)]
NSNumber Major { get; }
[Export ("minor", ArgumentSemantic.Copy)]
NSNumber Minor { get; }
[Export ("proximity")]
CLProximity Proximity { get; }
[Export ("accuracy")]
double Accuracy { get; }
[Export ("rssi")]
nint Rssi { get; }
[iOS (13,0)]
[Export ("timestamp", ArgumentSemantic.Copy)]
NSDate Timestamp { get; }
}
delegate void CLGeocodeCompletionHandler (CLPlacemark [] placemarks, NSError error);
[BaseType (typeof (NSObject))]
interface CLGeocoder {
[Export ("isGeocoding")]
bool Geocoding { get; }
[Export ("reverseGeocodeLocation:completionHandler:")]
[Async]
void ReverseGeocodeLocation (CLLocation location, CLGeocodeCompletionHandler completionHandler);
[Watch (4,0), TV (11,0), Mac (10,13), iOS (11,0)]
[Export ("reverseGeocodeLocation:preferredLocale:completionHandler:")]
[Async]
void ReverseGeocodeLocation (CLLocation location, [NullAllowed] NSLocale locale, CLGeocodeCompletionHandler completionHandler);
[Deprecated (PlatformName.WatchOS, 4, 0, message: "Use 'GeocodeAddress (string, CLRegion, NSLocale, CLGeocodeCompletionHandler)' instead.")]
[Deprecated (PlatformName.iOS, 11, 0, message: "Use 'GeocodeAddress (string, CLRegion, NSLocale, CLGeocodeCompletionHandler)' instead.")]
[Deprecated (PlatformName.MacOSX, 10, 13, message: "Use 'GeocodeAddress (string, CLRegion, NSLocale, CLGeocodeCompletionHandler)' instead.")]
[Export ("geocodeAddressDictionary:completionHandler:")]
[Async]
void GeocodeAddress (NSDictionary addressDictionary, CLGeocodeCompletionHandler completionHandler);
[Export ("geocodeAddressString:completionHandler:")]
[Async]
void GeocodeAddress (string addressString, CLGeocodeCompletionHandler completionHandler);
[Export ("geocodeAddressString:inRegion:completionHandler:")]
[Async]
void GeocodeAddress (string addressString, [NullAllowed] CLRegion region, CLGeocodeCompletionHandler completionHandler);
[Watch (4,0), TV (11,0), Mac (10,13), iOS (11,0)]
[Async]
[Export ("geocodeAddressString:inRegion:preferredLocale:completionHandler:")]
void GeocodeAddress (string addressString, [NullAllowed] CLRegion region, [NullAllowed] NSLocale locale, CLGeocodeCompletionHandler completionHandler);
[Export ("cancelGeocode")]
void CancelGeocode ();
#if !TVOS
[Watch (4,0), NoTV, Mac (10,13), iOS (11,0)]
[Export ("geocodePostalAddress:completionHandler:")]
[Async]
void GeocodePostalAddress (CNPostalAddress postalAddress, CLGeocodeCompletionHandler completionHandler);
[Watch (4,0), NoTV, Mac (10,13), iOS (11,0)]
[Export ("geocodePostalAddress:preferredLocale:completionHandler:")]
[Async]
void GeocodePostalAddress (CNPostalAddress postalAddress, [NullAllowed] NSLocale locale, CLGeocodeCompletionHandler completionHandler);
#endif
}
[NoWatch][NoTV]
[iOS (8,0), Mac (11,0)]
[BaseType (typeof (NSObject))]
interface CLVisit : NSSecureCoding, NSCopying {
[Export ("arrivalDate", ArgumentSemantic.Copy)]
NSDate ArrivalDate { get; }
[Export ("departureDate", ArgumentSemantic.Copy)]
NSDate DepartureDate { get; }
[Export ("coordinate")]
CLLocationCoordinate2D Coordinate { get; }
[Export ("horizontalAccuracy")]
double HorizontalAccuracy { get; }
}
[NoWatch, NoTV, Mac (11,0), iOS (13,0)]
[BaseType (typeof (NSObject))]
[DisableDefaultCtor] // NSInvalidArgumentException Reason: -[CLBeaconIdentityConstraint init]: unrecognized selector sent to instance 0x600001930300
interface CLBeaconIdentityConstraint : NSCopying, NSSecureCoding {
[Export ("initWithUUID:")]
IntPtr Constructor (NSUuid uuid);
[Export ("initWithUUID:major:")]
IntPtr Constructor (NSUuid uuid, ushort major);
[Export ("initWithUUID:major:minor:")]
IntPtr Constructor (NSUuid uuid, ushort major, ushort minor);
[Export ("UUID", ArgumentSemantic.Copy)]
NSUuid Uuid { get; }
[NullAllowed, Export ("major", ArgumentSemantic.Copy)]
[BindAs (typeof (short?))]
NSNumber Major { get; }
[NullAllowed, Export ("minor", ArgumentSemantic.Copy)]
[BindAs (typeof (short?))]
NSNumber Minor { get; }
}
[iOS (15,0), TV (15,0), MacCatalyst (15,0), Mac (12,0), Watch (8,0)]
[Protocol]
interface CLLocationPushServiceExtension
{
[Abstract]
[Export ("didReceiveLocationPushPayload:completion:")]
void DidReceiveLocationPushPayload (NSDictionary<NSString, NSObject> payload, Action completion);
[Export ("serviceExtensionWillTerminate")]
void ServiceExtensionWillTerminate ();
}
[Watch (8,0), TV (15,0), Mac (12,0), iOS (15,0), MacCatalyst (15,0)]
[BaseType (typeof(NSObject))]
interface CLLocationSourceInformation : NSCopying, NSSecureCoding
{
[Export ("initWithSoftwareSimulationState:andExternalAccessoryState:")]
IntPtr Constructor (bool isSoftware, bool isAccessory);
[Export ("isSimulatedBySoftware")]
bool IsSimulatedBySoftware { get; }
[Export ("isProducedByAccessory")]
bool IsProducedByAccessory { get; }
}
}
| 35.127273 | 258 | 0.725003 | [
"BSD-3-Clause"
] | mandel-macaque/xamarin-macios | src/corelocation.cs | 32,844 | C# |
using Autodesk.Forge;
using Autodesk.Forge.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace forgeSample.Controllers
{
public class FMDataController : ControllerBase
{
/// <summary>
/// Credentials on this request
/// </summary>
private Credentials Credentials { get; set; }
/// <summary>
/// Start a new workitem
/// </summary>
[HttpPost]
[Route("api/forge/revit_fm/upsert_assets")]
public async Task<IActionResult> UpsertAssets([FromForm] InputData input)
{
try
{
Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);
if (Credentials == null) { return null; }
JObject bodyJson = JObject.Parse(input.data);
SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
// builder.DataSource = @"C:\Users\ogasawr\GitHub Repo\Learn Autodesk Forge\NET Core\learn.forge.viewhubmodels\db\fm_assets.db";
builder.DataSource = @".\db\fm_assets.db";
using (SQLiteConnection conn = new SQLiteConnection(builder.ConnectionString))
{
List<Asset> assets = JsonConvert.DeserializeObject<List<Asset>>(bodyJson["assets"].ToString());
if (assets.Count > 0)
{
conn.Open();
using (var transaction = conn.BeginTransaction())
{
foreach (Asset asset in assets)
{
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM assets WHERE id = @id";
cmd.Parameters.Add(new SQLiteParameter("@id", asset.Id));
cmd.Prepare();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Close();
// update
cmd.CommandText = "UPDATE assets SET model_id = @model_id, name = @name, revit_guid = @revit_guid, category = @category,location = @location, type_name = @type_name WHERE id = @id";
cmd.Parameters.Add(new SQLiteParameter("@model_id", asset.ModelId));
cmd.Parameters.Add(new SQLiteParameter("@name", asset.Name));
cmd.Parameters.Add(new SQLiteParameter("@revit_guid", asset.RevitGuid));
cmd.Parameters.Add(new SQLiteParameter("@category", asset.Category));
cmd.Parameters.Add(new SQLiteParameter("@location", asset.Location));
cmd.Parameters.Add(new SQLiteParameter("@type_name", asset.TypeName));
cmd.ExecuteNonQuery();
}
else
{
reader.Close();
// insert
cmd.CommandText = "INSERT INTO assets(id, model_id, name, revit_guid, category, location, type_name) VALUES(@id, @model_id, @name, @revit_guid, @category, @location, @type_name)";
cmd.Parameters.Add(new SQLiteParameter("@id", asset.Id));
cmd.Parameters.Add(new SQLiteParameter("@model_id", asset.ModelId));
cmd.Parameters.Add(new SQLiteParameter("@name", asset.Name));
cmd.Parameters.Add(new SQLiteParameter("@revit_guid", asset.RevitGuid));
cmd.Parameters.Add(new SQLiteParameter("@category", asset.Category));
cmd.Parameters.Add(new SQLiteParameter("@location", asset.Location));
cmd.Parameters.Add(new SQLiteParameter("@type_name", asset.TypeName));
cmd.ExecuteNonQuery();
}
}
}
transaction.Commit();
}
conn.Close();
}
}
return Ok();
}
catch (Exception e)
{
return Ok();
}
}
public static async Task<JArray> GetAssetsFromFMDB(JObject bodyJson)
{
JArray assetArray = new JArray();
await Task.Run(() =>
{
try
{
SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.DataSource = @".\db\fm_assets.db";
using (SQLiteConnection conn = new SQLiteConnection(builder.ConnectionString))
{
List<Asset> assets = JsonConvert.DeserializeObject<List<Asset>>(bodyJson["assets"].ToString());
if (assets.Count > 0)
{
conn.Open();
foreach (Asset asset in assets)
{
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM assets WHERE revit_guid = @revit_guid";
cmd.Parameters.Add(new SQLiteParameter("@revit_guid", asset.RevitGuid));
cmd.Prepare();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string assetRevitGuid = reader["revit_guid"].ToString();
string assetId = reader["id"].ToString();
dynamic assetObj = new JObject();
assetObj.AssetRevitGuid = assetRevitGuid;
assetObj.AssetId = assetId;
assetArray.Add(assetObj);
}
}
reader.Close();
}
}
conn.Close();
}
}
}
catch (Exception e)
{
}
});
return assetArray;
}
[HttpGet]
[Route("api/forge/revit_fm/maintenance_records")]
public async Task<JArray> GetMaintenanceRecordsFromFMDB([FromQuery]string projectId, [FromQuery] string itemId)
{
JArray maintenanceRecordArray = new JArray();
string modelId = "https://developer.api.autodesk.com/data/v1/projects/" + projectId + "/items/" + itemId;
await Task.Run(() =>
{
try
{
SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.DataSource = @".\db\fm_assets.db";
using (SQLiteConnection conn = new SQLiteConnection(builder.ConnectionString))
{
if (modelId.Length > 0)
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM maintenance WHERE model_id = @model_id";
cmd.Parameters.Add(new SQLiteParameter("@model_id", modelId));
cmd.Prepare();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string reportId = reader["report_id"].ToString();
string assetId = reader["asset_id"].ToString();
string modelId = reader["model_id"].ToString();
string assetRevitGuid = reader["revit_guid"].ToString();
string priority = reader["priority"].ToString();
string status = reader["status"].ToString();
string title = reader["title"].ToString();
string assetName = reader["asset_name"].ToString();
string description = reader["description"].ToString();
string reporter = reader["reporter"].ToString();
string assignee = reader["assignee"].ToString();
string creadateDate = reader["created_at"].ToString();
string updatedDate = reader["updated_at"].ToString();
dynamic reportObj = new JObject();
reportObj.reportId = reportId;
reportObj.assetId = assetId;
reportObj.modelId = modelId;
reportObj.assetRevitGuid = assetRevitGuid;
reportObj.priority = priority;
reportObj.status = status;
reportObj.title = title;
reportObj.assetName = assetName;
reportObj.description = description;
reportObj.reporter = reporter;
reportObj.assignee = assignee;
reportObj.creadateDate = creadateDate;
reportObj.updatedDate = updatedDate;
maintenanceRecordArray.Add(reportObj);
}
}
reader.Close();
}
conn.Close();
}
}
}
catch (Exception e)
{
}
});
return maintenanceRecordArray;
}
/// <summary>
/// Start a new workitem
/// </summary>
[HttpPost]
[Route("api/forge/fm_revit/create_report")]
public async Task<IActionResult> CreateMaintenanceReport([FromForm] InputData input)
{
try
{
Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);
if (Credentials == null) { return null; }
JObject bodyJson = JObject.Parse(input.data);
SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.DataSource = @".\db\fm_assets.db";
using (SQLiteConnection conn = new SQLiteConnection(builder.ConnectionString))
{
MaintenanceReport report = JsonConvert.DeserializeObject<MaintenanceReport>(bodyJson.ToString());
conn.Open();
using (var transaction = conn.BeginTransaction())
{
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO maintenance(model_id, title, asset_name, asset_id, revit_guid, description, priority, status) VALUES(@model_id, @title, @asset_name, @asset_id, @revit_guid, @description, @priority, @status)";
cmd.Parameters.Add(new SQLiteParameter("@model_id", report.ModelId));
cmd.Parameters.Add(new SQLiteParameter("@title", report.Title));
cmd.Parameters.Add(new SQLiteParameter("@asset_name", report.AssetName));
cmd.Parameters.Add(new SQLiteParameter("@asset_id", report.AssetId));
cmd.Parameters.Add(new SQLiteParameter("@revit_guid", report.RevitGuid));
cmd.Parameters.Add(new SQLiteParameter("@description", report.Description));
cmd.Parameters.Add(new SQLiteParameter("@priority", report.Priority));
cmd.Parameters.Add(new SQLiteParameter("@status", "Open"));
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
conn.Close();
}
return Ok();
}
catch (Exception e)
{
return Ok();
}
}
public class InputData
{
public string data { get; set; }
}
[JsonObject]
class Asset
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("model_id")]
public string ModelId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("revit_guid")]
public string RevitGuid { get; set; }
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("type_name")]
public string TypeName { get; set; }
}
[JsonObject]
class MaintenanceReport
{
[JsonProperty("modelId")]
public string ModelId { get; set; }
[JsonProperty("assetName")]
public string AssetName { get; set; }
[JsonProperty("revitGuid")]
public string RevitGuid { get; set; }
[JsonProperty("assetId")]
public string AssetId { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("priority")]
public string Priority { get; set; }
}
}
}
| 42.674797 | 251 | 0.440973 | [
"MIT"
] | ogaryu/autodesk.forge.acc.fm.integration | forgesapmle/Controllers/FMDataController.cs | 15,749 | C# |
using System.Collections.Generic;
using CodeComposerLib.GraphViz.Dot.Value;
using TextComposerLib;
namespace CodeComposerLib.GraphViz.Dot.Label.Table
{
/// <summary>
/// This class represents the cell image inside an HTML table tag in the dot language
/// See http://www.graphviz.org/content/node-shapes#html for more details
/// </summary>
public sealed class DotHtmlCellImage : DotHtmlTag, IDotHtmlCellContents
{
/// <summary>
/// The source file path of the image
/// </summary>
public string ImageSource { get; private set; }
/// <summary>
/// The image scale
/// </summary>
public string ImageScale { get; private set; }
public override IEnumerable<KeyValuePair<string, string>> Attributes
{
get
{
if (string.IsNullOrEmpty(ImageScale) == false)
yield return new KeyValuePair<string, string>("SCALE", ImageScale);
if (string.IsNullOrEmpty(ImageSource) == false)
yield return new KeyValuePair<string, string>("SRC", ImageSource);
}
}
internal DotHtmlCellImage()
: base("IMG")
{
ImageSource = string.Empty;
ImageScale = string.Empty;
}
public DotHtmlCellImage ClearAttributes()
{
ImageSource = string.Empty;
ImageScale = string.Empty;
return this;
}
public DotHtmlCellImage ClearImageSource()
{
ImageSource = string.Empty;
return this;
}
public DotHtmlCellImage ClearImageScale()
{
ImageScale = string.Empty;
return this;
}
public DotHtmlCellImage SetImageSource(string filePath)
{
ImageSource = filePath.ValueToQuotedLiteral();
return this;
}
public DotHtmlCellImage SetImageScale(bool flag)
{
ImageScale = (flag ? "TRUE" : "FALSE").DoubleQuote();
return this;
}
public DotHtmlCellImage SetImageScale(DotNodeImageScale value)
{
ImageScale = value.QuotedValue.ToUpper();
return this;
}
public DotHtmlCellImage SetImageScaleFalse()
{
ImageScale = "\"FALSE\"";
return this;
}
public DotHtmlCellImage SetImageScaleTrue()
{
ImageScale = "\"TRUE\"";
return this;
}
public DotHtmlCellImage SetImageScaleWidth()
{
ImageScale = "\"WIDTH\"";
return this;
}
public DotHtmlCellImage SetImageScaleHeight()
{
ImageScale = "\"HEIGHT\"";
return this;
}
public DotHtmlCellImage SetImageScaleBoth()
{
ImageScale = "\"BOTH\"";
return this;
}
public override string ToString()
{
return TagNoContentsText;
}
}
}
| 23.572519 | 89 | 0.541127 | [
"MIT"
] | ga-explorer/GeometricAlgebraFulcrumLib | CodeComposerLib/CodeComposerLib/GraphViz/Dot/Label/Table/DotHtmlCellImage.cs | 3,090 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Lucene.Net.Search
{
/* See the description in BooleanScorer.java, comparing
* BooleanScorer & BooleanScorer2 */
/// <summary>An alternative to BooleanScorer that also allows a minimum number
/// of optional scorers that should match.
/// <br/>Implements skipTo(), and has no limitations on the numbers of added scorers.
/// <br/>Uses ConjunctionScorer, DisjunctionScorer, ReqOptScorer and ReqExclScorer.
/// </summary>
class BooleanScorer2 : Scorer
{
private class AnonymousClassDisjunctionSumScorer:DisjunctionSumScorer
{
private void InitBlock(BooleanScorer2 enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private BooleanScorer2 enclosingInstance;
public BooleanScorer2 Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal AnonymousClassDisjunctionSumScorer(BooleanScorer2 enclosingInstance, System.Collections.Generic.IList<Scorer> scorers, int minNrShouldMatch)
: base(scorers, minNrShouldMatch)
{
InitBlock(enclosingInstance);
}
private int lastScoredDoc = - 1;
// Save the score of lastScoredDoc, so that we don't compute it more than
// once in score().
private float lastDocScore = System.Single.NaN;
public override float Score()
{
int doc = DocID();
if (doc >= lastScoredDoc)
{
if (doc > lastScoredDoc)
{
lastDocScore = base.Score();
lastScoredDoc = doc;
}
Enclosing_Instance.coordinator.nrMatchers += base.nrMatchers;
}
return lastDocScore;
}
}
private class AnonymousClassConjunctionScorer:ConjunctionScorer
{
private void InitBlock(int requiredNrMatchers, BooleanScorer2 enclosingInstance)
{
this.requiredNrMatchers = requiredNrMatchers;
this.enclosingInstance = enclosingInstance;
}
private int requiredNrMatchers;
private BooleanScorer2 enclosingInstance;
public BooleanScorer2 Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal AnonymousClassConjunctionScorer(int requiredNrMatchers, BooleanScorer2 enclosingInstance, Lucene.Net.Search.Similarity defaultSimilarity, System.Collections.Generic.IList<Scorer> requiredScorers)
: base(defaultSimilarity, requiredScorers)
{
InitBlock(requiredNrMatchers, enclosingInstance);
}
private int lastScoredDoc = - 1;
// Save the score of lastScoredDoc, so that we don't compute it more than
// once in score().
private float lastDocScore = System.Single.NaN;
public override float Score()
{
int doc = DocID();
if (doc >= lastScoredDoc)
{
if (doc > lastScoredDoc)
{
lastDocScore = base.Score();
lastScoredDoc = doc;
}
Enclosing_Instance.coordinator.nrMatchers += requiredNrMatchers;
}
// All scorers match, so defaultSimilarity super.score() always has 1 as
// the coordination factor.
// Therefore the sum of the scores of the requiredScorers
// is used as score.
return lastDocScore;
}
}
private System.Collections.Generic.List<Scorer> requiredScorers;
private System.Collections.Generic.List<Scorer> optionalScorers;
private System.Collections.Generic.List<Scorer> prohibitedScorers;
private class Coordinator
{
public Coordinator(BooleanScorer2 enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(BooleanScorer2 enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private BooleanScorer2 enclosingInstance;
public BooleanScorer2 Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
internal float[] coordFactors = null;
internal int maxCoord = 0; // to be increased for each non prohibited scorer
internal int nrMatchers; // to be increased by score() of match counting scorers.
internal virtual void Init()
{
// use after all scorers have been added.
coordFactors = new float[maxCoord + 1];
Similarity sim = Enclosing_Instance.Similarity;
for (int i = 0; i <= maxCoord; i++)
{
coordFactors[i] = sim.Coord(i, maxCoord);
}
}
}
private Coordinator coordinator;
/// <summary>The scorer to which all scoring will be delegated,
/// except for computing and using the coordination factor.
/// </summary>
private Scorer countingSumScorer;
/// <summary>The number of optionalScorers that need to match (if there are any) </summary>
private int minNrShouldMatch;
private int doc = - 1;
/// <summary> Creates a <see cref="Scorer" /> with the given similarity and lists of required,
/// prohibited and optional scorers. In no required scorers are added, at least
/// one of the optional scorers will have to match during the search.
///
/// </summary>
/// <param name="similarity">The similarity to be used.
/// </param>
/// <param name="minNrShouldMatch">The minimum number of optional added scorers that should match
/// during the search. In case no required scorers are added, at least
/// one of the optional scorers will have to match during the search.
/// </param>
/// <param name="required">the list of required scorers.
/// </param>
/// <param name="prohibited">the list of prohibited scorers.
/// </param>
/// <param name="optional">the list of optional scorers.
/// </param>
public BooleanScorer2(Similarity similarity, int minNrShouldMatch,
System.Collections.Generic.List<Scorer> required,
System.Collections.Generic.List<Scorer> prohibited,
System.Collections.Generic.List<Scorer> optional)
: base(similarity)
{
if (minNrShouldMatch < 0)
{
throw new System.ArgumentException("Minimum number of optional scorers should not be negative");
}
coordinator = new Coordinator(this);
this.minNrShouldMatch = minNrShouldMatch;
optionalScorers = optional;
coordinator.maxCoord += optional.Count;
requiredScorers = required;
coordinator.maxCoord += required.Count;
prohibitedScorers = prohibited;
coordinator.Init();
countingSumScorer = MakeCountingSumScorer();
}
/// <summary>Count a scorer as a single match. </summary>
private class SingleMatchScorer:Scorer
{
private void InitBlock(BooleanScorer2 enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private BooleanScorer2 enclosingInstance;
public BooleanScorer2 Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private Scorer scorer;
private int lastScoredDoc = - 1;
// Save the score of lastScoredDoc, so that we don't compute it more than
// once in score().
private float lastDocScore = System.Single.NaN;
internal SingleMatchScorer(BooleanScorer2 enclosingInstance, Scorer scorer):base(scorer.Similarity)
{
InitBlock(enclosingInstance);
this.scorer = scorer;
}
public override float Score()
{
int doc = DocID();
if (doc >= lastScoredDoc)
{
if (doc > lastScoredDoc)
{
lastDocScore = scorer.Score();
lastScoredDoc = doc;
}
Enclosing_Instance.coordinator.nrMatchers++;
}
return lastDocScore;
}
public override int DocID()
{
return scorer.DocID();
}
public override int NextDoc()
{
return scorer.NextDoc();
}
public override int Advance(int target)
{
return scorer.Advance(target);
}
}
private Scorer CountingDisjunctionSumScorer(System.Collections.Generic.List<Scorer> scorers, int minNrShouldMatch)
{
// each scorer from the list counted as a single matcher
return new AnonymousClassDisjunctionSumScorer(this, scorers, minNrShouldMatch);
}
private static readonly Similarity defaultSimilarity;
private Scorer CountingConjunctionSumScorer(System.Collections.Generic.List<Scorer> requiredScorers)
{
// each scorer from the list counted as a single matcher
int requiredNrMatchers = requiredScorers.Count;
return new AnonymousClassConjunctionScorer(requiredNrMatchers, this, defaultSimilarity, requiredScorers);
}
private Scorer DualConjunctionSumScorer(Scorer req1, Scorer req2)
{
// non counting.
return new ConjunctionScorer(defaultSimilarity, new Scorer[]{req1, req2});
// All scorers match, so defaultSimilarity always has 1 as
// the coordination factor.
// Therefore the sum of the scores of two scorers
// is used as score.
}
/// <summary>Returns the scorer to be used for match counting and score summing.
/// Uses requiredScorers, optionalScorers and prohibitedScorers.
/// </summary>
private Scorer MakeCountingSumScorer()
{
// each scorer counted as a single matcher
return (requiredScorers.Count == 0)?MakeCountingSumScorerNoReq():MakeCountingSumScorerSomeReq();
}
private Scorer MakeCountingSumScorerNoReq()
{
// No required scorers
// minNrShouldMatch optional scorers are required, but at least 1
int nrOptRequired = (minNrShouldMatch < 1)?1:minNrShouldMatch;
Scorer requiredCountingSumScorer;
if (optionalScorers.Count > nrOptRequired)
requiredCountingSumScorer = CountingDisjunctionSumScorer(optionalScorers, nrOptRequired);
else if (optionalScorers.Count == 1)
requiredCountingSumScorer = new SingleMatchScorer(this, optionalScorers[0]);
else
requiredCountingSumScorer = CountingConjunctionSumScorer(optionalScorers);
return AddProhibitedScorers(requiredCountingSumScorer);
}
private Scorer MakeCountingSumScorerSomeReq()
{
// At least one required scorer.
if (optionalScorers.Count == minNrShouldMatch)
{
// all optional scorers also required.
var allReq = new System.Collections.Generic.List<Scorer>(requiredScorers);
allReq.AddRange(optionalScorers);
return AddProhibitedScorers(CountingConjunctionSumScorer(allReq));
}
else
{
// optionalScorers.size() > minNrShouldMatch, and at least one required scorer
Scorer requiredCountingSumScorer =
requiredScorers.Count == 1
? new SingleMatchScorer(this, requiredScorers[0])
: CountingConjunctionSumScorer(requiredScorers);
if (minNrShouldMatch > 0)
{
// use a required disjunction scorer over the optional scorers
return AddProhibitedScorers(DualConjunctionSumScorer(requiredCountingSumScorer, CountingDisjunctionSumScorer(optionalScorers, minNrShouldMatch)));
}
else
{
// minNrShouldMatch == 0
return new ReqOptSumScorer(AddProhibitedScorers(requiredCountingSumScorer),
optionalScorers.Count == 1
? new SingleMatchScorer(this, optionalScorers[0])
: CountingDisjunctionSumScorer(optionalScorers, 1));
}
}
}
/// <summary>Returns the scorer to be used for match counting and score summing.
/// Uses the given required scorer and the prohibitedScorers.
/// </summary>
/// <param name="requiredCountingSumScorer">A required scorer already built.
/// </param>
private Scorer AddProhibitedScorers(Scorer requiredCountingSumScorer)
{
return (prohibitedScorers.Count == 0)
? requiredCountingSumScorer
: new ReqExclScorer(requiredCountingSumScorer,
((prohibitedScorers.Count == 1)
? prohibitedScorers[0]
: new DisjunctionSumScorer(prohibitedScorers)));
}
/// <summary>Scores and collects all matching documents.</summary>
/// <param name="collector">The collector to which all matching documents are passed through.
/// </param>
public override void Score(Collector collector)
{
collector.SetScorer(this);
while ((doc = countingSumScorer.NextDoc()) != NO_MORE_DOCS)
{
collector.Collect(doc);
}
}
public /*protected internal*/ override bool Score(Collector collector, int max, int firstDocID)
{
doc = firstDocID;
collector.SetScorer(this);
while (doc < max)
{
collector.Collect(doc);
doc = countingSumScorer.NextDoc();
}
return doc != NO_MORE_DOCS;
}
public override int DocID()
{
return doc;
}
public override int NextDoc()
{
return doc = countingSumScorer.NextDoc();
}
public override float Score()
{
coordinator.nrMatchers = 0;
float sum = countingSumScorer.Score();
return sum * coordinator.coordFactors[coordinator.nrMatchers];
}
public override int Advance(int target)
{
return doc = countingSumScorer.Advance(target);
}
static BooleanScorer2()
{
defaultSimilarity = Search.Similarity.Default;
}
}
} | 40.870504 | 216 | 0.555712 | [
"Apache-2.0"
] | ClearCanvas/lucene.net | src/core/Search/BooleanScorer2.cs | 17,043 | C# |
/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:工作单元实现类
*│ 作 者:zhengshengyi
*│ 版 本:1.0
*│ 创建时间:2020/8/16 22:15:44
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: DotnetCms.Core.Repository
*│ 类 名: UnitOfWork
*└──────────────────────────────────────────────────────────────┘
*/
using Dapper;
using DotnetCms.Core.DbHelper;
using DotnetCms.Core.Options;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Transactions;
namespace DotnetCms.Core.Repository
{
public class UnitOfWork : IUnitOfWork
{
public IDbConnection _dbConnection;
protected DbOption _dbOpion;
private Dictionary<object, Action> addEntities;
private Dictionary<object, Action> updateEntities;
private Dictionary<object, Action> deleteEntities;
public UnitOfWork(IOptionsSnapshot<DbOption> options)
{
_dbOpion = options.Get("DotnetCmsOption");
if (_dbOpion == null)
{
throw new ArgumentNullException(nameof(DbOption));
}
addEntities = new Dictionary<object, Action>();
updateEntities = new Dictionary<object, Action>();
deleteEntities = new Dictionary<object, Action>();
}
public void Add<TEntity>(TEntity entity) where TEntity : class
{
this.addEntities.Add(entity, () =>
{
_dbConnection.Insert<TEntity>(entity);
});
}
public void Update<TEntity>(TEntity entity) where TEntity : class
{
this.updateEntities.Add(entity, () =>
{
_dbConnection.Update(entity);
});
}
public void Delete<TEntity>(TEntity entity) where TEntity : class
{
this.deleteEntities.Add(entity, () =>
{
_dbConnection.Delete(entity);
});
}
public int Commit()
{
int count = 0;
using (TransactionScope scope = CreateTransactionScope())
{
try
{
using (_dbConnection = ConnectionFactory.CreateConnection(_dbOpion.DbType, _dbOpion.ConnectionString))
{
foreach (var entity in deleteEntities.Keys)
{
this.deleteEntities[entity]();
}
foreach (var entity in updateEntities.Keys)
{
this.updateEntities[entity]();
}
foreach (var entity in addEntities.Keys)
{
this.addEntities[entity]();
}
}
scope.Complete();
count = deleteEntities.Count + updateEntities.Count + addEntities.Count;
deleteEntities.Clear();
updateEntities.Clear();
addEntities.Clear();
if (_dbConnection != null)
{
if (_dbConnection.State == ConnectionState.Open)
{
_dbConnection.Close();
}
// Conn.Dispose();
}
}
catch (Exception ex)
{
count = 0;
throw ex;
}
}
return count;
}
public static TransactionScope CreateTransactionScope()
{
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
transactionOptions.Timeout = TransactionManager.MaximumTimeout;
return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
}
}
}
| 33.816794 | 122 | 0.445372 | [
"MIT"
] | zhengshengyi/DotnetCms | DotnetCms.Core/Repository/UnitOfWork.cs | 5,026 | C# |
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Text;
namespace App.Core.Utilities.Security
{
public class SigningCredentialsHelper
{
public static SigningCredentials CreateSigningCredentials(SecurityKey securityKey)
{
return new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
}
}
}
| 25.625 | 95 | 0.74878 | [
"MIT"
] | halilkoca/MovieApi | App/App.Core/Utilities/Security/SigningCredentialsHelper.cs | 412 | C# |
using System.Xml.Serialization;
namespace MonoGame.Extended.Tiled.Serialization
{
public class TiledMapTileLayerContent : TiledMapLayerContent
{
public TiledMapTileLayerContent()
: base(TiledMapLayerType.TileLayer)
{
}
[XmlAttribute(AttributeName = "x")]
public int X { get; set; }
[XmlAttribute(AttributeName = "y")]
public int Y { get; set; }
[XmlAttribute(AttributeName = "width")]
public int Width { get; set; }
[XmlAttribute(AttributeName = "height")]
public int Height { get; set; }
[XmlElement(ElementName = "data")]
public TiledMapTileLayerDataContent Data { get; set; }
[XmlIgnore]
public TiledMapTile[] Tiles { get; set; }
}
} | 26.233333 | 64 | 0.60737 | [
"MIT"
] | Acidburn0zzz/MonoGame.Extended | Source/MonoGame.Extended.Tiled/Serialization/TiledMapTileLayerContent.cs | 787 | C# |
// <copyright file="GlobalSuppressions.cs" company="Sven Erik Matzen">
// Copyright (c) Sven Erik Matzen. All rights reserved.
// </copyright>
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "No globalization needed.")]
[assembly: SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "Structure of tests is this way in my projects.")]
[assembly: SuppressMessage("Usage", "CA1806:Do not ignore method results", Justification = "needed for testing purpose", Scope = "member", Target = "~M:Sem.Tools.TestHelper.Tests.ClassExpectedExceptionMessageAttribute.Ctor.CtorThrowsExpectedExceptionWhenExceptionTypeNotInheritsException")]
[assembly: SuppressMessage("Usage", "CA1806:Do not ignore method results", Justification = "needed for testing purpose", Scope = "member", Target = "~M:Sem.Tools.TestHelper.Tests.ClassExpectedExceptionMessageAttribute.Ctor.CtorThrowsExpectedExceptionWhenTypeIsNull")]
| 94.272727 | 290 | 0.795564 | [
"MIT"
] | Interface007/Sem.Tools | Sem.Tools.TestHelper.Tests/GlobalSuppressions.cs | 1,039 | 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("04. Pokemon Evolution")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04. Pokemon Evolution")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4a1222cb-3de4-4d29-8e3d-2176aae120f5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.243243 | 84 | 0.74417 | [
"MIT"
] | stoyanovmiroslav/Tech-Module-Practice | Programming Fundamentals/Programming Fundamentals Exams/Programming Fundamentals Exam - 09 July 2017/04. Pokemon Evolution/Properties/AssemblyInfo.cs | 1,418 | C# |
using System.IO;
namespace TeleSharp.TL.Messages
{
[TLObject(479598769)]
public class TLRequestGetAllStickers : TLMethod
{
public override int Constructor
{
get
{
return 479598769;
}
}
public int Hash { get; set; }
public TLAbsAllStickers Response { get; set; }
public void ComputeFlags()
{
}
public override void DeserializeBody(BinaryReader br)
{
Hash = br.ReadInt32();
}
public override void SerializeBody(BinaryWriter bw)
{
bw.Write(Constructor);
bw.Write(Hash);
}
public override void DeserializeResponse(BinaryReader br)
{
Response = (TLAbsAllStickers)ObjectUtils.DeserializeObject(br);
}
}
}
| 20 | 75 | 0.539535 | [
"MIT"
] | cobra91/TelegramCSharpForward | TeleSharp.TL/TL/Messages/TLRequestGetAllStickers.cs | 860 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Facebook;
using FacebookAds.Interfaces;
/// <summary>
/// The MIT License (MIT)
///
/// Copyright (c) 2017 - Luke Paris (Paradoxis) | Searchresult Performancemarketing
///
/// 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.
/// </summary>
/// <date>2017-11-12 14:56:48</date>
/// <author>Luke Paris (Paradoxis) | [email protected]</author>
///
/// <remarks>
/// This file was automatically generated using the Facebook Ads
/// PHP SDK to C# converter found in this library under '/src/SdkConverter/'
/// For more information please refer to the official documentation
/// </remarks>
namespace FacebookAds.Object
{
public class AdsPixelStats : AbstractCrudObject
{
/// <summary>
/// Initializes a new instance of the <see cref="AdsPixelStats"/> class.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="parentId">The parent identifier.</param>
/// <param name="client">The client.</param>
public AdsPixelStats(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client) { }
/// <summary>Gets the endpoint of the API call.</summary>
/// <returns>Endpoint URL</returns>
protected override string GetEndpoint()
{
return "";
}
}
}
| 38.734375 | 126 | 0.696652 | [
"MIT"
] | AsimKhan2019/Facebook-Ads-SDK-C- | src/FacebookAds/FacebookAds/Object/AdsPixelStats.cs | 2,479 | C# |
// <auto-generated />
using System;
using HBSIS_Padawan.Sistema.Boletim.Repositories.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace HBSIS_Padawan.Sistema.Boletim.Repositories.Migrations
{
[DbContext(typeof(ApplicationContext))]
[Migration("20200926195921_FirstMigration")]
partial class FirstMigration
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.8")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.Aluno", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Cpf")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("Nascimento")
.HasColumnType("datetime2");
b.Property<string>("Nome")
.IsRequired()
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.Property<string>("Sobrenome")
.IsRequired()
.HasColumnType("nvarchar(20)")
.HasMaxLength(20);
b.HasKey("Id");
b.ToTable("Alunos");
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.AlunoCurso", b =>
{
b.Property<int>("AlunoId")
.HasColumnType("int");
b.Property<int>("CursoId")
.HasColumnType("int");
b.HasKey("AlunoId", "CursoId");
b.HasIndex("CursoId");
b.ToTable("AlunoCurso");
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.Curso", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Nome")
.IsRequired()
.HasColumnType("Varchar(50)");
b.Property<string>("Situacao")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("nvarchar(max)")
.HasDefaultValue("Ativo");
b.HasKey("Id");
b.ToTable("Cursos");
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.CursoMateria", b =>
{
b.Property<int>("CursoId")
.HasColumnType("int");
b.Property<int>("MateriaId")
.HasColumnType("int");
b.HasKey("CursoId", "MateriaId");
b.HasIndex("MateriaId");
b.ToTable("CursoMateria");
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.Materia", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("Cadastro")
.ValueGeneratedOnAdd()
.HasColumnType("datetime2")
.HasDefaultValueSql("GETDATE()");
b.Property<string>("Descricao")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Nome")
.IsRequired()
.HasColumnType("Varchar(50)");
b.Property<string>("Status")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("nvarchar(max)")
.HasDefaultValue("Ativo");
b.HasKey("Id");
b.ToTable("Materias");
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.Models.AlunoMateria", b =>
{
b.Property<int>("AlunoId")
.HasColumnType("int");
b.Property<int>("MateriaId")
.HasColumnType("int");
b.Property<int>("Id")
.HasColumnType("int");
b.Property<double>("Nota")
.HasColumnType("float");
b.HasKey("AlunoId", "MateriaId");
b.HasIndex("MateriaId");
b.ToTable("AlunoMateria");
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.Usuario", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Login")
.HasColumnType("nvarchar(max)");
b.Property<string>("Senha")
.HasColumnType("nvarchar(max)");
b.Property<int>("Tipo")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Usuarios");
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.AlunoCurso", b =>
{
b.HasOne("HBSIS_Padawan.Sistema.Boletim.Models.Aluno", "Aluno")
.WithMany("AlunoCursos")
.HasForeignKey("AlunoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("HBSIS_Padawan.Sistema.Boletim.Models.Curso", "Curso")
.WithMany("CursoAlunos")
.HasForeignKey("CursoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.CursoMateria", b =>
{
b.HasOne("HBSIS_Padawan.Sistema.Boletim.Models.Curso", "Curso")
.WithMany("CursoMaterias")
.HasForeignKey("CursoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("HBSIS_Padawan.Sistema.Boletim.Models.Materia", "Materia")
.WithMany("MateriaCursos")
.HasForeignKey("MateriaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("HBSIS_Padawan.Sistema.Boletim.Models.Models.AlunoMateria", b =>
{
b.HasOne("HBSIS_Padawan.Sistema.Boletim.Models.Aluno", "Aluno")
.WithMany("AlunoMaterias")
.HasForeignKey("AlunoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("HBSIS_Padawan.Sistema.Boletim.Models.Materia", "Materia")
.WithMany("MateriaAlunos")
.HasForeignKey("MateriaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.893805 | 125 | 0.473494 | [
"MIT"
] | rmarnon/HBSIS_Padawan.Sstema.Boletim | HBSIS_Padawan.Sistema.Boletim.Repositories/Migrations/20200926195921_FirstMigration.Designer.cs | 8,566 | C# |
using System.Windows.Input;
using FlaUI.Core.WindowsAPI;
using Macad.Test.UI.Framework;
using NUnit.Framework;
namespace Macad.Test.UI.Application.Edit
{
public class KeyboardTests : UITestBase
{
[SetUp]
public void SetUp()
{
Reset();
}
//--------------------------------------------------------------------------------------------------
[Test]
public void ForwardEscapeFromTreeView()
{
// Init
TestDataGenerator.GenerateBox(MainWindow);
// Start transform
MainWindow.Ribbon.SelectGroup("Edit");
Assert.IsTrue(MainWindow.Ribbon.IsButtonEnabled("TransformShape"));
MainWindow.Ribbon.ClickButton("TransformShape");
Assert.AreEqual("TransformTool", Pipe.GetValue<string>("$Context.EditorState.ActiveTool"));
// Select tree view
MainWindow.Document.SelectItem("Box_1");
// Press Escape, tool should be canceled
Pipe.TypeKey(VirtualKeyShort.ESCAPE);
Assert.AreEqual("", Pipe.GetValue<string>("$Context.EditorState.ActiveTool"));
}
//--------------------------------------------------------------------------------------------------
[Test]
public void ForwardSpaceFromTreeView()
{
// Init
TestDataGenerator.GenerateBox(MainWindow);
Assert.IsFalse(Pipe.GetValue<bool>("$Context.WorkspaceController.VisualObjects.EntityIsolationEnabled"));
// Select tree view
MainWindow.Document.SelectItem("Box_1");
// Press Escape, tool should be canceled
Pipe.TypeKey(VirtualKeyShort.SPACE);
Assert.IsTrue(Pipe.GetValue<bool>("$Context.WorkspaceController.VisualObjects.EntityIsolationEnabled"));
}
//--------------------------------------------------------------------------------------------------
[Test]
public void ForwardKeysFromLayers()
{
// Init
bool gridEnabled = Pipe.GetValue<bool>("$Context.WorkspaceController.Workspace.GridEnabled");
// Select layers
MainWindow.Layers.SelectItem(0);
// Press G, grid should be toggled
Pipe.TypeKey(VirtualKeyShort.KEY_G);
Assert.AreNotEqual(gridEnabled, Pipe.GetValue<bool>("$Context.WorkspaceController.Workspace.GridEnabled"));
}
//--------------------------------------------------------------------------------------------------
[Test]
public void ForwardSpaceFromLayers()
{
// Init
TestDataGenerator.GenerateBox(MainWindow);
Assert.IsFalse(Pipe.GetValue<bool>("$Context.WorkspaceController.VisualObjects.EntityIsolationEnabled"));
// Select layers
MainWindow.Layers.SelectItem(0);
// Press Escape, tool should be canceled
Pipe.TypeKey(VirtualKeyShort.SPACE);
Assert.IsTrue(Pipe.GetValue<bool>("$Context.WorkspaceController.VisualObjects.EntityIsolationEnabled"));
}
}
} | 36.898876 | 120 | 0.511267 | [
"MIT"
] | RileyGe/Macad3D | Source/Test.UI/Application/Edit/KeyboardTests.cs | 3,286 | C# |
using System;
using Client.Unit;
using Client.UI;
namespace Client.UnitFSM
{
/// <summary>
/// 玩家胜利的状态
/// </summary>
public class SuccessState : FSMState
{
public SuccessState(Room content)
: base(content, FSMStateType.SuccessState)
{
}
/// <summary>
/// 进入玩家胜利状态,打开胜利界面卡牌
/// </summary>
/// <param name="e"></param>
/// <param name="lastState"></param>
public override void Enter(Core.FSM.Event e, Core.FSM.FiniteStateMachine<Room>.State lastState)
{
CardManager.Instance.OpenCard((int)SpecialCardType.SuccessType);
}
protected override void _OnExit(Core.FSM.Event e, Core.FSM.FiniteStateMachine<Room>.State nextState)
{
}
protected override Core.FSM.FiniteStateMachine<Room>.State _DoTick(float deltaTime)
{
return this;
}
}
}
| 24.948718 | 109 | 0.561151 | [
"Apache-2.0"
] | rusmass/wealthland_client | arpg_prg/client_prg/Assets/Code/Client/AI/FSM/SuccessState.cs | 1,023 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// 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("PowerShellClient.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PowerShellClient.Tests")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("75829f39-493b-453b-a634-b2d98c2619a4")]
// 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: Parallelize(Workers = 0, Scope = Microsoft.VisualStudio.TestTools.UnitTesting.ExecutionScope.MethodLevel)] | 48.1875 | 117 | 0.780156 | [
"CC0-1.0"
] | BrainSlugs83/PowerShellClient | BetterPowerShellClient.Tests/Properties/AssemblyInfo.cs | 1,545 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NEvilES.Abstractions.Pipeline.Async
{
public interface IReadFromReadModelAsync<in TId>
{
Task<T> GetAsync<T>(Guid id) where T : IHaveIdentity<TId>;
Task<IEnumerable<T>> QueryAsync<T>(Func<T, bool> p);
}
public interface IWriteReadModelAsync<in TId>
{
Task InsertAsync<T>(T item) where T : class, IHaveIdentity<TId>;
Task UpdateAsync<T>(T item) where T : class, IHaveIdentity<TId>;
Task SaveAsync<T>(T item) where T : class, IHaveIdentity<TId>;
Task DeleteAsync<T>(T item) where T : class, IHaveIdentity<TId>;
}
} | 33.095238 | 73 | 0.658993 | [
"Apache-2.0"
] | CRGCode/NEvilES | src/NEvilES.Abstractions/Pipeline/Async/IReadModelAsync.cs | 695 | C# |
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace Axe.Cli.Parser.Test.Helpers
{
static class ParsingResultTestExtensions
{
[SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local")]
public static void AssertError(
this ArgsParsingResult result,
ArgsParsingErrorCode code,
string trigger)
{
Assert.False(result.IsSuccess);
Assert.Null(result.Command);
Assert.NotNull(result.Error);
Assert.Equal(code, result.Error.Code);
Assert.Equal(trigger, result.Error.Trigger);
}
public static void AssertSuccess(this ArgsParsingResult result)
{
Assert.True(result.IsSuccess);
Assert.NotNull(result.Command);
}
}
} | 30.481481 | 85 | 0.62819 | [
"MIT"
] | AxeDotNet/Axe.Cli | test/Axe.Cli.Parser.Test/Helpers/ParsingResultTestExtensions.cs | 825 | C# |
using Prism.Commands;
using Prism.Events;
using PrismWPFHoneys.Core.Types.Events;
using PrismWPFHoneys.Core.Types.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Prism_WPF_Honeys.ViewModels
{
public class LoginViewModel
{
private IEventAggregator _ea;
public LoginViewModel(IEventAggregator ea)
{
_ea = ea;
//TODO: Do login tasks
}
private DelegateCommand _acceptCommand;
public DelegateCommand AcceptCommand =>
_acceptCommand ?? (_acceptCommand = new DelegateCommand(ExecuteAcceptCommand));
void ExecuteAcceptCommand()
{
FakeLoginTask();
}
private void FakeLoginTask()
{
Thread tCalendar = new Thread(new ThreadStart(ThreadCalendar));
Thread tContacts = new Thread(new ThreadStart(ThreadContacts));
Thread tMail = new Thread(new ThreadStart(ThreadMail));
tCalendar.Start();
tContacts.Start();
tMail.Start();
}
private void ThreadCalendar()
{
//Thread.Sleep(3000);
_ea.GetEvent<OnModuleInitializedEvent>().Publish(AppModuleNames.CalendarModuleName);
}
private void ThreadContacts()
{
//Thread.Sleep(6000);
_ea.GetEvent<OnModuleInitializedEvent>().Publish(AppModuleNames.ContactsModuleName);
}
private void ThreadMail()
{
_ea.GetEvent<OnModuleInitializedEvent>().Publish(AppModuleNames.MailModuleName);
}
}
}
| 27.639344 | 96 | 0.630486 | [
"MIT"
] | Serchland/Prism-WPF-Honeys | Prism WPF Honeys/ViewModels/LoginViewModel.cs | 1,688 | 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 Microsoft.DotNet.XHarness.CLI.CommandArguments.Wasm;
internal class NoIncognitoArgument : SwitchArgument
{
public NoIncognitoArgument()
: base("no-incognito", "Don't run in incognito mode", false)
{
}
}
| 31.357143 | 71 | 0.738041 | [
"MIT"
] | jkoritzinsky/xharness | src/Microsoft.DotNet.XHarness.CLI/CommandArguments/WASM/Arguments/NoIncognitoArgument.cs | 441 | 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.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.SimpleNotificationService.Model
{
///<summary>
/// AmazonSimpleNotificationService exception
/// </summary>
public class InternalErrorException : AmazonSimpleNotificationServiceException
{
/// <summary>
/// Constructs a new InternalErrorException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InternalErrorException(string message)
: base(message) {}
public InternalErrorException(string message, Exception innerException)
: base(message, innerException) {}
public InternalErrorException(Exception innerException)
: base(innerException) {}
public InternalErrorException(string message, Exception innerException, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, RequestId, statusCode) {}
public InternalErrorException(string message, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, RequestId, statusCode) {}
}
}
| 38.411765 | 164 | 0.684022 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.SimpleNotificationService/Model/InternalErrorException.cs | 1,959 | C# |
namespace Lupus_Titanium {
partial class FindRequestsPanel {
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle8 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle9 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle10 = new System.Windows.Forms.DataGridViewCellStyle();
this.pnlFindBorder = new System.Windows.Forms.Panel();
this.rtxtFind = new System.Windows.Forms.RichTextBox();
this.btnFindNext = new System.Windows.Forms.Button();
this.dgvFindResults = new System.Windows.Forms.DataGridView();
this.clmResult = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.lblFound = new System.Windows.Forms.Label();
this.pnlFindBorder.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvFindResults)).BeginInit();
this.SuspendLayout();
//
// pnlFindBorder
//
this.pnlFindBorder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pnlFindBorder.BackColor = System.Drawing.Color.White;
this.pnlFindBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pnlFindBorder.Controls.Add(this.rtxtFind);
this.pnlFindBorder.Location = new System.Drawing.Point(6, 4);
this.pnlFindBorder.Name = "pnlFindBorder";
this.pnlFindBorder.Padding = new System.Windows.Forms.Padding(1);
this.pnlFindBorder.Size = new System.Drawing.Size(437, 24);
this.pnlFindBorder.TabIndex = 36;
this.pnlFindBorder.Enter += new System.EventHandler(this.pnlFindBorder_Enter);
//
// rtxtFind
//
this.rtxtFind.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.rtxtFind.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtxtFind.Location = new System.Drawing.Point(4, 4);
this.rtxtFind.Multiline = false;
this.rtxtFind.Name = "rtxtFind";
this.rtxtFind.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
this.rtxtFind.Size = new System.Drawing.Size(430, 15);
this.rtxtFind.TabIndex = 31;
this.rtxtFind.Text = "";
this.rtxtFind.WordWrap = false;
this.rtxtFind.TextChanged += new System.EventHandler(this.rtxtFind_TextChanged);
this.rtxtFind.KeyUp += new System.Windows.Forms.KeyEventHandler(this.rtxtFind_KeyUp);
//
// btnFindNext
//
this.btnFindNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnFindNext.AutoSize = true;
this.btnFindNext.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnFindNext.BackColor = System.Drawing.Color.White;
this.btnFindNext.Enabled = false;
this.btnFindNext.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnFindNext.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnFindNext.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnFindNext.Location = new System.Drawing.Point(449, 4);
this.btnFindNext.MaximumSize = new System.Drawing.Size(9999, 24);
this.btnFindNext.Name = "btnFindNext";
this.btnFindNext.Size = new System.Drawing.Size(45, 24);
this.btnFindNext.TabIndex = 38;
this.btnFindNext.Text = "Next";
this.btnFindNext.UseVisualStyleBackColor = false;
this.btnFindNext.Click += new System.EventHandler(this.btnFindNext_Click);
//
// dgvFindResults
//
this.dgvFindResults.AllowUserToAddRows = false;
this.dgvFindResults.AllowUserToDeleteRows = false;
this.dgvFindResults.AllowUserToResizeRows = false;
dataGridViewCellStyle6.BackColor = System.Drawing.Color.White;
this.dgvFindResults.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle6;
this.dgvFindResults.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dgvFindResults.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.dgvFindResults.BackgroundColor = System.Drawing.Color.White;
this.dgvFindResults.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.dgvFindResults.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dgvFindResults.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
dataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle7.BackColor = System.Drawing.Color.White;
dataGridViewCellStyle7.Font = new System.Drawing.Font("Consolas", 9.75F);
dataGridViewCellStyle7.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle7.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle7.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvFindResults.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle7;
this.dgvFindResults.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dgvFindResults.ColumnHeadersVisible = false;
this.dgvFindResults.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.clmResult});
dataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle8.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle8.Font = new System.Drawing.Font("Consolas", 9.75F);
dataGridViewCellStyle8.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle8.SelectionBackColor = System.Drawing.SystemColors.ControlDark;
dataGridViewCellStyle8.SelectionForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle8.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dgvFindResults.DefaultCellStyle = dataGridViewCellStyle8;
this.dgvFindResults.EnableHeadersVisualStyles = false;
this.dgvFindResults.Font = new System.Drawing.Font("Consolas", 9.75F);
this.dgvFindResults.Location = new System.Drawing.Point(6, 53);
this.dgvFindResults.MultiSelect = false;
this.dgvFindResults.Name = "dgvFindResults";
this.dgvFindResults.ReadOnly = true;
this.dgvFindResults.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
dataGridViewCellStyle9.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle9.BackColor = System.Drawing.Color.White;
dataGridViewCellStyle9.Font = new System.Drawing.Font("Consolas", 9.75F);
dataGridViewCellStyle9.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle9.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle9.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle9.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvFindResults.RowHeadersDefaultCellStyle = dataGridViewCellStyle9;
this.dgvFindResults.RowHeadersVisible = false;
this.dgvFindResults.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
dataGridViewCellStyle10.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(250)))), ((int)(((byte)(250)))), ((int)(((byte)(250)))));
this.dgvFindResults.RowsDefaultCellStyle = dataGridViewCellStyle10;
this.dgvFindResults.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvFindResults.Size = new System.Drawing.Size(488, 80);
this.dgvFindResults.TabIndex = 39;
this.dgvFindResults.VirtualMode = true;
this.dgvFindResults.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.dgvFindResults_CellValueNeeded);
this.dgvFindResults.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvFindResults_RowEnter);
this.dgvFindResults.SelectionChanged += new System.EventHandler(this.dgvFindResults_SelectionChanged);
this.dgvFindResults.Enter += new System.EventHandler(this.dgvFindResults_Enter);
this.dgvFindResults.Leave += new System.EventHandler(this.dgvFindResults_Leave);
//
// clmResult
//
this.clmResult.HeaderText = "Result";
this.clmResult.Name = "clmResult";
this.clmResult.ReadOnly = true;
this.clmResult.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.clmResult.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.clmResult.Width = 5;
//
// lblFound
//
this.lblFound.AutoSize = true;
this.lblFound.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.lblFound.Location = new System.Drawing.Point(6, 37);
this.lblFound.Name = "lblFound";
this.lblFound.Size = new System.Drawing.Size(43, 13);
this.lblFound.TabIndex = 40;
this.lblFound.Text = "0 found";
//
// FindRequestsPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(254)))), ((int)(((byte)(254)))));
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Controls.Add(this.lblFound);
this.Controls.Add(this.dgvFindResults);
this.Controls.Add(this.btnFindNext);
this.Controls.Add(this.pnlFindBorder);
this.DoubleBuffered = true;
this.Name = "FindRequestsPanel";
this.Size = new System.Drawing.Size(500, 35);
this.VisibleChanged += new System.EventHandler(this.FindRequestsPanel_VisibleChanged);
this.pnlFindBorder.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgvFindResults)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel pnlFindBorder;
private System.Windows.Forms.RichTextBox rtxtFind;
private System.Windows.Forms.Button btnFindNext;
private System.Windows.Forms.DataGridView dgvFindResults;
private System.Windows.Forms.DataGridViewTextBoxColumn clmResult;
private System.Windows.Forms.Label lblFound;
}
}
| 66.024631 | 171 | 0.670596 | [
"MIT"
] | sizingservers/Lupus-Titanium | Lupus-Titanium/Controls and dialogs/FindRequestsPanel.Designer.cs | 13,405 | C# |
using KFDtool.Adapter.Protocol.Adapter;
using KFDtool.P25.DataLinkIndependent;
using KFDtool.P25.DeviceProtocol;
using KFDtool.P25.Kmm;
using KFDtool.P25.NetworkProtocol;
using KFDtool.P25.Partition;
using KFDtool.P25.ThreeWire;
using KFDtool.P25.TransferConstructs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KFDtool.P25.ManualRekey
{
public class ManualRekeyApplication
{
private static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
private bool WithPreamble { get; set; }
private byte Mfid { get; set; }
private IDeviceProtocol DeviceProtocol;
public ManualRekeyApplication(AdapterProtocol adapterProtocol)
{
DeviceProtocol = new ThreeWireProtocol(adapterProtocol);
WithPreamble = false;
Mfid = 0x00;
}
public ManualRekeyApplication(UdpProtocol udpProtocol, bool motVariant)
{
DeviceProtocol = new DataLinkIndependentProtocol(udpProtocol, motVariant);
WithPreamble = true;
Mfid = motVariant ? (byte)0x90 : (byte)0x00;
}
private void Begin()
{
DeviceProtocol.SendKeySignature();
DeviceProtocol.InitSession();
}
private KmmBody TxRxKmm(KmmBody commandKmmBody)
{
KmmFrame commandKmmFrame = new KmmFrame(commandKmmBody);
byte[] toRadio = WithPreamble ? commandKmmFrame.ToBytesWithPreamble(Mfid) : commandKmmFrame.ToBytes();
byte[] fromRadio = DeviceProtocol.PerformKmmTransfer(toRadio);
KmmFrame responseKmmFrame = new KmmFrame(WithPreamble, fromRadio);
return responseKmmFrame.KmmBody;
}
private void End()
{
DeviceProtocol.EndSession();
}
public void Keyload(List<CmdKeyItem> keyItems)
{
List<List<CmdKeyItem>> keyGroups = KeyPartitioner.PartitionKeys(keyItems);
Begin();
try
{
InventoryCommandListActiveKsetIds cmdKmmBody1 = new InventoryCommandListActiveKsetIds();
KmmBody rspKmmBody1 = TxRxKmm(cmdKmmBody1);
int activeKeysetId = 0;
if (rspKmmBody1 is InventoryResponseListActiveKsetIds)
{
InventoryResponseListActiveKsetIds kmm = rspKmmBody1 as InventoryResponseListActiveKsetIds;
Logger.Debug("number of active keyset ids: {0}", kmm.KsetIds.Count);
for (int i = 0; i < kmm.KsetIds.Count; i++)
{
Logger.Debug("* keyset id index {0} *", i);
Logger.Debug("keyset id: {0} (dec), {0:X} (hex)", kmm.KsetIds[i]);
}
// TODO support more than one crypto group
if (kmm.KsetIds.Count > 0)
{
activeKeysetId = kmm.KsetIds[0];
}
else
{
activeKeysetId = 1; // to match KVL3000+ R3.53.03 behavior
}
}
else if (rspKmmBody1 is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = rspKmmBody1 as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
foreach (List<CmdKeyItem> keyGroup in keyGroups)
{
ModifyKeyCommand modifyKeyCommand = new ModifyKeyCommand();
// TODO support more than one crypto group
if (keyGroup[0].UseActiveKeyset && !keyGroup[0].IsKek)
{
modifyKeyCommand.KeysetId = activeKeysetId;
}
else if (keyGroup[0].UseActiveKeyset && keyGroup[0].IsKek)
{
modifyKeyCommand.KeysetId = 0xFF; // to match KVL3000+ R3.53.03 behavior
}
else
{
modifyKeyCommand.KeysetId = keyGroup[0].KeysetId;
}
modifyKeyCommand.AlgorithmId = keyGroup[0].AlgorithmId;
foreach (CmdKeyItem key in keyGroup)
{
Logger.Debug(key.ToString());
KeyItem keyItem = new KeyItem();
keyItem.SLN = key.Sln;
keyItem.KeyId = key.KeyId;
keyItem.Key = key.Key.ToArray();
keyItem.KEK = key.IsKek;
keyItem.Erase = false;
modifyKeyCommand.KeyItems.Add(keyItem);
}
KmmBody rspKmmBody2 = TxRxKmm(modifyKeyCommand);
if (rspKmmBody2 is RekeyAcknowledgment)
{
RekeyAcknowledgment kmm = rspKmmBody2 as RekeyAcknowledgment;
Logger.Debug("number of key status: {0}", kmm.Keys.Count);
for (int i = 0; i < kmm.Keys.Count; i++)
{
KeyStatus status = kmm.Keys[i];
Logger.Debug("* key status index {0} *", i);
Logger.Debug("algorithm id: {0} (dec), {0:X} (hex)", status.AlgorithmId);
Logger.Debug("key id: {0} (dec), {0:X} (hex)", status.KeyId);
Logger.Debug("status: {0} (dec), {0:X} (hex)", status.Status);
if (status.Status != 0)
{
string statusDescr = OperationStatusExtensions.ToStatusString((OperationStatus)status.Status);
string statusReason = OperationStatusExtensions.ToReasonString((OperationStatus)status.Status);
throw new Exception(
string.Format(
"received unexpected key status{0}" +
"algorithm id: {1} (0x{1:X}){0}" +
"key id: {2} (0x{2:X}){0}" +
"status: {3} (0x{3:X}){0}" +
"status description: {4}{0}" +
"status reason: {5}",
Environment.NewLine, status.AlgorithmId, status.KeyId, status.Status, statusDescr, statusReason
)
);
}
}
}
else if (rspKmmBody2 is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = rspKmmBody2 as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("received unexpected kmm");
}
}
}
catch
{
End();
throw;
}
End();
}
public void EraseKeys(List<CmdKeyItem> keyItems)
{
List<List<CmdKeyItem>> keyGroups = KeyPartitioner.PartitionKeys(keyItems);
Begin();
try
{
InventoryCommandListActiveKsetIds cmdKmmBody1 = new InventoryCommandListActiveKsetIds();
KmmBody rspKmmBody1 = TxRxKmm(cmdKmmBody1);
int activeKeysetId = 0;
if (rspKmmBody1 is InventoryResponseListActiveKsetIds)
{
InventoryResponseListActiveKsetIds kmm = rspKmmBody1 as InventoryResponseListActiveKsetIds;
Logger.Debug("number of active keyset ids: {0}", kmm.KsetIds.Count);
for (int i = 0; i < kmm.KsetIds.Count; i++)
{
Logger.Debug("* keyset id index {0} *", i);
Logger.Debug("keyset id: {0} (dec), {0:X} (hex)", kmm.KsetIds[i]);
}
// TODO support more than one crypto group
if (kmm.KsetIds.Count > 0)
{
activeKeysetId = kmm.KsetIds[0];
}
else
{
activeKeysetId = 1; // to match KVL3000+ R3.53.03 behavior
}
}
else if (rspKmmBody1 is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = rspKmmBody1 as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
foreach (List<CmdKeyItem> keyGroup in keyGroups)
{
ModifyKeyCommand modifyKeyCommand = new ModifyKeyCommand();
// TODO support more than one crypto group
if (keyGroup[0].UseActiveKeyset && !keyGroup[0].IsKek)
{
modifyKeyCommand.KeysetId = activeKeysetId;
}
else if (keyGroup[0].UseActiveKeyset && keyGroup[0].IsKek)
{
modifyKeyCommand.KeysetId = 0xFF; // to match KVL3000+ R3.53.03 behavior
}
else
{
modifyKeyCommand.KeysetId = keyGroup[0].KeysetId;
}
modifyKeyCommand.AlgorithmId = 0x81; // to match KVL3000+ R3.53.03 behavior
foreach (CmdKeyItem key in keyGroup)
{
Logger.Debug(key.ToString());
KeyItem keyItem = new KeyItem();
keyItem.SLN = key.Sln;
keyItem.KeyId = 65535; // to match KVL3000+ R3.53.03 behavior
keyItem.Key = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; // to match KVL3000+ R3.53.03 behavior
keyItem.KEK = key.IsKek;
keyItem.Erase = true;
modifyKeyCommand.KeyItems.Add(keyItem);
}
KmmBody rspKmmBody2 = TxRxKmm(modifyKeyCommand);
if (rspKmmBody2 is RekeyAcknowledgment)
{
RekeyAcknowledgment kmm = rspKmmBody2 as RekeyAcknowledgment;
Logger.Debug("number of key status: {0}", kmm.Keys.Count);
for (int i = 0; i < kmm.Keys.Count; i++)
{
KeyStatus status = kmm.Keys[i];
Logger.Debug("* key status index {0} *", i);
Logger.Debug("algorithm id: {0} (dec), {0:X} (hex)", status.AlgorithmId);
Logger.Debug("key id: {0} (dec), {0:X} (hex)", status.KeyId);
Logger.Debug("status: {0} (dec), {0:X} (hex)", status.Status);
if (status.Status != 0)
{
string statusDescr = OperationStatusExtensions.ToStatusString((OperationStatus)status.Status);
string statusReason = OperationStatusExtensions.ToReasonString((OperationStatus)status.Status);
throw new Exception(
string.Format(
"received unexpected key status{0}" +
"algorithm id: {1} (0x{1:X}){0}" +
"key id: {2} (0x{2:X}){0}" +
"status: {3} (0x{3:X}){0}" +
"status description: {4}{0}" +
"status reason: {5}",
Environment.NewLine, status.AlgorithmId, status.KeyId, status.Status, statusDescr, statusReason
)
);
}
}
}
else if (rspKmmBody2 is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = rspKmmBody2 as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("received unexpected kmm");
}
}
}
catch
{
End();
throw;
}
End();
}
public void EraseAllKeys()
{
Begin();
try
{
ZeroizeCommand commandKmmBody = new ZeroizeCommand();
KmmBody responseKmmBody = TxRxKmm(commandKmmBody);
if (responseKmmBody is ZeroizeResponse)
{
Logger.Debug("zerozied");
}
else if (responseKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = responseKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
catch
{
End();
throw;
}
End();
}
public List<RspKeyInfo> ViewKeyInfo()
{
List<RspKeyInfo> result = new List<RspKeyInfo>();
Begin();
try
{
bool more = true;
int marker = 0;
while (more)
{
InventoryCommandListActiveKeys commandKmmBody = new InventoryCommandListActiveKeys();
commandKmmBody.InventoryMarker = marker;
commandKmmBody.MaxKeysRequested = 78;
KmmBody responseKmmBody = TxRxKmm(commandKmmBody);
if (responseKmmBody is InventoryResponseListActiveKeys)
{
InventoryResponseListActiveKeys kmm = responseKmmBody as InventoryResponseListActiveKeys;
marker = kmm.InventoryMarker;
Logger.Debug("inventory marker: {0}", marker);
if (marker == 0)
{
more = false;
}
Logger.Debug("number of keys returned: {0}", kmm.Keys.Count);
for (int i = 0; i < kmm.Keys.Count; i++)
{
KeyInfo info = kmm.Keys[i];
Logger.Debug("* key index {0} *", i);
Logger.Debug("keyset id: {0} (dec), {0:X} (hex)", info.KeySetId);
Logger.Debug("sln: {0} (dec), {0:X} (hex)", info.SLN);
Logger.Debug("algorithm id: {0} (dec), {0:X} (hex)", info.AlgorithmId);
Logger.Debug("key id: {0} (dec), {0:X} (hex)", info.KeyId);
RspKeyInfo res = new RspKeyInfo();
res.KeysetId = info.KeySetId;
res.Sln = info.SLN;
res.AlgorithmId = info.AlgorithmId;
res.KeyId = info.KeyId;
result.Add(res);
}
}
else if (responseKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = responseKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
}
catch
{
End();
throw;
}
End();
return result;
}
public int ViewKmfRsi()
{
int result = new int();
Begin();
try
{
InventoryCommandListKmfRsi commandKmmBody = new InventoryCommandListKmfRsi();
KmmBody responseKmmBody = TxRxKmm(commandKmmBody);
if (responseKmmBody is InventoryResponseListKmfRsi)
{
Logger.Debug("MNP response");
InventoryResponseListKmfRsi kmm = responseKmmBody as InventoryResponseListKmfRsi;
result = kmm.KmfRsi;
}
else if (responseKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = responseKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
catch
{
End();
throw;
}
End();
return result;
}
public int ViewMnp()
{
int result = new int();
Begin();
try
{
InventoryCommandListMnp commandKmmBody = new InventoryCommandListMnp();
KmmBody responseKmmBody = TxRxKmm(commandKmmBody);
if (responseKmmBody is InventoryResponseListMnp)
{
Logger.Debug("MNP response");
InventoryResponseListMnp kmm = responseKmmBody as InventoryResponseListMnp;
result = kmm.MessageNumberPeriod;
}
else if (responseKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = responseKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
catch
{
End();
throw;
}
End();
return result;
}
public RspRsiInfo LoadConfig(int kmfRsi, int mnp)
{
RspRsiInfo result = new RspRsiInfo();
Begin();
try
{
LoadConfigCommand cmdKmmBody = new LoadConfigCommand();
cmdKmmBody.KmfRsi = kmfRsi;
cmdKmmBody.MessageNumberPeriod = mnp;
KmmBody rspKmmBody = TxRxKmm(cmdKmmBody);
if (rspKmmBody is LoadConfigResponse)
{
LoadConfigResponse kmm = rspKmmBody as LoadConfigResponse;
result.RSI = kmm.RSI;
result.MN = kmm.MN;
result.Status = kmm.Status;
}
else if (rspKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = rspKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
catch
{
End();
throw;
}
End();
return result;
}
public RspRsiInfo ChangeRsi(int rsiOld, int rsiNew, int mnp)
{
RspRsiInfo result = new RspRsiInfo();
Begin();
try
{
ChangeRsiCommand cmdKmmBody = new ChangeRsiCommand();
cmdKmmBody.RsiOld = rsiOld;
cmdKmmBody.RsiNew = rsiNew;
cmdKmmBody.MessageNumber = mnp;
KmmBody rspKmmBody = TxRxKmm(cmdKmmBody);
if (rspKmmBody is ChangeRsiResponse)
{
ChangeRsiResponse kmm = rspKmmBody as ChangeRsiResponse;
result.RSI = rsiNew;
result.MN = mnp;
result.Status = kmm.Status;
}
else if (rspKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = rspKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
catch
{
End();
throw;
}
End();
return result;
}
public List<RspRsiInfo> ViewRsiItems()
{
List<RspRsiInfo> result = new List<RspRsiInfo>();
Begin();
try
{
bool more = true;
int marker = 0;
while (more)
{
InventoryCommandListRsiItems commandKmmBody = new InventoryCommandListRsiItems();
KmmBody responseKmmBody = TxRxKmm(commandKmmBody);
if (responseKmmBody is InventoryResponseListRsiItems)
{
InventoryResponseListRsiItems kmm = responseKmmBody as InventoryResponseListRsiItems;
Logger.Debug("inventory marker: {0}", marker);
if (marker == 0)
{
more = false;
}
Logger.Debug("number of RSIs returned: {0}", kmm.RsiItems.Count);
for (int i = 0; i < kmm.RsiItems.Count; i++)
{
RsiItem item = kmm.RsiItems[i];
Logger.Debug("* rsi index {0} *", i);
Logger.Debug("rsi id: {0} (dec), {0:X} (hex)", item.RSI);
Logger.Debug("mn: {0} (dec), {0:X} (hex)", item.MessageNumber);
RspRsiInfo res = new RspRsiInfo();
res.RSI = (int)item.RSI;
res.MN = item.MessageNumber;
result.Add(res);
}
}
else if (responseKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = responseKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
}
catch
{
End();
throw;
}
End();
return result;
}
public List<RspKeysetInfo> ViewKeysetTaggingInfo()
{
List<RspKeysetInfo> result = new List<RspKeysetInfo>();
Begin();
try
{
InventoryCommandListKeysetTaggingInfo commandKmmBody = new InventoryCommandListKeysetTaggingInfo();
KmmBody responseKmmBody = TxRxKmm(commandKmmBody);
if (responseKmmBody is InventoryResponseListKeysetTaggingInfo)
{
Logger.Debug("KeysetTaggingInfo response");
InventoryResponseListKeysetTaggingInfo kmm = responseKmmBody as InventoryResponseListKeysetTaggingInfo;
for (int i = 0; i < kmm.KeysetItems.Count; i++)
{
KeysetItem item = kmm.KeysetItems[i];
RspKeysetInfo res = new RspKeysetInfo();
res.KeysetId = item.KeysetId;
res.KeysetName = item.KeysetName;
res.KeysetType = item.KeysetType;
res.ActivationDateTime = item.ActivationDateTime;
res.ReservedField = item.ReservedField;
result.Add(res);
}
}
else if (responseKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = responseKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
catch
{
End();
throw;
}
End();
return result;
}
public RspChangeoverInfo ActivateKeyset(int keysetSuperseded, int keysetActivated)
{
RspChangeoverInfo result = new RspChangeoverInfo();
Begin();
try
{
ChangeoverCommand cmdKmmBody = new ChangeoverCommand();
cmdKmmBody.KeysetIdSuperseded = keysetSuperseded;
cmdKmmBody.KeysetIdActivated = keysetActivated;
KmmBody rspKmmBody = TxRxKmm(cmdKmmBody);
if (rspKmmBody is ChangeoverResponse)
{
ChangeoverResponse kmm = rspKmmBody as ChangeoverResponse;
result.KeysetIdSuperseded = kmm.KeysetIdSuperseded;
result.KeysetIdActivated = kmm.KeysetIdActivated;
}
else if (rspKmmBody is NegativeAcknowledgment)
{
NegativeAcknowledgment kmm = rspKmmBody as NegativeAcknowledgment;
string statusDescr = OperationStatusExtensions.ToStatusString(kmm.Status);
string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
}
else
{
throw new Exception("unexpected kmm");
}
}
catch
{
End();
throw;
}
End();
return result;
}
public void LoadAuthenticationKey()
{
throw new NotImplementedException();
}
public void DeleteAuthenticationKey()
{
throw new NotImplementedException();
}
public void ViewSuidInfo()
{
throw new NotImplementedException();
}
public void ViewActiveSuidInfo()
{
throw new NotImplementedException();
}
}
}
| 38.436019 | 187 | 0.467016 | [
"MIT"
] | DeltaBravo15/KFDtool | sw/control/KFDtool.P25/ManualRekey/ManualRekeyApplication.cs | 32,442 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AsVectorUInt32()
{
var test = new VectorAs__AsVectorUInt32();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorAs__AsVectorUInt32
{
private static readonly int LargestVectorSize = 16;
private static readonly int VectorElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int NumericsElementCount = Unsafe.SizeOf<Vector<UInt32>>() / sizeof(UInt32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Vector128<UInt32> value;
value = Vector128.Create((uint)TestLibrary.Generator.GetUInt32());
Vector<UInt32> result = value.AsVector();
ValidateResult(result, value);
value = result.AsVector128();
ValidateResult(value, result);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Vector128<UInt32> value;
value = Vector128.Create((uint)TestLibrary.Generator.GetUInt32());
object Result = typeof(Vector128)
.GetMethod(nameof(Vector128.AsVector))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector<UInt32>)(Result), value);
value = (Vector128<UInt32>)typeof(Vector128)
.GetMethods()
.Where((methodInfo) => {
if (methodInfo.Name == nameof(Vector128.AsVector128))
{
var parameters = methodInfo.GetParameters();
return (parameters.Length == 1) &&
(parameters[0].ParameterType.IsGenericType) &&
(parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(Vector<>));
}
return false;
})
.Single()
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { Result });
ValidateResult(value, (Vector<UInt32>)(Result));
}
private void ValidateResult(Vector<UInt32> result, Vector128<UInt32> value, [CallerMemberName] string method = "")
{
UInt32[] resultElements = new UInt32[NumericsElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result);
UInt32[] valueElements = new UInt32[VectorElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, method);
}
private void ValidateResult(Vector128<UInt32> result, Vector<UInt32> value, [CallerMemberName] string method = "")
{
UInt32[] resultElements = new UInt32[VectorElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result);
UInt32[] valueElements = new UInt32[NumericsElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, method);
}
private void ValidateResult(UInt32[] resultElements, UInt32[] valueElements, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements.Length <= valueElements.Length)
{
for (var i = 0; i < resultElements.Length; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
}
else
{
for (var i = 0; i < valueElements.Length; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
for (var i = valueElements.Length; i < resultElements.Length; i++)
{
if (resultElements[i] != default)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt32>.AsVector: {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 40.588957 | 124 | 0.522521 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/General/Vector128_1/AsVector.UInt32.cs | 6,616 | C# |
using ApplicationApp.Interfaces;
using Domain.Interfaces.InterfaceProduct;
using Domain.Interfaces.InterfaceServices;
using Entities.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ApplicationApp.OpenApp
{
public class AppProduct : InterfaceProductApp
{
IProduct _iproduct;
IServiceProduct _iserviceProduct;
public AppProduct(IProduct iproduct,IServiceProduct iserviceProduct)
{
_iproduct = iproduct;
_iserviceProduct = iserviceProduct;
}
public async Task Add(Product Objeto)
{
await _iproduct.Add(Objeto);
}
public async Task Delete(Product Objeto)
{
await _iproduct.Delete(Objeto);
}
public async Task<Product> GetEntityById(int Id)
{
return await _iproduct.GetEntityById(Id);
}
public async Task<List<Product>> List()
{
return await _iproduct.List();
}
public async Task Update(Product Objeto)
{
await _iproduct.Update(Objeto);
}
#region Metodos Customizados
public async Task AddProduct(Product product)
{
await _iserviceProduct.AddProduct(product);
}
public async Task UpdateProduct(Product product)
{
await _iserviceProduct.UpdateProduct(product);
}
#endregion
}
}
| 25.423729 | 76 | 0.62 | [
"MIT"
] | DeivideSilva/Asp.NetCore | ProjetoDDD/ApplicationApp/OpenApp/AppProduct.cs | 1,502 | C# |
namespace RevolutAPI.Models.Counterparties
{
public class ProfileType
{
public static string BUSINESS = "business";
public static string PERSONAL = "personal";
}
} | 24 | 51 | 0.671875 | [
"MIT"
] | Code-Around/RevolutAPI | src/RevolutAPI/RevolutAPI/Models/Counterparties/ProfileType.cs | 194 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Snowlight.Game.Spaces
{
public enum UserMovementNode
{
Blocked,
Walkable,
WalkableEndOfRoute
}
}
| 15.4 | 33 | 0.679654 | [
"MIT"
] | DaLoE99/Servidores-DaLoE | 3/BoomBang/Game/Spaces/UserMovementNode.cs | 233 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using NearForums.Web.State;
using System.Web;
using NearForums.Configuration;
using NearForums.Web.Extensions;
namespace NearForums.Web.UI
{
public class TemplatedLayout : BaseViewPage
{
protected virtual TemplateState Template
{
get
{
if (Session.TemplatePreviewed != null)
{
return Session.TemplatePreviewed;
}
return Cache.Template;
}
}
protected virtual int? TemplatePreviewId
{
get
{
int? id = null;
if (Session.TemplatePreviewed != null)
{
id = Session.TemplatePreviewed.Id;
}
return id;
}
}
public override void ExecutePageHierarchy()
{
base.ExecutePageHierarchy();
foreach (TemplateState.TemplateItem item in Template.Items)
{
WriteItem(item);
}
}
protected virtual void WriteItem(TemplateState.TemplateItem item)
{
if (item.Type == TemplateState.TemplateItemType.Text)
{
WriteLiteral(item.Value);
}
else if (item.Type == TemplateState.TemplateItemType.Container)
{
switch (item.Value.ToUpper()) //Name
{
case "BODYCONTAINER":
Write(RenderBody());
WriteTemplatePreview();
break;
case "HEADCONTAINER":
Write(Html.Partial("HeadContainer"));
if (IsSectionDefined("Head"))
{
Write(RenderSection("Head"));
}
break;
}
}
else if (item.Type == TemplateState.TemplateItemType.Partial)
{
Write(Html.Partial(item.Value, ViewData));
}
}
/// <summary>
/// If the template is beeing previewed, renders a special partial view
/// </summary>
protected virtual void WriteTemplatePreview()
{
if (TemplatePreviewId != null)
{
Write(Html.Partial("~/Views/Templates/PreviewPartial.cshtml", ViewData));
}
}
}
}
| 21.456522 | 78 | 0.632219 | [
"MIT"
] | axence-inc/nearforums | solution/NearForums.Web/UI/TemplatedLayout.cs | 1,976 | C# |
using System;
using MFiles.VAF.Common;
using MFilesAPI;
namespace MFiles.VAF.Extensions
{
/// <summary>
/// Extension methods for the <see cref="MFSearchBuilder"/> class.
/// </summary>
// ReSharper disable once InconsistentNaming
public static partial class MFSearchBuilderExtensionMethods
{
/// <summary>
/// Adds a <see cref="SearchCondition"/> to the collection to find items with the given owner.
/// </summary>
/// <param name="searchBuilder">The <see cref="MFSearchBuilder"/> to add the condition to.</param>
/// <param name="owner">The owner item.</param>
/// <returns>The <paramref name="searchBuilder"/> provided, for chaining.</returns>
public static MFSearchBuilder Owner
(
this MFSearchBuilder searchBuilder,
ObjVerEx owner
)
{
// Sanity.
if (null == owner)
throw new ArgumentNullException(nameof(owner));
// Use the other overload.
return searchBuilder.Owner(owner.ObjVer);
}
/// <summary>
/// Adds a <see cref="SearchCondition"/> to the collection to find items with the given owner.
/// </summary>
/// <param name="searchBuilder">The <see cref="MFSearchBuilder"/> to add the condition to.</param>
/// <param name="owner">The owner item.</param>
/// <returns>The <paramref name="searchBuilder"/> provided, for chaining.</returns>
public static MFSearchBuilder Owner
(
this MFSearchBuilder searchBuilder,
ObjVer owner
)
{
// Sanity.
if (null == owner)
throw new ArgumentNullException(nameof(owner));
// Use the other overload.
return searchBuilder.Owner(owner.ObjID);
}
/// <summary>
/// Adds a <see cref="SearchCondition"/> to the collection to find items with the given owner.
/// </summary>
/// <param name="searchBuilder">The <see cref="MFSearchBuilder"/> to add the condition to.</param>
/// <param name="owner">The owner item.</param>
/// <returns>The <paramref name="searchBuilder"/> provided, for chaining.</returns>
public static MFSearchBuilder Owner
(
this MFSearchBuilder searchBuilder,
ObjID objID
)
{
// Sanity.
if (null == objID)
throw new ArgumentNullException(nameof(objID));
// Get the owner object type.
var ownerObjType = searchBuilder
.Vault
.ObjectTypeOperations
.GetObjectType(objID.Type);
// Use the other method.
return searchBuilder.AddPropertyValueSearchCondition
(
ownerObjType.OwnerPropertyDef,
MFDataType.MFDatatypeLookup, // Owner must be single-select
objID.ID,
MFConditionType.MFConditionTypeEqual
);
}
}
}
| 30.206897 | 101 | 0.668189 | [
"MIT"
] | CraigHawker/VAF.Extensions.Community | MFiles.VAF.Extensions/ExtensionMethods/MFSearchBuilderExtensionMethods/Owner.cs | 2,630 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM.IEC61968.LoadControl;
using TTC2017.SmartGrids.CIM.IEC61968.Metering;
using TTC2017.SmartGrids.CIM.IEC61968.WiresExt;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Generation.GenerationDynamics;
using TTC2017.SmartGrids.CIM.IEC61970.Generation.Production;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.EnergyScheduling;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfLoadControl;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations;
using TTC2017.SmartGrids.CIM.IEC61970.LoadModel;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
using TTC2017.SmartGrids.CIM.IEC61970.Outage;
using TTC2017.SmartGrids.CIM.IEC61970.Protection;
using TTC2017.SmartGrids.CIM.IEC61970.StateVariables;
namespace TTC2017.SmartGrids.CIM.IEC61970.Wires
{
/// <summary>
/// The public interface for ReactiveCapabilityCurve
/// </summary>
[DefaultImplementationTypeAttribute(typeof(ReactiveCapabilityCurve))]
[XmlDefaultImplementationTypeAttribute(typeof(ReactiveCapabilityCurve))]
public interface IReactiveCapabilityCurve : IModelElement, ICurve
{
/// <summary>
/// The hydrogenPressure property
/// </summary>
float HydrogenPressure
{
get;
set;
}
/// <summary>
/// The coolantTemperature property
/// </summary>
float CoolantTemperature
{
get;
set;
}
/// <summary>
/// The InitiallyUsedBySynchronousMachines property
/// </summary>
IOrderedSetExpression<ISynchronousMachine> InitiallyUsedBySynchronousMachines
{
get;
}
/// <summary>
/// The SynchronousMachines property
/// </summary>
IOrderedSetExpression<ISynchronousMachine> SynchronousMachines
{
get;
}
/// <summary>
/// Gets fired before the HydrogenPressure property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> HydrogenPressureChanging;
/// <summary>
/// Gets fired when the HydrogenPressure property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> HydrogenPressureChanged;
/// <summary>
/// Gets fired before the CoolantTemperature property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CoolantTemperatureChanging;
/// <summary>
/// Gets fired when the CoolantTemperature property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CoolantTemperatureChanged;
}
}
| 33.646018 | 96 | 0.666491 | [
"MIT"
] | georghinkel/ttc2017smartGrids | generator/Schema/IEC61970/Wires/IReactiveCapabilityCurve.cs | 3,804 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Xamarin.Interactive.Core;
using Xamarin.Interactive.Serialization;
namespace Xamarin.Interactive.Client.Web.Controllers
{
[Route ("/api/identify")]
public sealed class AgentIdentificationController : Controller
{
[HttpPost]
public IActionResult Index (
[FromQuery (Name = "token")] string token)
{
// Note: unfortunately cannot do '[FromBody] AgentIdentity' because
// ASP.NET Core requires everything to be public for model binding,
// and AgentIdentity is intentionally internal.
var identity = (AgentIdentity)InteractiveJsonSerializerSettings
.SharedInstance
.CreateSerializer ()
.Deserialize (Request.Body);
if (ClientApp.SharedInstance.AgentIdentificationManager.RespondToAgentIdentityRequest (
Guid.Parse (token),
identity))
return Ok ();
return NotFound ();
}
}
} | 31.837838 | 99 | 0.640068 | [
"MIT"
] | Bhaskers-Blu-Org2/workbooks | Clients/Xamarin.Interactive.Client.Web/Controllers/AgentIdentificationController.cs | 1,178 | C# |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using Avalonia.Cairo.Media;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Gtk;
using DrawingContext = Avalonia.Media.DrawingContext;
namespace Avalonia.Cairo
{
using global::Cairo;
/// <summary>
/// A cairo render target.
/// </summary>
public class RenderTarget : IRenderTarget
{
private readonly Surface _surface;
private readonly Func<Gdk.Drawable> _drawableAccessor;
/// <summary>
/// Initializes a new instance of the <see cref="RenderTarget"/> class.
/// </summary>
/// <param name="window">The window.</param>
/// <param name="width">The width of the window.</param>
/// <param name="height">The height of the window.</param>
public RenderTarget(Func<Gdk.Drawable> drawable)
{
_drawableAccessor = drawable;
}
public RenderTarget(ImageSurface surface)
{
_surface = surface;
}
/// <summary>
/// Creates a cairo surface that targets a platform-specific resource.
/// </summary>
/// <returns>A surface wrapped in an <see cref="Avalonia.Media.DrawingContext"/>.</returns>
public DrawingContext CreateDrawingContext() => new DrawingContext(CreateMediaDrawingContext());
public IDrawingContextImpl CreateMediaDrawingContext()
{
if (_drawableAccessor != null)
return new Media.DrawingContext(_drawableAccessor());
if (_surface != null)
return new Media.DrawingContext(_surface);
throw new InvalidOperationException("Unspecified render target");
}
public void Dispose() => _surface?.Dispose();
}
}
| 32.65 | 104 | 0.642675 | [
"MIT"
] | KvanTTT/Avalonia | src/Gtk/Avalonia.Cairo/RenderTarget.cs | 1,959 | C# |
using BlazorBoilerplate.Infrastructure.Server;
using BlazorBoilerplate.Server.Managers;
using BlazorBoilerplate.Infrastructure.Storage.DataModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
namespace BlazorBoilerplate.Server.Tests.Managers
{
[TestFixture]
class ExternalAuthManagerTests
{
private ExternalAuthManager _externalAuthManager;
private Mock<IAccountManager> _accountManager;
private Mock<UserManager<ApplicationUser>> _userManager;
private Mock<SignInManager<ApplicationUser>> _signInManager;
private Mock<ILogger<ExternalAuthManager>> _logger;
private Mock<IConfiguration> _configuration;
[SetUp]
public void SetUp()
{
var userStore = new Mock<IUserStore<ApplicationUser>>();
var contextAccessor = new Mock<IHttpContextAccessor>();
var userPrincipalFactory = new Mock<IUserClaimsPrincipalFactory<ApplicationUser>>();
_accountManager = new Mock<IAccountManager>();
_userManager = new Mock<UserManager<ApplicationUser>>(userStore.Object, null, null, null, null, null, null, null, null);
_signInManager = new Mock<SignInManager<ApplicationUser>>(_userManager.Object, contextAccessor.Object, userPrincipalFactory.Object, null, null, null, null);
_logger = new Mock<ILogger<ExternalAuthManager>>();
_configuration = new Mock<IConfiguration>();
_externalAuthManager = new ExternalAuthManager(_accountManager.Object, _userManager.Object, _signInManager.Object, _logger.Object, _configuration.Object);
}
[Test]
public void SetupWorked()
{
Assert.Pass();
}
}
}
| 35.826923 | 168 | 0.712292 | [
"MIT"
] | Kayira150/blazor_sample | src/Tests/BlazorBoilerplate.Server.Tests/Managers/ExternalAuthManagerTests.cs | 1,865 | C# |
using System;
using ClaimsReserving.Models;
using ClaimsReserving.Services.Validation.Record;
using NUnit.Framework;
namespace ClaimsReserving.Tests.Services.Validation.Record
{
[TestFixture]
public class YearValidatorTests
{
private YearValidator _target;
[SetUp]
public void Setup()
{
_target = new YearValidator(new Defects());
}
[Test]
public void TwoErrorsWhenDevelopmentYearIs1066AndOlderThanOriginYear()
{
// Arrange
var record = new YearlyData {DevelopmentYear = 1066, OriginYear = 2000, ProductName = "Comp"};
// Act
var result = _target.Validate(record);
// Assert
Assert.That(result.Errors[0], Is.EqualTo("The Development Year 1066 is less than the Origin Year 2000"));
Assert.That(result.Errors[1], Is.EqualTo("The Development Year 1066 is too old"));
}
[Test]
public void WarningWhenOriginYearInTheFuture()
{
// It is also reasonable to consider this case an error - would normally check something like this with a B.A.
// Arrange
var record = new YearlyData { DevelopmentYear = 3000, OriginYear = 3000, ProductName = "Comp" };
// Act
var result = _target.Validate(record);
// Assert
Assert.That(result.Warnings[0], Is.EqualTo("The Origin Year 3000 post dates the year that this PC’s system clock is set to ("
+ DateTime.Now.Year + ")."));
}
}
}
| 32.269231 | 139 | 0.57211 | [
"Apache-2.0"
] | zombiecodekill/CSV-ClaimsReserving | ClaimsReserving.Tests/Services/Validation/Record/YearValidatorTests.cs | 1,682 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.Serialization;
namespace Microsoft.CSharp.RuntimeBinder
{
/// <summary>
/// Represents an error that occurs while processing a dynamic bind in the C# runtime binder. Exceptions of this type differ from <see cref="RuntimeBinderInternalCompilerException"/> in that
/// <see cref="RuntimeBinderException"/> represents a failure to bind in the sense of a usual compiler error, whereas <see cref="RuntimeBinderInternalCompilerException"/>
/// represents a malfunctioning of the runtime binder itself.
/// </summary>
[Serializable]
public class RuntimeBinderException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="RuntimeBinderException"/> class.
/// </summary>
public RuntimeBinderException() { }
/// <summary>
/// Initializes a new instance of the <see cref="RuntimeBinderException"/> class with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public RuntimeBinderException(string? message) : base(message) { }
/// <summary>
/// Initializes a new instance of the <see cref="RuntimeBinderException"/> class with a specified error message
/// and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
public RuntimeBinderException(string? message, Exception? innerException)
: base(message, innerException) { }
/// <summary>
/// Initializes a new instance of the <see cref="RuntimeBinderException"/> class with serialized data.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected RuntimeBinderException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
}
| 55.413043 | 194 | 0.690859 | [
"MIT"
] | belav/runtime | src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinderException.cs | 2,549 | C# |
using Microsoft.EntityFrameworkCore.Storage;
using Sio.Cms.Lib.Models.Cms;
using Sio.Cms.Lib.Services;
using Sio.Cms.Lib.ViewModels;
using Sio.Common.Helper;
using Sio.Domain.Core.ViewModels;
using Sio.Domain.Data.ViewModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using static Sio.Cms.Lib.SioEnums;
namespace Sio.Cms.Lib.ViewModels.SioSystem
{
public class SystemConfigurationViewModel
: ViewModelBase<SioCmsContext, SioConfiguration, SystemConfigurationViewModel>
{
#region Properties
#region Models
[Required]
[JsonProperty("keyword")]
public string Keyword { get; set; }
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("dataType")]
public SioDataType DataType { get; set; }
[JsonProperty("status")]
public SioContentStatus Status { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("createdDatetime")]
public DateTime CreatedDatetime { get; set; }
[JsonProperty("createdBy")]
public string CreatedBy { get; set; }
#endregion Models
#region Views
[JsonProperty("domain")]
public string Domain { get { return SioService.GetConfig<string>("Domain", Specificulture); } }
[JsonProperty("property")]
public DataValueViewModel Property { get; set; }
#endregion Views
#endregion Properties
#region Contructors
public SystemConfigurationViewModel()
: base()
{
}
public SystemConfigurationViewModel(SioConfiguration model, SioCmsContext _context = null, IDbContextTransaction _transaction = null)
: base(model, _context, _transaction)
{
}
#endregion Contructors
#region Overrides
public override SioConfiguration ParseModel(SioCmsContext _context = null, IDbContextTransaction _transaction = null)
{
if (CreatedDatetime == default(DateTime))
{
CreatedDatetime = DateTime.UtcNow;
}
return base.ParseModel(_context, _transaction);
}
public override void ExpandView(SioCmsContext _context = null, IDbContextTransaction _transaction = null)
{
Property = new DataValueViewModel() { DataType = DataType, Value = Value, Name = Keyword };
}
#endregion
#region Expands
public static async Task<RepositoryResponse<bool>> ImportConfigurations(List<SioConfiguration> arrConfiguration, string destCulture)
{
var result = new RepositoryResponse<bool>() { IsSucceed = true };
var context = new SioCmsContext();
var transaction = context.Database.BeginTransaction();
try
{
foreach (var item in arrConfiguration)
{
var lang = new SystemConfigurationViewModel(item, context, transaction);
lang.Specificulture = destCulture;
var saveResult = await lang.SaveModelAsync(false, context, transaction);
result.IsSucceed = result.IsSucceed && saveResult.IsSucceed;
if (!result.IsSucceed)
{
result.Exception = saveResult.Exception;
result.Errors = saveResult.Errors;
break;
}
}
UnitOfWorkHelper<SioCmsContext>.HandleTransaction(result.IsSucceed, true, transaction);
}
catch (Exception ex) // TODO: Add more specific exeption types instead of Exception only
{
var error = UnitOfWorkHelper<SioCmsContext>.HandleException<SystemConfigurationViewModel>(ex, true, transaction);
result.IsSucceed = false;
result.Errors = error.Errors;
result.Exception = error.Exception;
}
finally
{
//if current Context is Root
context?.Dispose();
}
return result;
}
#endregion
}
}
| 36.055556 | 142 | 0.587057 | [
"MIT"
] | Swastika-IO/Swastika | src/Sio.Cms.Lib/ViewModels/System/SystemConfigurationViewModel.cs | 4,543 | C# |
using Newtonsoft.Json;
namespace Our.Umbraco.Look.BackOffice.Models.Api
{
public class RebuildViewData
{
[JsonProperty("validIndexer")]
public bool ValidIndexer { get; set; } = false;
[JsonProperty("indexerName")]
public string IndexerName { get; set; }
}
}
| 21.785714 | 55 | 0.642623 | [
"MIT"
] | Hendy/umbraco-look | src/Our.Umbraco.Look.BackOffice/Models/Api/RebuildViewData.cs | 307 | C# |
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using gatling.Authorization;
using gatling.Authorization.Roles;
using gatling.Authorization.Users;
using gatling.Editions;
using gatling.MultiTenancy;
namespace gatling.Identity
{
public static class IdentityRegistrar
{
public static IdentityBuilder Register(IServiceCollection services)
{
services.AddLogging();
return services.AddAbpIdentity<Tenant, User, Role>()
.AddAbpTenantManager<TenantManager>()
.AddAbpUserManager<UserManager>()
.AddAbpRoleManager<RoleManager>()
.AddAbpEditionManager<EditionManager>()
.AddAbpUserStore<UserStore>()
.AddAbpRoleStore<RoleStore>()
.AddAbpLogInManager<LogInManager>()
.AddAbpSignInManager<SignInManager>()
.AddAbpSecurityStampValidator<SecurityStampValidator>()
.AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>()
.AddPermissionChecker<PermissionChecker>()
.AddDefaultTokenProviders();
}
}
}
| 35.878788 | 79 | 0.662162 | [
"MIT"
] | Dash-Nguyen/abp | aspnet-core/src/gatling.Core/Identity/IdentityRegistrar.cs | 1,186 | C# |
using System;
using System.Buffers.Binary;
using System.Text;
namespace BoschFirmwareTool
{
class FirmwareHeader
{
public static readonly int HeaderLength = 0x400;
public uint Magic { get; set; }
public uint Target { get; set; }
public uint Variant { get; set; }
public uint Version { get; set; }
public uint Length { get; set; }
public uint Base { get; set; }
public uint Checksum { get; set; } // Only present on the "root" header and subheaders. If headers are doubly nested, file header will not have a checksum.
public uint Type { get; set; }
public byte[] NegativeList { get; set; }
public byte[] Signature { get; set; }
public byte[] KeyBlob { get; set; }
public long Offset { get; set; } // Offset into the file which it was found.
public static FirmwareHeader Parse(ReadOnlySpan<byte> span)
{
if (span.Length < HeaderLength)
{
throw new ArgumentException($"input buffer too short", nameof(span));
}
return new FirmwareHeader
{
Magic = BinaryPrimitives.ReadUInt32BigEndian(span[0..4]),
Target = BinaryPrimitives.ReadUInt32BigEndian(span[4..8]),
Variant = BinaryPrimitives.ReadUInt32BigEndian(span[8..12]),
Version = BinaryPrimitives.ReadUInt32BigEndian(span[12..16]),
Length = BinaryPrimitives.ReadUInt32BigEndian(span[16..20]),
Base = BinaryPrimitives.ReadUInt32BigEndian(span[20..24]),
Checksum = BinaryPrimitives.ReadUInt32BigEndian(span[24..28]),
Type = BinaryPrimitives.ReadUInt32BigEndian(span[28..32]),
NegativeList = span[32..64].ToArray(),
Signature = span[76..332].ToArray(),
KeyBlob = span[588..844].ToArray()
};
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("Firmware Header\n");
sb.Append($"Target: {Target:X} ");
sb.Append($"Variant: {Variant:X} ");
sb.Append($"Version: {Version:X} ");
sb.Append($"Length: {Length:X}");
return sb.ToString();
}
}
}
| 38.081967 | 163 | 0.569522 | [
"BSD-3-Clause"
] | anvilsecure/BoschFirmwareTool | CLI/FirmwareHeader.cs | 2,325 | C# |
public class Solution {
public int ComputeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int answer = 0;
answer += (C - A) * (D - B);
answer += (G - E) * (H - F);
// minus overlap
int xOverlap = 0;
if (E <= A && A <= G) {
xOverlap = C <= G ? (C - A) : (G - A);
} else if (A <= E && E <= C) {
xOverlap = G <= C ? (G - E) : (C - E);
}
if (xOverlap > 0) {
int yOverlap = 0;
if (F <= B && B <= H) {
yOverlap = D <= H ? (D - B) : (H - B);
} else if (B <= F && F <= D) {
yOverlap = H <= D ? (H - F) : (D - F);
}
if (yOverlap > 0) {
answer -= xOverlap * yOverlap;
}
}
return answer;
}
}
| 31.925926 | 85 | 0.325986 | [
"MIT"
] | txchen/csharp-leet | solutions/Q223.cs | 862 | C# |
// Copyright © 2021 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
// Originally Based on https://github.com/CefNet/CefNet.DevTools.Protocol/blob/0a124720474a469b5cef03839418f5e1debaf2f0/CefNet.DevTools.Protocol/IEventProxy.cs
using System;
using System.IO;
using System.Threading;
namespace CefSharp.DevTools
{
/// <summary>
/// Event Proxy
/// </summary>
internal interface IEventProxy : IDisposable
{
/// <summary>
/// Raise Event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="eventName">event name</param>
/// <param name="stream">Stream containing JSON</param>
/// <param name="syncContext">SynchronizationContext</param>
void Raise(object sender, string eventName, Stream stream, SynchronizationContext syncContext);
}
}
| 33.714286 | 159 | 0.683263 | [
"BSD-3-Clause"
] | Bodekaer/CefSharp | CefSharp/DevTools/IEventProxy.cs | 945 | C# |
using System.Collections.Generic;
using FarsiLibrary.Utils;
namespace Iauq.Information.Models.Events
{
public class EventsModel : List<EventModel>
{
public EventsModel Add(long id, PersianDate holdingDate, string title, string slug, string description)
{
Add(new EventModel
{
Id = id,
HoldingDate = holdingDate,
Title = title,
Slug = slug,
Description = description
});
return this;
}
}
} | 27.727273 | 111 | 0.493443 | [
"MIT"
] | m-sadegh-sh/Iauq | src/Iauq.Information/Models/Events/EventsModel.cs | 610 | C# |
namespace Silky.Rpc.Security
{
public class ClaimTypes
{
public const string UserId = "http://silky.com/identity/claims/userid";
public const string UserName = "http://silky.com/identity/claims/username";
public const string Email = "http://silky.com/identity/claims/email";
public const string Phone = "http://silky.com/identity/claims/phone";
public const string Terminal = "http://silky.com/identity/claims/terminal";
public const string OrgId = "http://silky.com/identity/claims/OrgId";
public const string DataPermission = "http://silky.com/identity/claims/DataPermission";
public const string DataPermissionOrgIds = "http://silky.com/identity/claims/DataPermissionOrgIds";
public const string TenantId = "http://silky.com/identity/claims/TenantId";
public const string IsAllOrg = "http://silky.com/identity/claims/IsAllOrg";
public const string Expired = "exp";
}
} | 36.333333 | 107 | 0.690112 | [
"MIT"
] | scjjcs/silky | framework/src/Silky.Rpc/Security/ClaimTypes.cs | 981 | C# |
#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RVP
{
[CustomEditor(typeof(HoverWheel))]
[CanEditMultipleObjects]
public class HoverWheelEditor : Editor
{
bool isPrefab = false;
static bool showButtons = true;
public override void OnInspectorGUI()
{
GUIStyle boldFoldout = new GUIStyle(EditorStyles.foldout);
boldFoldout.fontStyle = FontStyle.Bold;
HoverWheel targetScript = (HoverWheel)target;
HoverWheel[] allTargets = new HoverWheel[targets.Length];
isPrefab = F.IsPrefab(targetScript);
for (int i = 0; i < targets.Length; i++)
{
Undo.RecordObject(targets[i], "Hover Wheel Change");
allTargets[i] = targets[i] as HoverWheel;
}
DrawDefaultInspector();
if (!isPrefab && targetScript.gameObject.activeInHierarchy)
{
showButtons = EditorGUILayout.Foldout(showButtons, "Quick Actions", boldFoldout);
EditorGUI.indentLevel++;
if (showButtons)
{
if (GUILayout.Button("Get Visual Wheel"))
{
foreach (HoverWheel curTarget in allTargets)
{
if (curTarget.transform.childCount > 0)
{
curTarget.visualWheel = curTarget.transform.GetChild(0);
}
else
{
Debug.LogWarning("No visual wheel found.", this);
}
}
}
}
EditorGUI.indentLevel--;
}
if (GUI.changed)
{
EditorUtility.SetDirty(targetScript);
}
}
}
}
#endif | 31.68254 | 97 | 0.477455 | [
"MIT"
] | DavidArppe/GameOff2020 | Packages/com.davidarppe.randomationvehiclephysicspackage/Scripts/Editors/HoverWheelEditor.cs | 1,998 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("Bodoconsult.Core.Windows")]
[assembly: AssemblyDescription("MS Windows related tools like icon extraction, reading data from url-files")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bodoconsult EDV-Dienstleistung GmbH")]
[assembly: AssemblyProduct("Bodoconsult.Core.Windows")]
[assembly: AssemblyCopyright("Copyright © Bodoconsult EDV-Dienstleistung GmbH 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("73414A82-A442-4FC9-8678-9B4BD3D84121")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| 44.888889 | 109 | 0.767327 | [
"MIT"
] | RobertLeisner/Bodoconsult.Core.Windows | Bodoconsult.Core.Windows/Properties/AssemblyInfo.cs | 1,634 | C# |
using System;
namespace Xyaneon.Bioinformatics.FASTA.Identifiers
{
/// <summary>
/// A GenBank FASTA identifier.
/// </summary>
public sealed class GenBankIdentifier : Identifier
{
/// <summary>
/// Initializes a new instance of the <see cref="GenBankIdentifier"/> class.
/// </summary>
/// <param name="accession">The accession number.</param>
/// <param name="locus">The locus number.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="accession"/> is <see langword="null"/>.
/// -or-
/// <paramref name="locus"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="accession"/> is empty or all whitespace.
/// -or-
/// <paramref name="locus"/> is empty or all whitespace.
/// </exception>
public GenBankIdentifier(string accession, string locus) : base(Constants.Codes.GenBank)
{
if (accession == null)
{
throw new ArgumentNullException(nameof(accession), "The accession number cannot be null.");
}
if (locus == null)
{
throw new ArgumentNullException(nameof(locus), "The locus number cannot be null.");
}
if (string.IsNullOrWhiteSpace(accession))
{
throw new ArgumentException("The accession number cannot be empty or all whitespace.", nameof(accession));
}
if (string.IsNullOrWhiteSpace(locus))
{
throw new ArgumentException("The locus number cannot be empty or all whitespace.", nameof(locus));
}
Accession = accession;
Locus = locus;
}
/// <summary>
/// Gets the accession number of this identifier.
/// </summary>
public string Accession { get; }
/// <summary>
/// Gets the locus number of this identifier.
/// </summary>
public string Locus { get; }
/// <summary>
/// Returns the string representation of this identifier, as it would
/// appear in the FASTA file.
/// </summary>
/// <returns>The string representation of this identifier.</returns>
public override string ToString()
{
return $"{Code}|{Accession}|{Locus}";
}
}
}
| 34.180556 | 122 | 0.552215 | [
"MIT"
] | Xyaneon/Xyaneon.Bioinformatics.FASTA | Xyaneon.Bioinformatics.FASTA/Identifiers/GenBankIdentifier.cs | 2,463 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using WindowsAuth.models;
using WindowsAuth.Services;
using WindowsAuth;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Security.Claims;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Extensions.Logging;
namespace WebPortal.Helper
{
public class OpenIDAuthentication: OpenIdConnectOptions
{
private readonly string _authenticationScheme = null;
private readonly Dictionary<string, object> _config = null;
public bool _bUseAadGraph = false;
public bool _bUseToken = false;
public bool _bUseIdToken = false;
public string _displayName = null;
public string _clientId = null;
public string _clientSecret = null;
public string _authorityFormat = null;
public string _tenant = null;
public string _AadResourceURL = null;
public string _scope = null;
public string _redirectURL = "";
public string _graphBasePoint = null;
public string _graphApiVersion = null;
public Dictionary<string, object> _domains = null;
public readonly ILogger _logger;
public OpenIDAuthentication( string authenticationScheme, object config, ILoggerFactory logger)
{
_logger = logger.CreateLogger("Authentication(" + authenticationScheme +")");
_authenticationScheme = authenticationScheme;
_config = config as Dictionary<string, object>;
if (Object.ReferenceEquals(_config, null))
throw new System.ArgumentException(String.Format("Authentication {0}, there is no valid configuration object {1}", authenticationScheme, config));
if (_config.ContainsKey("UseAadGraph") &&
String.Compare(_config["UseAadGraph"] as string, "true", true) == 0)
_bUseAadGraph = true;
else
_bUseAadGraph = false;
if (_config.ContainsKey("UseToken") &&
String.Compare(_config["UseToken"] as string, "true", true) == 0)
_bUseToken = true;
else
_bUseToken = false;
if (_config.ContainsKey("UseIdToken") &&
String.Compare(_config["UseIdToken"] as string, "true", true) == 0)
_bUseIdToken = true;
else
_bUseIdToken = false;
if (_config.ContainsKey("DisplayName"))
_displayName = _config["DisplayName"] as string;
if (_config.ContainsKey("ClientId"))
_clientId = _config["ClientId"] as string;
if (_bUseAadGraph && String.IsNullOrEmpty(_clientId))
throw new System.ArgumentException(String.Format("Authentication {0}, there is clientId"));
if (_config.ContainsKey("ClientSecret"))
_clientSecret = _config["ClientSecret"] as string;
if (_bUseAadGraph && String.IsNullOrEmpty(_clientSecret))
throw new System.ArgumentException(String.Format("Authentication {0}, there is ClientSecret"));
if (_config.ContainsKey("AuthorityFormat"))
_authorityFormat = _config["AuthorityFormat"] as string;
if ( String.IsNullOrEmpty(_authorityFormat))
throw new System.ArgumentException(String.Format("Authentication {0}, mendatory configuration AuthorityFormat is missing."));
if (_config.ContainsKey("Tenant"))
_tenant = _config["Tenant"] as string;
if (_bUseAadGraph && String.IsNullOrEmpty(_tenant))
throw new System.ArgumentException(String.Format("Authentication {0}, mendatory configuration Tenant is missing."));
if (_config.ContainsKey("AzureResourceURL"))
_AadResourceURL = _config["AzureResourceURL"] as string;
if (_config.ContainsKey("Scope"))
_scope = _config["Scope"] as string;
if (_config.ContainsKey("RedirectUri"))
_redirectURL = _config["RedirectUri"] as string;
if (_config.ContainsKey("GraphBaseEndpoint"))
_graphBasePoint = _config["GraphBaseEndpoint"] as string;
if (_bUseAadGraph && String.IsNullOrEmpty(_graphBasePoint))
throw new System.ArgumentException(String.Format("Authentication {0}, need GraphBaseEndpoint."));
if (_config.ContainsKey("GraphApiVersion"))
_graphApiVersion = _config["GraphApiVersion"] as string;
if (_bUseAadGraph && String.IsNullOrEmpty(_graphApiVersion))
throw new System.ArgumentException(String.Format("Authentication {0}, need GraphApiVersion."));
if (_config.ContainsKey("Domains"))
_domains = _config["Domains"] as Dictionary<string, object>;
_logger.LogInformation("Use AadGraph {0}, ClientId {1}, ClientSecret{2}, AuthorityFormat {3}, Tenant {4}, AzureResourceURL {5}, Scope {6}, RedirectURL {7}, GraphBaseEndpoint {8}, GraphApiVersion {9}",
_bUseAadGraph, _clientId, _clientSecret,
_authorityFormat, _tenant, _AadResourceURL, _scope, _redirectURL,
_graphBasePoint, _graphApiVersion);
AuthenticationScheme = _authenticationScheme;
ClientId = _clientId;
DisplayName = _displayName;
CallbackPath = new PathString( "/signin-" + _authenticationScheme );
// AutomaticChallenge = true;
if ( !String.IsNullOrEmpty(_clientSecret))
ClientSecret = _clientSecret;
if ( !String.IsNullOrEmpty(_scope))
{
foreach (var scope in _scope.Split(new char[] { ' ' }))
{
Scope.Add(scope);
}
}
if (_bUseAadGraph || _bUseToken )
ResponseType = OpenIdConnectResponseType.CodeIdToken;
if ( _bUseIdToken )
ResponseType = OpenIdConnectResponseType.IdToken;
Authority = String.Format(_authorityFormat, _tenant);
PostLogoutRedirectUri = "/";
GetClaimsFromUserInfoEndpoint = true;
/*
openIDOpt.TokenValidationParameters = new TokenValidationParameters
{
// instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
// we inject our own multitenant validation logic
ValidateIssuer = false
};*/
var ev = new OpenIdConnectEvents();
if (_bUseAadGraph)
{
ev.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
ev.OnRedirectToIdentityProvider = OnRedirectToIdentityProvider;
}
if ( _bUseAadGraph || _bUseToken || _bUseIdToken )
ev.OnTokenValidated = OnTokenValidated;
ev.OnRemoteFailure = OnAuthenticationFailed;
Events = ev;
}
public bool isAuthentication(string email )
{
foreach ( var pair in _domains )
{
var domain = pair.Value as string;
if (email.IndexOf(domain, StringComparison.OrdinalIgnoreCase) >= 0)
return true;
}
return false;
}
// Handle sign-in errors differently than generic errors.
private Task OnAuthenticationFailed(FailureContext context)
{
context.HandleResponse();
context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);
return Task.FromResult(0);
}
private Task OnRedirectToIdentityProvider(RedirectContext context)
{
// Using examples from: https://github.com/jinlmsft/active-directory-webapp-webapi-multitenant-openidconnect-aspnetcore
if (_bUseAadGraph)
{
string adminConsentSignUp = null;
if (context.Request.Path == new PathString("/Account/SignUp") && context.Properties.Items.TryGetValue(Constants.AdminConsentKey, out adminConsentSignUp))
{
if (adminConsentSignUp == Constants.True)
{
context.ProtocolMessage.Prompt = "admin_consent";
}
}
context.ProtocolMessage.Prompt = "admin_consent";
}
return Task.FromResult(0);
}
// Redeem the auth code for a token to the Graph API and cache it for later.
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
// Redeem auth code for access token and cache it for later use
context.HttpContext.User = context.Ticket.Principal;
IAzureAdTokenService tokenService = (IAzureAdTokenService)context.HttpContext.RequestServices.GetService(typeof(IAzureAdTokenService));
await tokenService.RedeemAuthCodeForAadGraph(context.ProtocolMessage.Code, context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]);
// Notify the OIDC middleware that we already took care of code redemption.
context.HandleCodeRedemption();
}
private async Task OnAuthorizationCodeReceivedExp(AuthorizationCodeReceivedContext context)
{
string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
ClientCredential clientCred = new ClientCredential(_clientId, _clientSecret);
var Authority = String.Format(_authorityFormat, _tenant);
var GraphResourceId = _AadResourceURL;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId);
context.HandleCodeRedemption();
}
// Inject custom logic for validating which users we allow to sign in
// Here we check that the user (or their tenant admin) has signed up for the application.
private Task OnTokenValidated(TokenValidatedContext context)
{
// Retrieve caller data from the incoming principal
string issuer = context.Ticket.Principal.FindFirst(Constants.Issuer).Value;
string objectID = context.Ticket.Principal.FindFirst(Constants.ObjectIdClaimType).Value;
string tenantID = context.Ticket.Principal.FindFirst(Constants.TenantIdClaimType).Value;
string upn = "";
var upnPnt = context.Ticket.Principal.FindFirst(ClaimTypes.Upn);
if (!Object.ReferenceEquals(upnPnt, null))
{
upn = upnPnt.Value;
}
else
{
var emailPnt = context.Ticket.Principal.FindFirst(ClaimTypes.Email);
if (!Object.ReferenceEquals(emailPnt, null))
{
upn = emailPnt.Value;
}
}
WebAppContext db = (WebAppContext)context.HttpContext.RequestServices.GetService(typeof(WebAppContext));
db.Database.EnsureCreated();
// If the user is signing up, add the user or tenant to the database record of sign ups.
Tenant tenant = db.Tenants.FirstOrDefault(a => a.IssValue.Equals(issuer));
AADUserRecord user = db.Users.FirstOrDefault(b => b.ObjectID.Equals(objectID));
string adminConsentSignUp = null;
if (context.Properties.Items.TryGetValue(Constants.AdminConsentKey, out adminConsentSignUp))
{
if (adminConsentSignUp == Constants.True)
{
if (tenant == null)
{
tenant = new Tenant { Created = DateTime.Now, IssValue = issuer, Name = context.Properties.Items[Constants.TenantNameKey], AdminConsented = true };
db.Tenants.Add(tenant);
}
else
{
tenant.AdminConsented = true;
}
}
else if (user == null)
{
user = new AADUserRecord { UPN = upn, ObjectID = objectID };
db.Users.Add(user);
}
db.SaveChanges();
}
// Ensure that the caller is recorded in the db of users who went through the individual onboarding
// or if the caller comes from an admin-consented, recorded issuer.
if ((tenant == null || !tenant.AdminConsented) && (user == null))
{
// If not, the caller was neither from a trusted issuer or a registered user - throw to block the authentication flow
// throw new SecurityTokenValidationException("Did you forget to sign-up?");
}
return Task.FromResult(0);
}
}
}
| 48.757042 | 213 | 0.605113 | [
"MIT"
] | AI-ML-Projects/DLWorkspace | src/WebUI/dotnet/WebPortal/Helper/OpenIDAuthentication.cs | 13,849 | C# |
using System;
using System.Diagnostics;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using DDay.iCal.Serialization.iCalendar;
using System.IO;
namespace DDay.iCal
{
/// <summary>
/// The iCalendar equivalent of the .NET <see cref="DateTime"/> class.
/// <remarks>
/// In addition to the features of the <see cref="DateTime"/> class, the <see cref="iCalDateTime"/>
/// class handles time zone differences, and integrates seamlessly into the iCalendar framework.
/// </remarks>
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public sealed class iCalDateTime :
EncodableDataType,
IDateTime
{
#region Static Public Properties
static public iCalDateTime Now
{
get
{
return new iCalDateTime(DateTime.Now);
}
}
static public iCalDateTime Today
{
get
{
return new iCalDateTime(DateTime.Today);
}
}
#endregion
#region Private Fields
private DateTime _Value;
private bool _HasDate;
private bool _HasTime;
private TimeZoneObservance? _TimeZoneObservance;
private bool _IsUniversalTime;
#endregion
#region Constructors
public iCalDateTime() { }
public iCalDateTime(IDateTime value)
{
Initialize(value.Value, value.TZID, null);
}
public iCalDateTime(DateTime value) : this(value, null) { }
public iCalDateTime(DateTime value, string tzid)
{
Initialize(value, tzid, null);
}
public iCalDateTime(DateTime value, TimeZoneObservance tzo)
{
Initialize(value, tzo);
}
public iCalDateTime(int year, int month, int day, int hour, int minute, int second)
{
Initialize(year, month, day, hour, minute, second, null, null);
HasTime = true;
}
public iCalDateTime(int year, int month, int day, int hour, int minute, int second, string tzid)
{
Initialize(year, month, day, hour, minute, second, tzid, null);
HasTime = true;
}
public iCalDateTime(int year, int month, int day, int hour, int minute, int second, string tzid, IICalendar iCal)
{
Initialize(year, month, day, hour, minute, second, tzid, iCal);
HasTime = true;
}
public iCalDateTime(int year, int month, int day)
: this(year, month, day, 0, 0, 0) { }
public iCalDateTime(int year, int month, int day, bool hasTime)
: this(year, month, day, 0, 0, 0) { HasTime = hasTime; }
public iCalDateTime(int year, int month, int day, string tzid)
: this(year, month, day, 0, 0, 0, tzid) { }
public iCalDateTime(int year, int month, int day, string tzid, bool hasTime)
: this(year, month, day, 0, 0, 0, tzid) { HasTime = hasTime; }
public iCalDateTime(string value)
{
DateTimeSerializer serializer = new DateTimeSerializer();
CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable);
}
private void Initialize(int year, int month, int day, int hour, int minute, int second, string tzid, IICalendar iCal)
{
Initialize(CoerceDateTime(year, month, day, hour, minute, second, DateTimeKind.Local), tzid, iCal);
}
private void Initialize(DateTime value, string tzid, IICalendar iCal)
{
if (value.Kind == DateTimeKind.Utc)
this.IsUniversalTime = true;
// Convert all incoming values to UTC.
this.Value = DateTime.SpecifyKind(value, DateTimeKind.Utc);
this.HasDate = true;
this.HasTime = (value.Second == 0 && value.Minute == 0 && value.Hour == 0) ? false : true;
this.TZID = tzid;
this.AssociatedObject = iCal;
}
private void Initialize(DateTime value, TimeZoneObservance tzo)
{
if (value.Kind == DateTimeKind.Utc)
this.IsUniversalTime = true;
// Convert all incoming values to UTC.
this.Value = DateTime.SpecifyKind(value, DateTimeKind.Utc);
this.HasDate = true;
this.HasTime = (value.Second == 0 && value.Minute == 0 && value.Hour == 0) ? false : true;
if (tzo.TimeZoneInfo != null)
this.TZID = tzo.TimeZoneInfo.TZID;
this.TimeZoneObservance = tzo;
this.AssociatedObject = tzo.TimeZoneInfo;
}
private DateTime CoerceDateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
{
DateTime dt = DateTime.MinValue;
// NOTE: determine if a date/time value exceeds the representable date/time values in .NET.
// If so, let's automatically adjust the date/time to compensate.
// FIXME: should we have a parsing setting that will throw an exception
// instead of automatically adjusting the date/time value to the
// closest representable date/time?
try
{
if (year > 9999)
dt = DateTime.MaxValue;
else if (year > 0)
dt = new DateTime(year, month, day, hour, minute, second, kind);
}
catch
{
}
return dt;
}
#endregion
#region Protected Methods
protected TimeZoneObservance? GetTimeZoneObservance()
{
if (_TimeZoneObservance == null &&
TZID != null &&
Calendar != null)
{
ITimeZone tz = Calendar.GetTimeZone(TZID);
if (tz != null)
_TimeZoneObservance = tz.GetTimeZoneObservance(this);
}
return _TimeZoneObservance;
}
#endregion
#region Overrides
public override ICalendarObject AssociatedObject
{
get
{
return base.AssociatedObject;
}
set
{
if (!object.Equals(AssociatedObject, value))
{
base.AssociatedObject = value;
}
}
}
public override void CopyFrom(ICopyable obj)
{
base.CopyFrom(obj);
IDateTime dt = obj as IDateTime;
if (dt != null)
{
_Value = dt.Value;
_IsUniversalTime = dt.IsUniversalTime;
_HasDate = dt.HasDate;
_HasTime = dt.HasTime;
AssociateWith(dt);
}
}
public override bool Equals(object obj)
{
if (obj is IDateTime)
{
this.AssociateWith((IDateTime)obj);
return ((IDateTime)obj).UTC.Equals(UTC);
}
else if (obj is DateTime)
{
iCalDateTime dt = new iCalDateTime((DateTime)obj);
this.AssociateWith(dt);
return object.Equals(dt.UTC, UTC);
}
return false;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return ToString(null, null);
}
#endregion
#region Operators
public static bool operator <(iCalDateTime left, IDateTime right)
{
left.AssociateWith(right);
if (left.HasTime || right.HasTime)
return left.UTC < right.UTC;
else return left.UTC.Date < right.UTC.Date;
}
public static bool operator >(iCalDateTime left, IDateTime right)
{
left.AssociateWith(right);
if (left.HasTime || right.HasTime)
return left.UTC > right.UTC;
else return left.UTC.Date > right.UTC.Date;
}
public static bool operator <=(iCalDateTime left, IDateTime right)
{
left.AssociateWith(right);
if (left.HasTime || right.HasTime)
return left.UTC <= right.UTC;
else return left.UTC.Date <= right.UTC.Date;
}
public static bool operator >=(iCalDateTime left, IDateTime right)
{
left.AssociateWith(right);
if (left.HasTime || right.HasTime)
return left.UTC >= right.UTC;
else return left.UTC.Date >= right.UTC.Date;
}
public static bool operator ==(iCalDateTime left, IDateTime right)
{
left.AssociateWith(right);
if (left.HasTime || right.HasTime)
return left.UTC.Equals(right.UTC);
else return left.UTC.Date.Equals(right.UTC.Date);
}
public static bool operator !=(iCalDateTime left, IDateTime right)
{
left.AssociateWith(right);
if (left.HasTime || right.HasTime)
return !left.UTC.Equals(right.UTC);
else return !left.UTC.Date.Equals(right.UTC.Date);
}
public static TimeSpan operator -(iCalDateTime left, IDateTime right)
{
left.AssociateWith(right);
return left.UTC - right.UTC;
}
public static IDateTime operator -(iCalDateTime left, TimeSpan right)
{
IDateTime copy = left.Copy<IDateTime>();
copy.Value -= right;
return copy;
}
public static IDateTime operator +(iCalDateTime left, TimeSpan right)
{
IDateTime copy = left.Copy<IDateTime>();
copy.Value += right;
return copy;
}
public static implicit operator iCalDateTime(DateTime left)
{
return new iCalDateTime(left);
}
#endregion
#region IDateTime Members
/// <summary>
/// Converts the date/time to local time, according to the time
/// zone specified in the TZID property.
/// </summary>
public DateTime Local
{
get
{
if (IsUniversalTime &&
TZID != null)
{
DateTime value = HasTime ? Value : Value.Date;
// Get the Time Zone Observance, if possible
TimeZoneObservance? tzi = TimeZoneObservance;
if (tzi == null || !tzi.HasValue)
tzi = GetTimeZoneObservance();
if (tzi != null && tzi.HasValue)
{
Debug.Assert(tzi.Value.TimeZoneInfo.OffsetTo != null);
return DateTime.SpecifyKind(tzi.Value.TimeZoneInfo.OffsetTo.ToLocal(value), DateTimeKind.Local);
}
}
return DateTime.SpecifyKind(HasTime ? Value : Value.Date, DateTimeKind.Local);
}
}
/// <summary>
/// Converts the date/time to UTC (Coordinated Universal Time)
/// </summary>
public DateTime UTC
{
get
{
if (IsUniversalTime)
return DateTime.SpecifyKind(Value, DateTimeKind.Utc);
else if (TZID != null)
{
DateTime value = Value;
// Get the Time Zone Observance, if possible
TimeZoneObservance? tzi = TimeZoneObservance;
if (tzi == null || !tzi.HasValue)
tzi = GetTimeZoneObservance();
if (tzi != null && tzi.HasValue)
{
Debug.Assert(tzi.Value.TimeZoneInfo.OffsetTo != null);
return DateTime.SpecifyKind(tzi.Value.TimeZoneInfo.OffsetTo.ToUTC(value), DateTimeKind.Utc);
}
}
// Fallback to the OS-conversion
return DateTime.SpecifyKind(Value, DateTimeKind.Local).ToUniversalTime();
}
}
/// <summary>
/// Gets/sets the <see cref="iCalTimeZoneInfo"/> object for the time
/// zone set by <see cref="TZID"/>.
/// </summary>
public TimeZoneObservance? TimeZoneObservance
{
get
{
return _TimeZoneObservance;
}
set
{
_TimeZoneObservance = value;
if (value != null &&
value.HasValue &&
value.Value.TimeZoneInfo != null)
{
this.TZID = value.Value.TimeZoneInfo.TZID;
}
else
{
this.TZID = null;
}
}
}
public bool IsUniversalTime
{
get { return _IsUniversalTime; }
set { _IsUniversalTime = value; }
}
public string TimeZoneName
{
get
{
if (IsUniversalTime)
return "UTC";
else if (_TimeZoneObservance != null && _TimeZoneObservance.HasValue)
return _TimeZoneObservance.Value.TimeZoneInfo.TimeZoneName;
return string.Empty;
}
}
public DateTime Value
{
get { return _Value; }
set
{
if (!object.Equals(_Value, value))
{
_Value = value;
// Reset the time zone info if the new date/time doesn't
// fall within this time zone observance.
if (_TimeZoneObservance != null &&
_TimeZoneObservance.HasValue &&
!_TimeZoneObservance.Value.Contains(this))
_TimeZoneObservance = null;
}
}
}
public bool HasDate
{
get { return _HasDate; }
set { _HasDate = value; }
}
public bool HasTime
{
get { return _HasTime; }
set { _HasTime = value; }
}
public string TZID
{
get { return Parameters.Get("TZID"); }
set
{
if (!object.Equals(TZID, value))
{
Parameters.Set("TZID", value);
// Set the time zone observance to null if the TZID
// doesn't match.
if (value != null &&
_TimeZoneObservance != null &&
_TimeZoneObservance.HasValue &&
_TimeZoneObservance.Value.TimeZoneInfo != null &&
!object.Equals(_TimeZoneObservance.Value.TimeZoneInfo.TZID, value))
_TimeZoneObservance = null;
}
}
}
public int Year
{
get { return Value.Year; }
}
public int Month
{
get { return Value.Month; }
}
public int Day
{
get { return Value.Day; }
}
public int Hour
{
get { return Value.Hour; }
}
public int Minute
{
get { return Value.Minute; }
}
public int Second
{
get { return Value.Second; }
}
public int Millisecond
{
get { return Value.Millisecond; }
}
public long Ticks
{
get { return Value.Ticks; }
}
public DayOfWeek DayOfWeek
{
get { return Value.DayOfWeek; }
}
public int DayOfYear
{
get { return Value.DayOfYear; }
}
public IDateTime FirstDayOfYear
{
get
{
IDateTime dt = Copy<IDateTime>();
dt.Value = Value.AddDays(-Value.DayOfYear + 1).Date;
return dt;
}
}
public IDateTime FirstDayOfMonth
{
get
{
IDateTime dt = Copy<IDateTime>();
dt.Value = Value.AddDays(-Value.Day + 1).Date;
return dt;
}
}
public DateTime Date
{
get { return Value.Date; }
}
public TimeSpan TimeOfDay
{
get { return Value.TimeOfDay; }
}
public IDateTime ToTimeZone(TimeZoneObservance tzo)
{
ITimeZoneInfo tzi = tzo.TimeZoneInfo;
if (tzi != null)
return new iCalDateTime(tzi.OffsetTo.ToLocal(UTC), tzo);
return null;
}
public IDateTime ToTimeZone(ITimeZone tz)
{
if (tz != null)
{
TimeZoneObservance? tzi = tz.GetTimeZoneObservance(this);
if (tzi != null && tzi.HasValue)
return ToTimeZone(tzi.Value);
// FIXME: if the time cannot be resolved, should we
// just provide a copy? Is this always appropriate?
return Copy<IDateTime>();
}
else throw new ArgumentException("You must provide a valid time zone to the ToTimeZone() method", "tz");
}
public IDateTime ToTimeZone(string tzid)
{
if (tzid != null)
{
if (Calendar != null)
{
ITimeZone tz = Calendar.GetTimeZone(tzid);
if (tz != null)
return ToTimeZone(tz);
// FIXME: sometimes a calendar is perfectly valid but the time zone
// could not be resolved. What should we do here?
//throw new Exception("The '" + tzid + "' time zone could not be resolved.");
return Copy<IDateTime>();
}
else throw new Exception("The iCalDateTime object must have an iCalendar associated with it in order to use TimeZones.");
}
else throw new ArgumentException("You must provide a valid TZID to the ToTimeZone() method", "tzid");
}
public IDateTime SetTimeZone(ITimeZone tz)
{
if (tz != null)
this.TZID = tz.TZID;
return this;
}
public IDateTime Add(TimeSpan ts)
{
return this + ts;
}
public IDateTime Subtract(TimeSpan ts)
{
return this - ts;
}
public TimeSpan Subtract(IDateTime dt)
{
return this - dt;
}
public IDateTime AddYears(int years)
{
IDateTime dt = Copy<IDateTime>();
dt.Value = Value.AddYears(years);
return dt;
}
public IDateTime AddMonths(int months)
{
IDateTime dt = Copy<IDateTime>();
dt.Value = Value.AddMonths(months);
return dt;
}
public IDateTime AddDays(int days)
{
IDateTime dt = Copy<IDateTime>();
dt.Value = Value.AddDays(days);
return dt;
}
public IDateTime AddHours(int hours)
{
IDateTime dt = Copy<IDateTime>();
if (!dt.HasTime && hours % 24 > 0)
dt.HasTime = true;
dt.Value = Value.AddHours(hours);
return dt;
}
public IDateTime AddMinutes(int minutes)
{
IDateTime dt = Copy<IDateTime>();
if (!dt.HasTime && minutes % 1440 > 0)
dt.HasTime = true;
dt.Value = Value.AddMinutes(minutes);
return dt;
}
public IDateTime AddSeconds(int seconds)
{
IDateTime dt = Copy<IDateTime>();
if (!dt.HasTime && seconds % 86400 > 0)
dt.HasTime = true;
dt.Value = Value.AddSeconds(seconds);
return dt;
}
public IDateTime AddMilliseconds(int milliseconds)
{
IDateTime dt = Copy<IDateTime>();
if (!dt.HasTime && milliseconds % 86400000 > 0)
dt.HasTime = true;
dt.Value = Value.AddMilliseconds(milliseconds);
return dt;
}
public IDateTime AddTicks(long ticks)
{
IDateTime dt = Copy<IDateTime>();
dt.HasTime = true;
dt.Value = Value.AddTicks(ticks);
return dt;
}
public bool LessThan(IDateTime dt)
{
return this < dt;
}
public bool GreaterThan(IDateTime dt)
{
return this > dt;
}
public bool LessThanOrEqual(IDateTime dt)
{
return this <= dt;
}
public bool GreaterThanOrEqual(IDateTime dt)
{
return this >= dt;
}
public void AssociateWith(IDateTime dt)
{
if (AssociatedObject == null && dt.AssociatedObject != null)
AssociatedObject = dt.AssociatedObject;
else if (AssociatedObject != null && dt.AssociatedObject == null)
dt.AssociatedObject = AssociatedObject;
// If these share the same TZID, then let's see if we
// can share the time zone observance also!
if (TimeZoneName != null && string.Equals(TimeZoneName, dt.TimeZoneName))
{
if (TimeZoneObservance != null && dt.TimeZoneObservance == null)
{
IDateTime normalizedDt = new iCalDateTime(TimeZoneObservance.Value.TimeZoneInfo.OffsetTo.ToUTC(dt.Value));
if (TimeZoneObservance.Value.Contains(normalizedDt))
dt.TimeZoneObservance = TimeZoneObservance;
}
else if (dt.TimeZoneObservance != null && TimeZoneObservance == null)
{
IDateTime normalizedDt = new iCalDateTime(dt.TimeZoneObservance.Value.TimeZoneInfo.OffsetTo.ToUTC(Value));
if (dt.TimeZoneObservance.Value.Contains(normalizedDt))
TimeZoneObservance = dt.TimeZoneObservance;
}
}
}
#endregion
#region IComparable Members
public int CompareTo(IDateTime dt)
{
if (this.Equals(dt))
return 0;
else if (this < dt)
return -1;
else if (this > dt)
return 1;
throw new Exception("An error occurred while comparing two IDateTime values.");
}
#endregion
#region IFormattable Members
public string ToString(string format)
{
return ToString(format, null);
}
public string ToString(string format, IFormatProvider formatProvider)
{
string tz = TimeZoneName;
if (!string.IsNullOrEmpty(tz))
tz = " " + tz;
if (format != null)
return Value.ToString(format, formatProvider) + tz;
else if (HasTime && HasDate)
return Value.ToString() + tz;
else if (HasTime)
return Value.TimeOfDay.ToString() + tz;
else
return Value.ToShortDateString() + tz;
}
#endregion
}
}
| 30.628057 | 137 | 0.502983 | [
"BSD-3-Clause"
] | ststeiger/DDay.iCal | DDay.iCal/DataTypes/iCalDateTime.cs | 23,798 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DragonWarriorEditor {
class Tile : ITile {
// TODO: Currently assuming 1 byte = index, so 0-255
// TODO: put in adaptor function
public byte[] RawData { get; set; }
public Size Size { get; set; }
// TODO: FIgure out live updates but with caching
public Image AsImage(IPalette palette) {
//public Image AsImage(int[] ) {
/*
Bitmap b = new Bitmap(this.Size.Width, this.Size.Height, PixelFormat.Format32bppArgb);
b.Palette.Entries.
Bitmap.FromStream()
b.
using (MemoryStream mStream = new MemoryStream()) {
return Image.FromStream(mStream);
}
*/
throw new NotImplementedException();
}
public Image AsImage() {
throw new NotImplementedException();
}
// TODO: Currently assuming rawdata = indexes
public byte[] ToRawImage(IPalette palette) {
byte[] data = new byte[4 * this.RawData.Length];
for (int i = 0; i < this.RawData.Length; i++) {
int offset = i * 4;
Color color = palette.Colors[this.RawData[i]];
data[offset] = color.A;
data[offset + 1] = color.R;
data[offset + 2] = color.G;
data[offset + 3] = color.B;
}
return data;
}
}
}
| 24.254545 | 89 | 0.667166 | [
"MIT"
] | TheAnsarya/DragonWarriorEditor | DragonWarriorEditor/Tile.cs | 1,336 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LinqToDB.SqlQuery
{
public class SqlColumn : IEquatable<SqlColumn>, ISqlExpression
{
public SqlColumn(SelectQuery parent, ISqlExpression expression, string alias)
{
Parent = parent;
Expression = expression ?? throw new ArgumentNullException(nameof(expression));
RawAlias = alias;
#if DEBUG
_columnNumber = ++_columnCounter;
#endif
}
public SqlColumn(SelectQuery builder, ISqlExpression expression)
: this(builder, expression, null)
{
}
#if DEBUG
readonly int _columnNumber;
static int _columnCounter;
#endif
public ISqlExpression Expression { get; set; }
public SelectQuery Parent { get; set; }
internal string RawAlias { get; set; }
public string Alias
{
get
{
if (RawAlias == null)
{
switch (Expression)
{
case SqlField field : return field.Alias ?? field.PhysicalName;
case SqlColumn column : return column.Alias;
case SelectQuery query:
{
if (query.Select.Columns.Count == 1 && query.Select.Columns[0].Alias != "*")
return query.Select.Columns[0].Alias;
break;
}
}
}
return RawAlias;
}
set => RawAlias = value;
}
private bool _underlyingColumnSet;
private SqlColumn _underlyingColumn;
public SqlColumn UnderlyingColumn
{
get
{
if (_underlyingColumnSet)
return _underlyingColumn;
var columns = new List<SqlColumn>(10);
var column = Expression as SqlColumn;
while (column != null)
{
if (column._underlyingColumn != null)
{
columns.Add(column._underlyingColumn);
break;
}
columns.Add(column);
column = column.Expression as SqlColumn;
}
_underlyingColumnSet = true;
if (columns.Count == 0)
return null;
_underlyingColumn = columns[columns.Count - 1];
for (var i = 0; i < columns.Count - 1; i++)
{
var c = columns[i];
c._underlyingColumn = _underlyingColumn;
c._underlyingColumnSet = true;
}
return _underlyingColumn;
}
}
public bool Equals(SqlColumn other)
{
if (other == null)
return false;
if (!Equals(Parent, other.Parent))
return false;
if (Expression.Equals(other.Expression))
return true;
//return false;
return UnderlyingColumn != null && UnderlyingColumn.Equals(other.UnderlyingColumn);
//var found =
//
// || new QueryVisitor().Find(other, e =>
// {
// switch(e.ElementType)
// {
// case QueryElementType.Column: return ((Column)e).Expression.Equals(Expression);
// }
// return false;
// }) != null
// || new QueryVisitor().Find(Expression, e =>
// {
// switch (e.ElementType)
// {
// case QueryElementType.Column: return ((Column)e).Expression.Equals(other.Expression);
// }
// return false;
// }) != null;
//return found;
}
public override string ToString()
{
#if OVERRIDETOSTRING
return ((IQueryElement)this).ToString(new StringBuilder(), new Dictionary<IQueryElement,IQueryElement>()).ToString();
#else
if (Expression is SqlField)
return ((IQueryElement)this).ToString(new StringBuilder(), new Dictionary<IQueryElement,IQueryElement>()).ToString();
return base.ToString();
#endif
}
#region ISqlExpression Members
public bool CanBeNull => Expression.CanBeNull;
public bool Equals(ISqlExpression other, Func<ISqlExpression,ISqlExpression,bool> comparer)
{
if (this == other)
return true;
var otherColumn = other as SqlColumn;
if (otherColumn == null)
return false;
if (Parent != otherColumn.Parent)
return false;
if (Parent.HasSetOperators)
return false;
return
Expression.Equals(
otherColumn.Expression,
(ex1, ex2) =>
{
// var c = ex1 as Column;
// if (c != null && c.Parent != Parent)
// return false;
// c = ex2 as Column;
// if (c != null && c.Parent != Parent)
// return false;
return comparer(ex1, ex2);
})
&&
comparer(this, other);
}
public int Precedence => SqlQuery.Precedence.Primary;
public Type SystemType => Expression.SystemType;
public ICloneableElement Clone(Dictionary<ICloneableElement, ICloneableElement> objectTree, Predicate<ICloneableElement> doClone)
{
if (!doClone(this))
return this;
var parent = (SelectQuery)Parent.Clone(objectTree, doClone);
if (!objectTree.TryGetValue(this, out var clone))
objectTree.Add(this, clone = new SqlColumn(
parent,
(ISqlExpression)Expression.Clone(objectTree, doClone),
RawAlias));
return clone;
}
#endregion
#region IEquatable<ISqlExpression> Members
bool IEquatable<ISqlExpression>.Equals(ISqlExpression other)
{
if (this == other)
return true;
return other is SqlColumn && Equals((SqlColumn)other);
}
#endregion
#region ISqlExpressionWalkable Members
public ISqlExpression Walk(WalkOptions options, Func<ISqlExpression,ISqlExpression> func)
{
if (!(options.SkipColumns && Expression is SqlColumn))
Expression = Expression.Walk(options, func);
if (options.ProcessParent)
Parent = (SelectQuery)func(Parent);
return func(this);
}
#endregion
#region IQueryElement Members
public QueryElementType ElementType => QueryElementType.Column;
StringBuilder IQueryElement.ToString(StringBuilder sb, Dictionary<IQueryElement,IQueryElement> dic)
{
if (dic.ContainsKey(this))
return sb.Append("...");
dic.Add(this, this);
sb
.Append('t')
.Append(Parent.SourceID)
.Append(".");
#if DEBUG
sb.Append('[').Append(_columnNumber).Append(']');
#endif
if (Expression is SelectQuery)
{
sb.Append("(\n\t\t");
var len = sb.Length;
Expression.ToString(sb, dic).Replace("\n", "\n\t\t", len, sb.Length - len);
sb.Append("\n\t)");
}
else
{
Expression.ToString(sb, dic);
}
dic.Remove(this);
return sb;
}
#endregion
}
}
| 23.168498 | 132 | 0.618814 | [
"MIT"
] | FrancisChung/linq2db | Source/LinqToDB/SqlQuery/SqlColumn.cs | 6,055 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SampleApp.IdentityServer.Data;
using SampleApp.IdentityServer.Models;
using SampleApp.IdentityServer.Services;
namespace SampleApp.IdentityServer
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
// Adds IdentityServer
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 36.25 | 135 | 0.625379 | [
"MIT"
] | Arashrohani/SampleApp | src/SampleApp.IdentityServer/Startup.cs | 3,627 | C# |
#region Header
//
// CmdPlaceFamilyInstance.cs - call PromptForFamilyInstancePlacement
// to place family instances and use the DocumentChanged event to
// capture the newly added element ids
//
// Copyright (C) 2010-2020 by Jeremy Tammik,
// Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using ComponentManager = Autodesk.Windows.ComponentManager;
using IWin32Window = System.Windows.Forms.IWin32Window;
using Keys = System.Windows.Forms.Keys;
#endregion // Namespaces
namespace BuildingCoder
{
[Transaction( TransactionMode.Manual )]
class CmdPlaceFamilyInstance : IExternalCommand
{
/// <summary>
/// Set this flag to true to abort after
/// placing the first instance.
/// </summary>
static bool _place_one_single_instance_then_abort
= true;
/// <summary>
/// Send messages to main Revit application window.
/// </summary>
//IWin32Window _revit_window; // 2018
IntPtr _revit_window; // 2019
List<ElementId> _added_element_ids
= new List<ElementId>();
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
//_revit_window
// = new JtWindowHandle(
// ComponentManager.ApplicationWindow ); // 2018
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
_revit_window = uiapp.MainWindowHandle; // 2019
FilteredElementCollector collector
= new FilteredElementCollector( doc );
collector.OfCategory( BuiltInCategory.OST_Doors );
collector.OfClass( typeof( FamilySymbol ) );
FamilySymbol symbol = collector.FirstElement()
as FamilySymbol;
_added_element_ids.Clear();
app.DocumentChanged
+= new EventHandler<DocumentChangedEventArgs>(
OnDocumentChanged );
//PromptForFamilyInstancePlacementOptions opt
// = new PromptForFamilyInstancePlacementOptions();
try
{
uidoc.PromptForFamilyInstancePlacement( symbol );
}
catch( Autodesk.Revit.Exceptions.OperationCanceledException ex )
{
Debug.Print( ex.Message );
}
app.DocumentChanged
-= new EventHandler<DocumentChangedEventArgs>(
OnDocumentChanged );
int n = _added_element_ids.Count;
TaskDialog.Show(
"Place Family Instance",
string.Format(
"{0} element{1} added.", n,
( ( 1 == n ) ? "" : "s" ) ) );
return Result.Succeeded;
}
void OnDocumentChanged(
object sender,
DocumentChangedEventArgs e )
{
ICollection<ElementId> idsAdded
= e.GetAddedElementIds();
int n = idsAdded.Count;
Debug.Print( "{0} id{1} added.",
n, Util.PluralSuffix( n ) );
// This does not work, because the handler will
// be called each time a new instance is added,
// overwriting the previous ones recorded:
//_added_element_ids = e.GetAddedElementIds();
_added_element_ids.AddRange( idsAdded );
if( _place_one_single_instance_then_abort
&& 0 < n )
{
// Why do we send the WM_KEYDOWN message twice?
// I tried sending it once only, and that does
// not work. Maybe the proper thing to do would
// be something like the Press.OneKey method...
//
//Press.OneKey( _revit_window.Handle,
// (char) Keys.Escape );
//
// Nope, that did not work.
//
// Answer: When you place instances with
// PromptForFamilyInstancePlacement, the previous
// one remains selected just until you drop the
// next one. The first esc key hit removes that
// selection while still allowing you to continue
// adding instances to the model. Only a second
// esc hit aborts the command.
//Press.PostMessage( _revit_window.Handle,
// (uint) Press.KEYBOARD_MSG.WM_KEYDOWN,
// (uint) Keys.Escape, 0 ); // 2018
//Press.PostMessage( _revit_window.Handle,
// (uint) Press.KEYBOARD_MSG.WM_KEYDOWN,
// (uint) Keys.Escape, 0 ); // 2018
Press.PostMessage( _revit_window,
(uint) Press.KEYBOARD_MSG.WM_KEYDOWN,
(uint) Keys.Escape, 0 ); // 2019
Press.PostMessage( _revit_window,
(uint) Press.KEYBOARD_MSG.WM_KEYDOWN,
(uint) Keys.Escape, 0 ); // 2019
}
}
}
}
| 30.095808 | 71 | 0.625547 | [
"MIT"
] | roya13668593/the_building_coder_samples | BuildingCoder/BuildingCoder/CmdPlaceFamilyInstance.cs | 5,026 | C# |
using Flunt.Validations;
using Store.Domain.Entities;
namespace Store.Domain.Entities;
public class OrderItem : Entity
{
public OrderItem(Product product, int quantity)
{
AddNotifications(
new Contract<OrderItem>()
.Requires()
.IsNotNull(product,"Product", "Produto Inválido")
.IsGreaterThan(quantity,0,"Quantity", "A quantidade deve ser maior que zero")
);
Product = product;
Price = Product != null ? product.Price : 0;
Quantity = quantity;
}
public Product Product { get; private set; }
public decimal Price { get; private set; }
public int Quantity { get; private set; }
public decimal Total()
{
return Price * Quantity;
}
}
| 25.096774 | 93 | 0.605398 | [
"MIT"
] | paulo-ramos/curso-balta | Store/Store.Domain/Entities/OrderItem.cs | 779 | C# |
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Sensors.Model
{
/// <summary>
/// BaseSensorModel abstract class.
/// </summary>
public abstract class BaseSensorModel : INotifyPropertyChanged
{
private bool isSupported;
private int sensorCount;
/// <summary>
/// Raised when the property has changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Property for is supported.
/// </summary>
public bool IsSupported
{
get { return isSupported; }
set
{
isSupported = value;
OnPropertyChanged();
}
}
/// <summary>
/// Property for sensor count.
/// </summary>
public int SensorCount
{
get { return sensorCount; }
set
{
sensorCount = value;
OnPropertyChanged();
}
}
/// <summary>
/// Call method when property changed.
/// </summary>
/// <param name="propertyName">Property name.</param>
public void OnPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} | 28.597222 | 86 | 0.597863 | [
"Apache-2.0"
] | AchoWang/Tizen-CSharp-Samples | Wearable/Sensors/src/Sensors/Model/BaseSensorModel.cs | 2,061 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CPI.Common.Domain.AgreePay.YeePay
{
public abstract class RawYeePayCommonResponse
{
public String errorcode { get; set; }
public String errormsg { get; set; }
}
}
| 20.769231 | 49 | 0.696296 | [
"Apache-2.0"
] | SZarrow/CPI | src/CPI.Common/Domain/AgreePay/YeePay/RawYeePayCommonResponse.cs | 272 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Rest.Serverless.V1.Service;
namespace Twilio.Tests.Rest.Serverless.V1.Service
{
[TestFixture]
public class BuildTest : TwilioTest
{
[Test]
public void TestReadRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
BuildResource.Read("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestReadEmptyResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"builds\": [],\"meta\": {\"first_page_url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds?PageSize=50&Page=0\",\"key\": \"builds\",\"next_page_url\": null,\"page\": 0,\"page_size\": 50,\"previous_page_url\": null,\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds?PageSize=50&Page=0\"}}"
));
var response = BuildResource.Read("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestFetchRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Get,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds/ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
BuildResource.Fetch("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestFetchResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.OK,
"{\"sid\": \"ZB00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"asset_versions\": [{\"sid\": \"ZN00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"asset_sid\": \"ZH00000000000000000000000000000000\",\"date_created\": \"2018-11-10T20:00:00Z\",\"path\": \"asset-path\",\"visibility\": \"PUBLIC\"}],\"function_versions\": [{\"sid\": \"ZN00000000000000000000000000000001\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"function_sid\": \"ZH00000000000000000000000000000001\",\"date_created\": \"2018-11-10T20:00:00Z\",\"path\": \"function-path\",\"visibility\": \"PUBLIC\"}],\"dependencies\": [{\"name\": \"twilio\",\"version\": \"3.6.3\"}],\"status\": \"deploying\",\"date_created\": \"2018-11-10T20:00:00Z\",\"date_updated\": \"2018-11-10T20:00:00Z\",\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000\"}"
));
var response = BuildResource.Fetch("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestDeleteRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Delete,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds/ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
BuildResource.Delete("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestDeleteResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.NoContent,
"null"
));
var response = BuildResource.Delete("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
[Test]
public void TestCreateRequest()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
var request = new Request(
HttpMethod.Post,
Twilio.Rest.Domain.Serverless,
"/v1/Services/ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Builds",
""
);
twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content"));
try
{
BuildResource.Create("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.Fail("Expected TwilioException to be thrown for 500");
}
catch (ApiException) {}
twilioRestClient.Received().Request(request);
}
[Test]
public void TestCreateResponse()
{
var twilioRestClient = Substitute.For<ITwilioRestClient>();
twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
twilioRestClient.Request(Arg.Any<Request>())
.Returns(new Response(
System.Net.HttpStatusCode.Created,
"{\"sid\": \"ZB00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"asset_versions\": [{\"sid\": \"ZN00000000000000000000000000000000\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"asset_sid\": \"ZH00000000000000000000000000000000\",\"date_created\": \"2018-11-10T20:00:00Z\",\"path\": \"asset-path\",\"visibility\": \"PUBLIC\"}],\"function_versions\": [{\"sid\": \"ZN00000000000000000000000000000001\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ZS00000000000000000000000000000000\",\"function_sid\": \"ZH00000000000000000000000000000001\",\"date_created\": \"2018-11-10T20:00:00Z\",\"path\": \"function-path\",\"visibility\": \"PUBLIC\"}],\"dependencies\": [{\"name\": \"twilio\",\"version\": \"3.6.3\"}],\"status\": \"building\",\"date_created\": \"2018-11-10T20:00:00Z\",\"date_updated\": \"2018-11-10T20:00:00Z\",\"url\": \"https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000\"}"
));
var response = BuildResource.Create("ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient);
Assert.NotNull(response);
}
}
} | 54.630952 | 1,189 | 0.609065 | [
"MIT"
] | FishDawg/twilio-csharp | test/Twilio.Test/Rest/Serverless/V1/Service/BuildResourceTest.cs | 9,178 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PerformanceEf6.EF6.Models
{
[Table("Person.BusinessEntityAddress")]
public partial class BusinessEntityAddress
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int BusinessEntityID { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int AddressID { get; set; }
[Key]
[Column(Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int AddressTypeID { get; set; }
public Guid rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual Address Address { get; set; }
public virtual AddressType AddressType { get; set; }
public virtual BusinessEntity BusinessEntity { get; set; }
}
}
| 27.111111 | 66 | 0.651639 | [
"BSD-3-Clause"
] | Manishkr117/DesignPattern | DOTNETCORE/EFCoreSamples/PerformanceEf6/EF6/Models/BusinessEntityAddress.cs | 976 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Mps.V20190612.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class PoliticalConfigureInfoForUpdate : AbstractModel
{
/// <summary>
/// 画面鉴政控制参数。
/// </summary>
[JsonProperty("ImgReviewInfo")]
public PoliticalImgReviewTemplateInfoForUpdate ImgReviewInfo{ get; set; }
/// <summary>
/// 语音鉴政控制参数。
/// </summary>
[JsonProperty("AsrReviewInfo")]
public PoliticalAsrReviewTemplateInfoForUpdate AsrReviewInfo{ get; set; }
/// <summary>
/// 文本鉴政控制参数。
/// </summary>
[JsonProperty("OcrReviewInfo")]
public PoliticalOcrReviewTemplateInfoForUpdate OcrReviewInfo{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamObj(map, prefix + "ImgReviewInfo.", this.ImgReviewInfo);
this.SetParamObj(map, prefix + "AsrReviewInfo.", this.AsrReviewInfo);
this.SetParamObj(map, prefix + "OcrReviewInfo.", this.OcrReviewInfo);
}
}
}
| 32.706897 | 81 | 0.653137 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Mps/V20190612/Models/PoliticalConfigureInfoForUpdate.cs | 1,951 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from shared/wtypes.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="uCLSSPEC" /> struct.</summary>
public static unsafe class uCLSSPECTests
{
/// <summary>Validates that the <see cref="uCLSSPEC" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<uCLSSPEC>(), Is.EqualTo(sizeof(uCLSSPEC)));
}
/// <summary>Validates that the <see cref="uCLSSPEC" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(uCLSSPEC).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="uCLSSPEC" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(uCLSSPEC), Is.EqualTo(40));
}
else
{
Assert.That(sizeof(uCLSSPEC), Is.EqualTo(36));
}
}
}
}
| 34.295455 | 145 | 0.616965 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/shared/wtypes/uCLSSPECTests.cs | 1,511 | C# |
// Copyright (c) Cedita Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the solution root for license information.
using Chic.Attributes;
using Chic.Internal.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Chic.Internal
{
internal static class TypeTableMaps
{
private static ConcurrentDictionary<Type, TableRepresentation> TypeTableCache = new ConcurrentDictionary<Type, TableRepresentation>();
internal static TableRepresentation<TTableType> Get<TTableType>()
{
var type = typeof(TTableType);
if (!TypeTableCache.ContainsKey(type))
{
TypeTableCache.TryAdd(type, GetRepresentation<TTableType>());
}
return (TableRepresentation<TTableType>)TypeTableCache[type];
}
internal static TableRepresentation<TTableType> Get<TTableType>(TTableType dto)
{
return Get<TTableType>();
}
private static readonly string idConvention = "Id";
private static readonly Type[] mappableTypes = {
typeof(bool),
typeof(byte),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(decimal),
typeof(double),
typeof(float),
typeof(Guid),
typeof(int),
typeof(string),
typeof(char),
};
private static readonly Dictionary<Type, SqlDbType> sqlDataTypeMap = new Dictionary<Type, SqlDbType>
{
{ typeof(byte), SqlDbType.TinyInt },
{ typeof(byte[]), SqlDbType.Image },
{ typeof(char), SqlDbType.NChar },
{ typeof(char[]), SqlDbType.NVarChar },
{ typeof(bool), SqlDbType.Bit },
{ typeof(DateTime), SqlDbType.DateTime2 },
{ typeof(DateTimeOffset), SqlDbType.DateTimeOffset },
{ typeof(decimal), SqlDbType.Money },
{ typeof(double), SqlDbType.Float },
{ typeof(int), SqlDbType.Int },
{ typeof(float), SqlDbType.Real },
{ typeof(long), SqlDbType.BigInt },
{ typeof(short), SqlDbType.SmallInt },
{ typeof(string), SqlDbType.NVarChar },
{ typeof(TimeSpan), SqlDbType.Time },
};
private static TableRepresentation<TTableType> GetRepresentation<TTableType>()
{
var type = typeof(TTableType);
string tableName = type.Name + "s";
var tableAttr = type.GetCustomAttributes(false).SingleOrDefault(attr => attr.GetType().Name == nameof(System.ComponentModel.DataAnnotations.Schema.TableAttribute)) as dynamic;
if (tableAttr != null)
{
tableName = tableAttr.Name;
}
var conventionKeys = new[] { idConvention, type.Name + idConvention };
var tableRepresentation = new TableRepresentation<TTableType>
{
TableName = tableName
};
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
var nullableBaseType = Nullable.GetUnderlyingType(property.PropertyType);
var baseType = nullableBaseType ?? property.PropertyType;
if (!IsMappable(property)) continue;
var isDbGenerated = property.CustomAttributes.Any(m => m.AttributeType.Name == nameof(DbGeneratedAttribute));
var isKey = property.CustomAttributes.Any(m => m.AttributeType.Name == nameof(PrimaryKeyAttribute))
|| conventionKeys.Contains(property.Name);
var obj = Expression.Parameter(typeof(TTableType));
var prop = Expression.Property(obj, property);
var body = Expression.Convert(prop, typeof(object));
var propertyType = nullableBaseType != null ? typeof(string) : baseType;
if (baseType.IsEnum)
{
propertyType = baseType.GetEnumUnderlyingType();
}
// If it's nullable as a base then the type used for mapping should be a string
tableRepresentation.Columns.Add(new TableProperty<TTableType>
{
Name = property.Name,
Type = propertyType,
DbType = sqlDataTypeMap[propertyType],
IsDbGenerated = isDbGenerated,
IsKey = isKey,
Get = Expression.Lambda<Func<TTableType, object>>(body, obj).Compile()
});
}
// Determine & Store Primary Key
if (tableRepresentation.Columns.Count(m => m.IsKey) > 1)
{
throw new TableMappingException($"Type {type.Name} discovered multiple primary keys");
}
tableRepresentation.PrimaryKeyColumn = tableRepresentation.Columns.FirstOrDefault(m => m.IsKey);
return tableRepresentation;
}
private static bool IsMappable(PropertyInfo property)
{
if (property.CustomAttributes.Any(m => m.AttributeType.Name == nameof(DbIgnoreAttribute)))
{
return false;
}
var nullableBaseType = Nullable.GetUnderlyingType(property.PropertyType);
var baseType = nullableBaseType ?? property.PropertyType;
return (mappableTypes.Contains(baseType) || baseType.IsEnum);
}
}
}
| 40.034722 | 187 | 0.584562 | [
"Apache-2.0"
] | ceditalabs/Chic | src/Chic/Internal/TypeTableMap.cs | 5,767 | C# |
namespace FitDontQuit.Services.Models.Articles
{
using FitDontQuit.Data.Models;
public class CreateArticleServiceModel
{
public string Title { get; set; }
public string Content { get; set; }
public string ImageUrl { get; set; }
public ApplicationUser User { get; set; }
}
}
| 20.4375 | 49 | 0.639144 | [
"MIT"
] | YolitoMarinova/Fit-Dont-Quit.WebApp | Services/FitDontQuit.Services.Models/Articles/CreateArticleServiceModel.cs | 329 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace Devscovery
{
static public class ArrayExtensions
{
static public int[] Abs(this int[] xs)
{
Contract.Requires(xs != null);
Contract.Requires(Contract.ForAll(xs, x => x > Int32.MinValue));
Contract.Ensures(Contract.Result<int[]>() != null);
Contract.Ensures(
Contract.ForAll(Contract.Result<int[]>(), x => x >= 0));
var result = new int[xs.Length];
for(var i = 0; i < xs.Length; i++)
{
result[i] = MyMath.Abs_NetStyle(xs[i]);
}
return result;
}
}
}
#if false
Contract.Requires(xs != null);
Contract.Requires(Contract.ForAll(xs, x => x > Int32.MinValue));
Contract.Ensures(Contract.Result<int[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<int[]>(), x => x >= 0));
#endif | 25.246914 | 463 | 0.69291 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Demo/Devscovery/ArrayExtensions.cs | 2,045 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
namespace System.Web.Razor.Test
{
internal static class CodeCompileUnitExtensions
{
public static string GenerateCode<T>(this CodeCompileUnit ccu) where T : CodeDomProvider, new()
{
StringBuilder output = new StringBuilder();
using (StringWriter writer = new StringWriter(output))
{
T provider = new T();
provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions() { IndentString = " " });
}
return output.ToString();
}
}
}
| 31.92 | 133 | 0.646617 | [
"Apache-2.0"
] | Darth-Fx/AspNetMvcStack | test/System.Web.Razor.Test/CodeCompileUnitExtensions.cs | 800 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/mmeapi.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="AUXCAPS2A" /> struct.</summary>
public static unsafe class AUXCAPS2ATests
{
/// <summary>Validates that the <see cref="AUXCAPS2A" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<AUXCAPS2A>(), Is.EqualTo(sizeof(AUXCAPS2A)));
}
/// <summary>Validates that the <see cref="AUXCAPS2A" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(AUXCAPS2A).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="AUXCAPS2A" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(AUXCAPS2A), Is.EqualTo(96));
}
}
}
| 36.555556 | 145 | 0.652736 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | tests/Interop/Windows/um/mmeapi/AUXCAPS2ATests.cs | 1,318 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Axe.Windows.Core.Misc;
using Axe.Windows.Core.Types;
using Axe.Windows.Win32;
using Newtonsoft.Json;
using System;
using System.Globalization;
namespace Axe.Windows.Core.Bases
{
/// <summary>
/// Wrapper class for UIAutomationElement Property
/// </summary>
public class A11yProperty : IDisposable
{
/// <summary>
/// Property Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// Property Name
/// </summary>
public string Name { get; set; }
#pragma warning disable CA1051 // Do not declare visible instance fields
/// <summary>
/// Property value
/// because it is used in referenced variable later, it can't be property.
/// please keep it as field.
///
/// CA1051 because of backward compat issue with loading existing results file, can't change it to field.
/// </summary>
public dynamic Value;
#pragma warning restore CA1051 // Do not declare visible instance fields
[JsonIgnore]
public string TextValue
{
get
{
return this.ToString();
}
}
/// <summary>
/// Constructor with normal case
/// </summary>
/// <param name="id"></param>
/// <param name="element"></param>
public A11yProperty (int id, dynamic value,string name = null): this(id,name)
{
this.Value = value;
}
/// <summary>
/// private constructor
/// </summary>
/// <param name="id"></param>
/// <param name="name">if null, it is get name from PropertyTypes by id</param>
private A11yProperty(int id, string name)
{
this.Id = id;
this.Name = name ?? PropertyType.GetInstance().GetNameById(id);
}
/// <summary>
/// Constructor for serialization
/// </summary>
public A11yProperty() { }
public override string ToString()
{
string txt = null;
if (this.Value != null)
{
switch (this.Id)
{
case PropertyType.UIA_RuntimeIdPropertyId:
txt = this.ConvertIntArrayToString();
break;
case PropertyType.UIA_ControlTypePropertyId:
txt = this.Value != null ? ControlType.GetInstance().GetNameById(this.Value) : "";
break;
case PropertyType.UIA_BoundingRectanglePropertyId:
// if bounding rectangle is [0,0,0,0], treat it as non-exist. same behavior as Inspect
txt = GetBoundingRectangleText();
break;
case PropertyType.UIA_OrientationPropertyId:
switch ((int)this.Value)
{
case 0: //OrientationType_None
txt = "None(0)";
break;
case 1: //OrientationType_Horizontal
txt = "Horizontal(1)";
break;
case 2: // OrientationType_Vertical
txt = "Vertical(2)";
break;
}
break;
case PropertyType.UIA_PositionInSetPropertyId:
case PropertyType.UIA_LevelPropertyId:
case PropertyType.UIA_SizeOfSetPropertyId:
/// these properties are 1 based.
/// if value is smaller than 1, it should be ignored.
if(this.Value != null && this.Value > 0)
{
txt = this.Value?.ToString();
}
break;
case PropertyType.UIA_HeadingLevelPropertyId:
txt = HeadingLevelType.GetInstance().GetNameById(this.Value);
break;
case PropertyType.UIA_LandmarkTypePropertyId:
txt = this.Value != 0 ? LandmarkType.GetInstance().GetNameById(this.Value) : null; // 0 is default value.
break;
default:
if(this.Value is Int32[])
{
txt = ((Int32[])this.Value).ConvertInt32ArrayToString();
}
else if(this.Value is Double[])
{
txt = ((Double[])this.Value).ConvertDoubleArrayToString();
}
else
{
txt = this.Value?.ToString();
}
break;
}
}
return txt;
}
/// <summary>
/// Get proper bounding rectangle text based on teh date
/// </summary>
/// <returns></returns>
private string GetBoundingRectangleText()
{
string text = null;
var arr = this.Value;
if ((double)arr[2] < 0 || (double)arr[3] < 0)
{
// the 3rd and 4th values in array are negative value, we need to show value in different format like l,t,w,h
text = string.Format(CultureInfo.InvariantCulture, "[l={0},t={1},w={2},h={3}]", arr[0], arr[1], arr[2], arr[3]);
}
else
{
text = this.ToRectangle().IsEmpty == false ? this.ToRectangle().ToLeftTopRightBottomString() : null;
}
return text;
}
#region IDisposable Support
private bool disposedValue; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.Name = null;
if (this.Value != null)
{
if(NativeMethods.VariantClear(ref this.Value) == Win32Constants.S_OK)
{
this.Value = null;
}
}
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| 37.056701 | 130 | 0.45208 | [
"MIT"
] | chingucoding/axe-windows | src/Core/Bases/A11yProperty.cs | 6,996 | 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 codepipeline-2015-07-09.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.CodePipeline.Model;
namespace Amazon.CodePipeline
{
/// <summary>
/// Interface for accessing CodePipeline
///
/// AWS CodePipeline
/// <para>
/// <b>Overview</b>
/// </para>
///
/// <para>
/// This is the AWS CodePipeline API Reference. This guide provides descriptions of the
/// actions and data types for AWS CodePipeline. Some functionality for your pipeline
/// can only be configured through the API. For more information, see the <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html">AWS
/// CodePipeline User Guide</a>.
/// </para>
///
/// <para>
/// You can use the AWS CodePipeline API to work with pipelines, stages, actions, and
/// transitions.
/// </para>
///
/// <para>
/// <i>Pipelines</i> are models of automated release processes. Each pipeline is uniquely
/// named, and consists of stages, actions, and transitions.
/// </para>
///
/// <para>
/// You can work with pipelines by calling:
/// </para>
/// <ul> <li>
/// <para>
/// <a>CreatePipeline</a>, which creates a uniquely named pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>DeletePipeline</a>, which deletes the specified pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>GetPipeline</a>, which returns information about the pipeline structure and pipeline
/// metadata, including the pipeline Amazon Resource Name (ARN).
/// </para>
/// </li> <li>
/// <para>
/// <a>GetPipelineExecution</a>, which returns information about a specific execution
/// of a pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>GetPipelineState</a>, which returns information about the current state of the
/// stages and actions of a pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>ListActionExecutions</a>, which returns action-level details for past executions.
/// The details include full stage and action-level details, including individual action
/// duration, status, any errors that occurred during the execution, and input and output
/// artifact location details.
/// </para>
/// </li> <li>
/// <para>
/// <a>ListPipelines</a>, which gets a summary of all of the pipelines associated with
/// your account.
/// </para>
/// </li> <li>
/// <para>
/// <a>ListPipelineExecutions</a>, which gets a summary of the most recent executions
/// for a pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>StartPipelineExecution</a>, which runs the most recent revision of an artifact
/// through the pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>StopPipelineExecution</a>, which stops the specified pipeline execution from continuing
/// through the pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>UpdatePipeline</a>, which updates a pipeline with edits or changes to the structure
/// of the pipeline.
/// </para>
/// </li> </ul>
/// <para>
/// Pipelines include <i>stages</i>. Each stage contains one or more actions that must
/// complete before the next stage begins. A stage results in success or failure. If a
/// stage fails, the pipeline stops at that stage and remains stopped until either a new
/// version of an artifact appears in the source location, or a user takes action to rerun
/// the most recent artifact through the pipeline. You can call <a>GetPipelineState</a>,
/// which displays the status of a pipeline, including the status of stages in the pipeline,
/// or <a>GetPipeline</a>, which returns the entire structure of the pipeline, including
/// the stages of that pipeline. For more information about the structure of stages and
/// actions, see <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/pipeline-structure.html">AWS
/// CodePipeline Pipeline Structure Reference</a>.
/// </para>
///
/// <para>
/// Pipeline stages include <i>actions</i> that are categorized into categories such as
/// source or build actions performed in a stage of a pipeline. For example, you can use
/// a source action to import artifacts into a pipeline from a source such as Amazon S3.
/// Like stages, you do not work with actions directly in most cases, but you do define
/// and interact with actions when working with pipeline operations such as <a>CreatePipeline</a>
/// and <a>GetPipelineState</a>. Valid action categories are:
/// </para>
/// <ul> <li>
/// <para>
/// Source
/// </para>
/// </li> <li>
/// <para>
/// Build
/// </para>
/// </li> <li>
/// <para>
/// Test
/// </para>
/// </li> <li>
/// <para>
/// Deploy
/// </para>
/// </li> <li>
/// <para>
/// Approval
/// </para>
/// </li> <li>
/// <para>
/// Invoke
/// </para>
/// </li> </ul>
/// <para>
/// Pipelines also include <i>transitions</i>, which allow the transition of artifacts
/// from one stage to the next in a pipeline after the actions in one stage complete.
/// </para>
///
/// <para>
/// You can work with transitions by calling:
/// </para>
/// <ul> <li>
/// <para>
/// <a>DisableStageTransition</a>, which prevents artifacts from transitioning to the
/// next stage in a pipeline.
/// </para>
/// </li> <li>
/// <para>
/// <a>EnableStageTransition</a>, which enables transition of artifacts between stages
/// in a pipeline.
/// </para>
/// </li> </ul>
/// <para>
/// <b>Using the API to integrate with AWS CodePipeline</b>
/// </para>
///
/// <para>
/// For third-party integrators or developers who want to create their own integrations
/// with AWS CodePipeline, the expected sequence varies from the standard API user. To
/// integrate with AWS CodePipeline, developers need to work with the following items:
/// </para>
///
/// <para>
/// <b>Jobs</b>, which are instances of an action. For example, a job for a source action
/// might import a revision of an artifact from a source.
/// </para>
///
/// <para>
/// You can work with jobs by calling:
/// </para>
/// <ul> <li>
/// <para>
/// <a>AcknowledgeJob</a>, which confirms whether a job worker has received the specified
/// job.
/// </para>
/// </li> <li>
/// <para>
/// <a>GetJobDetails</a>, which returns the details of a job.
/// </para>
/// </li> <li>
/// <para>
/// <a>PollForJobs</a>, which determines whether there are any jobs to act on.
/// </para>
/// </li> <li>
/// <para>
/// <a>PutJobFailureResult</a>, which provides details of a job failure.
/// </para>
/// </li> <li>
/// <para>
/// <a>PutJobSuccessResult</a>, which provides details of a job success.
/// </para>
/// </li> </ul>
/// <para>
/// <b>Third party jobs</b>, which are instances of an action created by a partner action
/// and integrated into AWS CodePipeline. Partner actions are created by members of the
/// AWS Partner Network.
/// </para>
///
/// <para>
/// You can work with third party jobs by calling:
/// </para>
/// <ul> <li>
/// <para>
/// <a>AcknowledgeThirdPartyJob</a>, which confirms whether a job worker has received
/// the specified job.
/// </para>
/// </li> <li>
/// <para>
/// <a>GetThirdPartyJobDetails</a>, which requests the details of a job for a partner
/// action.
/// </para>
/// </li> <li>
/// <para>
/// <a>PollForThirdPartyJobs</a>, which determines whether there are any jobs to act
/// on.
/// </para>
/// </li> <li>
/// <para>
/// <a>PutThirdPartyJobFailureResult</a>, which provides details of a job failure.
/// </para>
/// </li> <li>
/// <para>
/// <a>PutThirdPartyJobSuccessResult</a>, which provides details of a job success.
/// </para>
/// </li> </ul>
/// </summary>
public partial interface IAmazonCodePipeline : IAmazonService, IDisposable
{
/// <summary>
/// Paginators for the service
/// </summary>
ICodePipelinePaginatorFactory Paginators { get; }
#region AcknowledgeJob
/// <summary>
/// Returns information about a specified job and whether that job has been received by
/// the job worker. Used for custom actions only.
/// </summary>
/// <param name="jobId">The unique system-generated ID of the job for which you want to confirm receipt.</param>
/// <param name="nonce">A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response of the <a>PollForJobs</a> request that returned this job.</param>
///
/// <returns>The response from the AcknowledgeJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeJob">REST API Reference for AcknowledgeJob Operation</seealso>
AcknowledgeJobResponse AcknowledgeJob(string jobId, string nonce);
/// <summary>
/// Returns information about a specified job and whether that job has been received by
/// the job worker. Used for custom actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AcknowledgeJob service method.</param>
///
/// <returns>The response from the AcknowledgeJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeJob">REST API Reference for AcknowledgeJob Operation</seealso>
AcknowledgeJobResponse AcknowledgeJob(AcknowledgeJobRequest request);
/// <summary>
/// Returns information about a specified job and whether that job has been received by
/// the job worker. Used for custom actions only.
/// </summary>
/// <param name="jobId">The unique system-generated ID of the job for which you want to confirm receipt.</param>
/// <param name="nonce">A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response of the <a>PollForJobs</a> request that returned this job.</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 AcknowledgeJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeJob">REST API Reference for AcknowledgeJob Operation</seealso>
Task<AcknowledgeJobResponse> AcknowledgeJobAsync(string jobId, string nonce, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns information about a specified job and whether that job has been received by
/// the job worker. Used for custom actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AcknowledgeJob 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 AcknowledgeJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeJob">REST API Reference for AcknowledgeJob Operation</seealso>
Task<AcknowledgeJobResponse> AcknowledgeJobAsync(AcknowledgeJobRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region AcknowledgeThirdPartyJob
/// <summary>
/// Confirms a job worker has received the specified job. Used for partner actions only.
/// </summary>
/// <param name="clientToken">The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.</param>
/// <param name="jobId">The unique system-generated ID of the job.</param>
/// <param name="nonce">A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response to a <a>GetThirdPartyJobDetails</a> request.</param>
///
/// <returns>The response from the AcknowledgeThirdPartyJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob">REST API Reference for AcknowledgeThirdPartyJob Operation</seealso>
AcknowledgeThirdPartyJobResponse AcknowledgeThirdPartyJob(string clientToken, string jobId, string nonce);
/// <summary>
/// Confirms a job worker has received the specified job. Used for partner actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AcknowledgeThirdPartyJob service method.</param>
///
/// <returns>The response from the AcknowledgeThirdPartyJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob">REST API Reference for AcknowledgeThirdPartyJob Operation</seealso>
AcknowledgeThirdPartyJobResponse AcknowledgeThirdPartyJob(AcknowledgeThirdPartyJobRequest request);
/// <summary>
/// Confirms a job worker has received the specified job. Used for partner actions only.
/// </summary>
/// <param name="clientToken">The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.</param>
/// <param name="jobId">The unique system-generated ID of the job.</param>
/// <param name="nonce">A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response to a <a>GetThirdPartyJobDetails</a> request.</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 AcknowledgeThirdPartyJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob">REST API Reference for AcknowledgeThirdPartyJob Operation</seealso>
Task<AcknowledgeThirdPartyJobResponse> AcknowledgeThirdPartyJobAsync(string clientToken, string jobId, string nonce, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Confirms a job worker has received the specified job. Used for partner actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the AcknowledgeThirdPartyJob 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 AcknowledgeThirdPartyJob service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNonceException">
/// The nonce was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/AcknowledgeThirdPartyJob">REST API Reference for AcknowledgeThirdPartyJob Operation</seealso>
Task<AcknowledgeThirdPartyJobResponse> AcknowledgeThirdPartyJobAsync(AcknowledgeThirdPartyJobRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateCustomActionType
/// <summary>
/// Creates a new custom action that can be used in all pipelines associated with the
/// AWS account. Only used for custom actions.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateCustomActionType service method.</param>
///
/// <returns>The response from the CreateCustomActionType service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreateCustomActionType">REST API Reference for CreateCustomActionType Operation</seealso>
CreateCustomActionTypeResponse CreateCustomActionType(CreateCustomActionTypeRequest request);
/// <summary>
/// Creates a new custom action that can be used in all pipelines associated with the
/// AWS account. Only used for custom actions.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateCustomActionType 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 CreateCustomActionType service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreateCustomActionType">REST API Reference for CreateCustomActionType Operation</seealso>
Task<CreateCustomActionTypeResponse> CreateCustomActionTypeAsync(CreateCustomActionTypeRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreatePipeline
/// <summary>
/// Creates a pipeline.
///
/// <note>
/// <para>
/// In the pipeline structure, you must include either <code>artifactStore</code> or <code>artifactStores</code>
/// in your pipeline, but you cannot use both. If you create a cross-region action in
/// your pipeline, you must use <code>artifactStores</code>.
/// </para>
/// </note>
/// </summary>
/// <param name="pipeline">Represents the structure of actions and stages to be performed in the pipeline. </param>
///
/// <returns>The response from the CreatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNameInUseException">
/// The specified pipeline name is already in use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso>
CreatePipelineResponse CreatePipeline(PipelineDeclaration pipeline);
/// <summary>
/// Creates a pipeline.
///
/// <note>
/// <para>
/// In the pipeline structure, you must include either <code>artifactStore</code> or <code>artifactStores</code>
/// in your pipeline, but you cannot use both. If you create a cross-region action in
/// your pipeline, you must use <code>artifactStores</code>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePipeline service method.</param>
///
/// <returns>The response from the CreatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNameInUseException">
/// The specified pipeline name is already in use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso>
CreatePipelineResponse CreatePipeline(CreatePipelineRequest request);
/// <summary>
/// Creates a pipeline.
///
/// <note>
/// <para>
/// In the pipeline structure, you must include either <code>artifactStore</code> or <code>artifactStores</code>
/// in your pipeline, but you cannot use both. If you create a cross-region action in
/// your pipeline, you must use <code>artifactStores</code>.
/// </para>
/// </note>
/// </summary>
/// <param name="pipeline">Represents the structure of actions and stages to be performed in the pipeline. </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 CreatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNameInUseException">
/// The specified pipeline name is already in use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso>
Task<CreatePipelineResponse> CreatePipelineAsync(PipelineDeclaration pipeline, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a pipeline.
///
/// <note>
/// <para>
/// In the pipeline structure, you must include either <code>artifactStore</code> or <code>artifactStores</code>
/// in your pipeline, but you cannot use both. If you create a cross-region action in
/// your pipeline, you must use <code>artifactStores</code>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreatePipeline 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 CreatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNameInUseException">
/// The specified pipeline name is already in use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/CreatePipeline">REST API Reference for CreatePipeline Operation</seealso>
Task<CreatePipelineResponse> CreatePipelineAsync(CreatePipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteCustomActionType
/// <summary>
/// Marks a custom action as deleted. <code>PollForJobs</code> for the custom action fails
/// after the action is marked for deletion. Used for custom actions only.
///
/// <important>
/// <para>
/// To re-create a custom action after it has been deleted you must use a string in the
/// version field that has never been used before. This string can be an incremented version
/// number, for example. To restore a deleted custom action, use a JSON file that is identical
/// to the deleted action, including the original string in the version field.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteCustomActionType service method.</param>
///
/// <returns>The response from the DeleteCustomActionType service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteCustomActionType">REST API Reference for DeleteCustomActionType Operation</seealso>
DeleteCustomActionTypeResponse DeleteCustomActionType(DeleteCustomActionTypeRequest request);
/// <summary>
/// Marks a custom action as deleted. <code>PollForJobs</code> for the custom action fails
/// after the action is marked for deletion. Used for custom actions only.
///
/// <important>
/// <para>
/// To re-create a custom action after it has been deleted you must use a string in the
/// version field that has never been used before. This string can be an incremented version
/// number, for example. To restore a deleted custom action, use a JSON file that is identical
/// to the deleted action, including the original string in the version field.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteCustomActionType 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 DeleteCustomActionType service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteCustomActionType">REST API Reference for DeleteCustomActionType Operation</seealso>
Task<DeleteCustomActionTypeResponse> DeleteCustomActionTypeAsync(DeleteCustomActionTypeRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeletePipeline
/// <summary>
/// Deletes the specified pipeline.
/// </summary>
/// <param name="name">The name of the pipeline to be deleted.</param>
///
/// <returns>The response from the DeletePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso>
DeletePipelineResponse DeletePipeline(string name);
/// <summary>
/// Deletes the specified pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeletePipeline service method.</param>
///
/// <returns>The response from the DeletePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso>
DeletePipelineResponse DeletePipeline(DeletePipelineRequest request);
/// <summary>
/// Deletes the specified pipeline.
/// </summary>
/// <param name="name">The name of the pipeline to be deleted.</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 DeletePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso>
Task<DeletePipelineResponse> DeletePipelineAsync(string name, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeletePipeline 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 DeletePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeletePipeline">REST API Reference for DeletePipeline Operation</seealso>
Task<DeletePipelineResponse> DeletePipelineAsync(DeletePipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteWebhook
/// <summary>
/// Deletes a previously created webhook by name. Deleting the webhook stops AWS CodePipeline
/// from starting a pipeline every time an external event occurs. The API returns successfully
/// when trying to delete a webhook that is already deleted. If a deleted webhook is re-created
/// by calling PutWebhook with the same name, it will have a different URL.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteWebhook service method.</param>
///
/// <returns>The response from the DeleteWebhook service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteWebhook">REST API Reference for DeleteWebhook Operation</seealso>
DeleteWebhookResponse DeleteWebhook(DeleteWebhookRequest request);
/// <summary>
/// Deletes a previously created webhook by name. Deleting the webhook stops AWS CodePipeline
/// from starting a pipeline every time an external event occurs. The API returns successfully
/// when trying to delete a webhook that is already deleted. If a deleted webhook is re-created
/// by calling PutWebhook with the same name, it will have a different URL.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteWebhook 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 DeleteWebhook service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeleteWebhook">REST API Reference for DeleteWebhook Operation</seealso>
Task<DeleteWebhookResponse> DeleteWebhookAsync(DeleteWebhookRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeregisterWebhookWithThirdParty
/// <summary>
/// Removes the connection between the webhook that was created by CodePipeline and the
/// external tool with events to be detected. Currently supported only for webhooks that
/// target an action type of GitHub.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeregisterWebhookWithThirdParty service method.</param>
///
/// <returns>The response from the DeregisterWebhookWithThirdParty service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.WebhookNotFoundException">
/// The specified webhook was entered in an invalid format or cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeregisterWebhookWithThirdParty">REST API Reference for DeregisterWebhookWithThirdParty Operation</seealso>
DeregisterWebhookWithThirdPartyResponse DeregisterWebhookWithThirdParty(DeregisterWebhookWithThirdPartyRequest request);
/// <summary>
/// Removes the connection between the webhook that was created by CodePipeline and the
/// external tool with events to be detected. Currently supported only for webhooks that
/// target an action type of GitHub.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeregisterWebhookWithThirdParty 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 DeregisterWebhookWithThirdParty service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.WebhookNotFoundException">
/// The specified webhook was entered in an invalid format or cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DeregisterWebhookWithThirdParty">REST API Reference for DeregisterWebhookWithThirdParty Operation</seealso>
Task<DeregisterWebhookWithThirdPartyResponse> DeregisterWebhookWithThirdPartyAsync(DeregisterWebhookWithThirdPartyRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DisableStageTransition
/// <summary>
/// Prevents artifacts in a pipeline from transitioning to the next stage in the pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisableStageTransition service method.</param>
///
/// <returns>The response from the DisableStageTransition service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DisableStageTransition">REST API Reference for DisableStageTransition Operation</seealso>
DisableStageTransitionResponse DisableStageTransition(DisableStageTransitionRequest request);
/// <summary>
/// Prevents artifacts in a pipeline from transitioning to the next stage in the pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DisableStageTransition 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 DisableStageTransition service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/DisableStageTransition">REST API Reference for DisableStageTransition Operation</seealso>
Task<DisableStageTransitionResponse> DisableStageTransitionAsync(DisableStageTransitionRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region EnableStageTransition
/// <summary>
/// Enables artifacts in a pipeline to transition to a stage in a pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EnableStageTransition service method.</param>
///
/// <returns>The response from the EnableStageTransition service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/EnableStageTransition">REST API Reference for EnableStageTransition Operation</seealso>
EnableStageTransitionResponse EnableStageTransition(EnableStageTransitionRequest request);
/// <summary>
/// Enables artifacts in a pipeline to transition to a stage in a pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EnableStageTransition 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 EnableStageTransition service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/EnableStageTransition">REST API Reference for EnableStageTransition Operation</seealso>
Task<EnableStageTransitionResponse> EnableStageTransitionAsync(EnableStageTransitionRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetJobDetails
/// <summary>
/// Returns information about a job. Used for custom actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="jobId">The unique system-generated ID for the job.</param>
///
/// <returns>The response from the GetJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetJobDetails">REST API Reference for GetJobDetails Operation</seealso>
GetJobDetailsResponse GetJobDetails(string jobId);
/// <summary>
/// Returns information about a job. Used for custom actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetJobDetails service method.</param>
///
/// <returns>The response from the GetJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetJobDetails">REST API Reference for GetJobDetails Operation</seealso>
GetJobDetailsResponse GetJobDetails(GetJobDetailsRequest request);
/// <summary>
/// Returns information about a job. Used for custom actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="jobId">The unique system-generated ID for the job.</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 GetJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetJobDetails">REST API Reference for GetJobDetails Operation</seealso>
Task<GetJobDetailsResponse> GetJobDetailsAsync(string jobId, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns information about a job. Used for custom actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetJobDetails 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 GetJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetJobDetails">REST API Reference for GetJobDetails Operation</seealso>
Task<GetJobDetailsResponse> GetJobDetailsAsync(GetJobDetailsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetPipeline
/// <summary>
/// Returns the metadata, structure, stages, and actions of a pipeline. Can be used to
/// return the entire structure of a pipeline in JSON format, which can then be modified
/// and used to update the pipeline structure with <a>UpdatePipeline</a>.
/// </summary>
/// <param name="name">The name of the pipeline for which you want to get information. Pipeline names must be unique under an AWS user account.</param>
/// <param name="version">The version number of the pipeline. If you do not specify a version, defaults to the current version.</param>
///
/// <returns>The response from the GetPipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineVersionNotFoundException">
/// The pipeline version was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline">REST API Reference for GetPipeline Operation</seealso>
GetPipelineResponse GetPipeline(string name, int version);
/// <summary>
/// Returns the metadata, structure, stages, and actions of a pipeline. Can be used to
/// return the entire structure of a pipeline in JSON format, which can then be modified
/// and used to update the pipeline structure with <a>UpdatePipeline</a>.
/// </summary>
/// <param name="name">The name of the pipeline for which you want to get information. Pipeline names must be unique under an AWS user account.</param>
///
/// <returns>The response from the GetPipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineVersionNotFoundException">
/// The pipeline version was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline">REST API Reference for GetPipeline Operation</seealso>
GetPipelineResponse GetPipeline(string name);
/// <summary>
/// Returns the metadata, structure, stages, and actions of a pipeline. Can be used to
/// return the entire structure of a pipeline in JSON format, which can then be modified
/// and used to update the pipeline structure with <a>UpdatePipeline</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPipeline service method.</param>
///
/// <returns>The response from the GetPipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineVersionNotFoundException">
/// The pipeline version was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline">REST API Reference for GetPipeline Operation</seealso>
GetPipelineResponse GetPipeline(GetPipelineRequest request);
/// <summary>
/// Returns the metadata, structure, stages, and actions of a pipeline. Can be used to
/// return the entire structure of a pipeline in JSON format, which can then be modified
/// and used to update the pipeline structure with <a>UpdatePipeline</a>.
/// </summary>
/// <param name="name">The name of the pipeline for which you want to get information. Pipeline names must be unique under an AWS user account.</param>
/// <param name="version">The version number of the pipeline. If you do not specify a version, defaults to the current version.</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 GetPipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineVersionNotFoundException">
/// The pipeline version was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline">REST API Reference for GetPipeline Operation</seealso>
Task<GetPipelineResponse> GetPipelineAsync(string name, int version, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the metadata, structure, stages, and actions of a pipeline. Can be used to
/// return the entire structure of a pipeline in JSON format, which can then be modified
/// and used to update the pipeline structure with <a>UpdatePipeline</a>.
/// </summary>
/// <param name="name">The name of the pipeline for which you want to get information. Pipeline names must be unique under an AWS user account.</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 GetPipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineVersionNotFoundException">
/// The pipeline version was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline">REST API Reference for GetPipeline Operation</seealso>
Task<GetPipelineResponse> GetPipelineAsync(string name, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the metadata, structure, stages, and actions of a pipeline. Can be used to
/// return the entire structure of a pipeline in JSON format, which can then be modified
/// and used to update the pipeline structure with <a>UpdatePipeline</a>.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPipeline 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 GetPipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineVersionNotFoundException">
/// The pipeline version was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipeline">REST API Reference for GetPipeline Operation</seealso>
Task<GetPipelineResponse> GetPipelineAsync(GetPipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetPipelineExecution
/// <summary>
/// Returns information about an execution of a pipeline, including details about artifacts,
/// the pipeline execution ID, and the name, version, and status of the pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPipelineExecution service method.</param>
///
/// <returns>The response from the GetPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineExecutionNotFoundException">
/// The pipeline execution was specified in an invalid format or cannot be found, or an
/// execution ID does not belong to the specified pipeline.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineExecution">REST API Reference for GetPipelineExecution Operation</seealso>
GetPipelineExecutionResponse GetPipelineExecution(GetPipelineExecutionRequest request);
/// <summary>
/// Returns information about an execution of a pipeline, including details about artifacts,
/// the pipeline execution ID, and the name, version, and status of the pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPipelineExecution 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 GetPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineExecutionNotFoundException">
/// The pipeline execution was specified in an invalid format or cannot be found, or an
/// execution ID does not belong to the specified pipeline.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineExecution">REST API Reference for GetPipelineExecution Operation</seealso>
Task<GetPipelineExecutionResponse> GetPipelineExecutionAsync(GetPipelineExecutionRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetPipelineState
/// <summary>
/// Returns information about the state of a pipeline, including the stages and actions.
///
/// <note>
/// <para>
/// Values returned in the <code>revisionId</code> and <code>revisionUrl</code> fields
/// indicate the source revision information, such as the commit ID, for the current state.
/// </para>
/// </note>
/// </summary>
/// <param name="name">The name of the pipeline about which you want to get information.</param>
///
/// <returns>The response from the GetPipelineState service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineState">REST API Reference for GetPipelineState Operation</seealso>
GetPipelineStateResponse GetPipelineState(string name);
/// <summary>
/// Returns information about the state of a pipeline, including the stages and actions.
///
/// <note>
/// <para>
/// Values returned in the <code>revisionId</code> and <code>revisionUrl</code> fields
/// indicate the source revision information, such as the commit ID, for the current state.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPipelineState service method.</param>
///
/// <returns>The response from the GetPipelineState service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineState">REST API Reference for GetPipelineState Operation</seealso>
GetPipelineStateResponse GetPipelineState(GetPipelineStateRequest request);
/// <summary>
/// Returns information about the state of a pipeline, including the stages and actions.
///
/// <note>
/// <para>
/// Values returned in the <code>revisionId</code> and <code>revisionUrl</code> fields
/// indicate the source revision information, such as the commit ID, for the current state.
/// </para>
/// </note>
/// </summary>
/// <param name="name">The name of the pipeline about which you want to get information.</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 GetPipelineState service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineState">REST API Reference for GetPipelineState Operation</seealso>
Task<GetPipelineStateResponse> GetPipelineStateAsync(string name, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns information about the state of a pipeline, including the stages and actions.
///
/// <note>
/// <para>
/// Values returned in the <code>revisionId</code> and <code>revisionUrl</code> fields
/// indicate the source revision information, such as the commit ID, for the current state.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetPipelineState 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 GetPipelineState service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetPipelineState">REST API Reference for GetPipelineState Operation</seealso>
Task<GetPipelineStateResponse> GetPipelineStateAsync(GetPipelineStateRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetThirdPartyJobDetails
/// <summary>
/// Requests the details of a job for a third party action. Used for partner actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="clientToken">The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.</param>
/// <param name="jobId">The unique system-generated ID used for identifying the job.</param>
///
/// <returns>The response from the GetThirdPartyJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetThirdPartyJobDetails">REST API Reference for GetThirdPartyJobDetails Operation</seealso>
GetThirdPartyJobDetailsResponse GetThirdPartyJobDetails(string clientToken, string jobId);
/// <summary>
/// Requests the details of a job for a third party action. Used for partner actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetThirdPartyJobDetails service method.</param>
///
/// <returns>The response from the GetThirdPartyJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetThirdPartyJobDetails">REST API Reference for GetThirdPartyJobDetails Operation</seealso>
GetThirdPartyJobDetailsResponse GetThirdPartyJobDetails(GetThirdPartyJobDetailsRequest request);
/// <summary>
/// Requests the details of a job for a third party action. Used for partner actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="clientToken">The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.</param>
/// <param name="jobId">The unique system-generated ID used for identifying the job.</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 GetThirdPartyJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetThirdPartyJobDetails">REST API Reference for GetThirdPartyJobDetails Operation</seealso>
Task<GetThirdPartyJobDetailsResponse> GetThirdPartyJobDetailsAsync(string clientToken, string jobId, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Requests the details of a job for a third party action. Used for partner actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetThirdPartyJobDetails 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 GetThirdPartyJobDetails service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/GetThirdPartyJobDetails">REST API Reference for GetThirdPartyJobDetails Operation</seealso>
Task<GetThirdPartyJobDetailsResponse> GetThirdPartyJobDetailsAsync(GetThirdPartyJobDetailsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListActionExecutions
/// <summary>
/// Lists the action executions that have occurred in a pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListActionExecutions service method.</param>
///
/// <returns>The response from the ListActionExecutions service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineExecutionNotFoundException">
/// The pipeline execution was specified in an invalid format or cannot be found, or an
/// execution ID does not belong to the specified pipeline.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionExecutions">REST API Reference for ListActionExecutions Operation</seealso>
ListActionExecutionsResponse ListActionExecutions(ListActionExecutionsRequest request);
/// <summary>
/// Lists the action executions that have occurred in a pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListActionExecutions 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 ListActionExecutions service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineExecutionNotFoundException">
/// The pipeline execution was specified in an invalid format or cannot be found, or an
/// execution ID does not belong to the specified pipeline.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionExecutions">REST API Reference for ListActionExecutions Operation</seealso>
Task<ListActionExecutionsResponse> ListActionExecutionsAsync(ListActionExecutionsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListActionTypes
/// <summary>
/// Gets a summary of all AWS CodePipeline action types associated with your account.
/// </summary>
///
/// <returns>The response from the ListActionTypes service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes">REST API Reference for ListActionTypes Operation</seealso>
ListActionTypesResponse ListActionTypes();
/// <summary>
/// Gets a summary of all AWS CodePipeline action types associated with your account.
/// </summary>
/// <param name="actionOwnerFilter">Filters the list of action types to those created by a specified entity.</param>
///
/// <returns>The response from the ListActionTypes service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes">REST API Reference for ListActionTypes Operation</seealso>
ListActionTypesResponse ListActionTypes(ActionOwner actionOwnerFilter);
/// <summary>
/// Gets a summary of all AWS CodePipeline action types associated with your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListActionTypes service method.</param>
///
/// <returns>The response from the ListActionTypes service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes">REST API Reference for ListActionTypes Operation</seealso>
ListActionTypesResponse ListActionTypes(ListActionTypesRequest request);
/// <summary>
/// Gets a summary of all AWS CodePipeline action types associated with your account.
/// </summary>
/// <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 ListActionTypes service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes">REST API Reference for ListActionTypes Operation</seealso>
Task<ListActionTypesResponse> ListActionTypesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a summary of all AWS CodePipeline action types associated with your account.
/// </summary>
/// <param name="actionOwnerFilter">Filters the list of action types to those created by a specified entity.</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 ListActionTypes service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes">REST API Reference for ListActionTypes Operation</seealso>
Task<ListActionTypesResponse> ListActionTypesAsync(ActionOwner actionOwnerFilter, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a summary of all AWS CodePipeline action types associated with your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListActionTypes 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 ListActionTypes service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListActionTypes">REST API Reference for ListActionTypes Operation</seealso>
Task<ListActionTypesResponse> ListActionTypesAsync(ListActionTypesRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPipelineExecutions
/// <summary>
/// Gets a summary of the most recent executions for a pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPipelineExecutions service method.</param>
///
/// <returns>The response from the ListPipelineExecutions service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelineExecutions">REST API Reference for ListPipelineExecutions Operation</seealso>
ListPipelineExecutionsResponse ListPipelineExecutions(ListPipelineExecutionsRequest request);
/// <summary>
/// Gets a summary of the most recent executions for a pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPipelineExecutions 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 ListPipelineExecutions service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelineExecutions">REST API Reference for ListPipelineExecutions Operation</seealso>
Task<ListPipelineExecutionsResponse> ListPipelineExecutionsAsync(ListPipelineExecutionsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListPipelines
/// <summary>
/// Gets a summary of all of the pipelines associated with your account.
/// </summary>
///
/// <returns>The response from the ListPipelines service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
ListPipelinesResponse ListPipelines();
/// <summary>
/// Gets a summary of all of the pipelines associated with your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPipelines service method.</param>
///
/// <returns>The response from the ListPipelines service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
ListPipelinesResponse ListPipelines(ListPipelinesRequest request);
/// <summary>
/// Gets a summary of all of the pipelines associated with your account.
/// </summary>
/// <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 ListPipelines service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
Task<ListPipelinesResponse> ListPipelinesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a summary of all of the pipelines associated with your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListPipelines 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 ListPipelines service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListPipelines">REST API Reference for ListPipelines Operation</seealso>
Task<ListPipelinesResponse> ListPipelinesAsync(ListPipelinesRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListTagsForResource
/// <summary>
/// Gets the set of key-value pairs (metadata) that are used to manage the 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 CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidArnException">
/// The specified resource ARN is invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ResourceNotFoundException">
/// The resource was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request);
/// <summary>
/// Gets the set of key-value pairs (metadata) that are used to manage the 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 CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidArnException">
/// The specified resource ARN is invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ResourceNotFoundException">
/// The resource was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListWebhooks
/// <summary>
/// Gets a listing of all the webhooks in this AWS Region for this account. The output
/// lists all webhooks and includes the webhook URL and ARN and the configuration for
/// each webhook.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListWebhooks service method.</param>
///
/// <returns>The response from the ListWebhooks service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListWebhooks">REST API Reference for ListWebhooks Operation</seealso>
ListWebhooksResponse ListWebhooks(ListWebhooksRequest request);
/// <summary>
/// Gets a listing of all the webhooks in this AWS Region for this account. The output
/// lists all webhooks and includes the webhook URL and ARN and the configuration for
/// each webhook.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListWebhooks 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 ListWebhooks service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidNextTokenException">
/// The next token was specified in an invalid format. Make sure that the next token you
/// provide is the token returned by a previous call.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/ListWebhooks">REST API Reference for ListWebhooks Operation</seealso>
Task<ListWebhooksResponse> ListWebhooksAsync(ListWebhooksRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PollForJobs
/// <summary>
/// Returns information about any jobs for AWS CodePipeline to act on. <code>PollForJobs</code>
/// is valid only for action types with "Custom" in the owner field. If the action type
/// contains "AWS" or "ThirdParty" in the owner field, the <code>PollForJobs</code> action
/// returns an error.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PollForJobs service method.</param>
///
/// <returns>The response from the PollForJobs service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionTypeNotFoundException">
/// The specified action type cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForJobs">REST API Reference for PollForJobs Operation</seealso>
PollForJobsResponse PollForJobs(PollForJobsRequest request);
/// <summary>
/// Returns information about any jobs for AWS CodePipeline to act on. <code>PollForJobs</code>
/// is valid only for action types with "Custom" in the owner field. If the action type
/// contains "AWS" or "ThirdParty" in the owner field, the <code>PollForJobs</code> action
/// returns an error.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts. This API also returns any secret values
/// defined for the action.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PollForJobs 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 PollForJobs service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionTypeNotFoundException">
/// The specified action type cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForJobs">REST API Reference for PollForJobs Operation</seealso>
Task<PollForJobsResponse> PollForJobsAsync(PollForJobsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PollForThirdPartyJobs
/// <summary>
/// Determines whether there are any third party jobs for a job worker to act on. Used
/// for partner actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PollForThirdPartyJobs service method.</param>
///
/// <returns>The response from the PollForThirdPartyJobs service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionTypeNotFoundException">
/// The specified action type cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForThirdPartyJobs">REST API Reference for PollForThirdPartyJobs Operation</seealso>
PollForThirdPartyJobsResponse PollForThirdPartyJobs(PollForThirdPartyJobsRequest request);
/// <summary>
/// Determines whether there are any third party jobs for a job worker to act on. Used
/// for partner actions only.
///
/// <important>
/// <para>
/// When this API is called, AWS CodePipeline returns temporary credentials for the S3
/// bucket used to store artifacts for the pipeline, if the action requires access to
/// that S3 bucket for input or output artifacts.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PollForThirdPartyJobs 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 PollForThirdPartyJobs service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionTypeNotFoundException">
/// The specified action type cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PollForThirdPartyJobs">REST API Reference for PollForThirdPartyJobs Operation</seealso>
Task<PollForThirdPartyJobsResponse> PollForThirdPartyJobsAsync(PollForThirdPartyJobsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutActionRevision
/// <summary>
/// Provides information to AWS CodePipeline about new revisions to a source.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutActionRevision service method.</param>
///
/// <returns>The response from the PutActionRevision service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionNotFoundException">
/// The specified action cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutActionRevision">REST API Reference for PutActionRevision Operation</seealso>
PutActionRevisionResponse PutActionRevision(PutActionRevisionRequest request);
/// <summary>
/// Provides information to AWS CodePipeline about new revisions to a source.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutActionRevision 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 PutActionRevision service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionNotFoundException">
/// The specified action cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutActionRevision">REST API Reference for PutActionRevision Operation</seealso>
Task<PutActionRevisionResponse> PutActionRevisionAsync(PutActionRevisionRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutApprovalResult
/// <summary>
/// Provides the response to a manual approval request to AWS CodePipeline. Valid responses
/// include Approved and Rejected.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutApprovalResult service method.</param>
///
/// <returns>The response from the PutApprovalResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionNotFoundException">
/// The specified action cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ApprovalAlreadyCompletedException">
/// The approval action has already been approved or rejected.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidApprovalTokenException">
/// The approval request already received a response or has expired.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutApprovalResult">REST API Reference for PutApprovalResult Operation</seealso>
PutApprovalResultResponse PutApprovalResult(PutApprovalResultRequest request);
/// <summary>
/// Provides the response to a manual approval request to AWS CodePipeline. Valid responses
/// include Approved and Rejected.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutApprovalResult 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 PutApprovalResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ActionNotFoundException">
/// The specified action cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ApprovalAlreadyCompletedException">
/// The approval action has already been approved or rejected.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidApprovalTokenException">
/// The approval request already received a response or has expired.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutApprovalResult">REST API Reference for PutApprovalResult Operation</seealso>
Task<PutApprovalResultResponse> PutApprovalResultAsync(PutApprovalResultRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutJobFailureResult
/// <summary>
/// Represents the failure of a job as returned to the pipeline by a job worker. Used
/// for custom actions only.
/// </summary>
/// <param name="jobId">The unique system-generated ID of the job that failed. This is the same ID returned from <code>PollForJobs</code>.</param>
/// <param name="failureDetails">The details about the failure of a job.</param>
///
/// <returns>The response from the PutJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobFailureResult">REST API Reference for PutJobFailureResult Operation</seealso>
PutJobFailureResultResponse PutJobFailureResult(string jobId, FailureDetails failureDetails);
/// <summary>
/// Represents the failure of a job as returned to the pipeline by a job worker. Used
/// for custom actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutJobFailureResult service method.</param>
///
/// <returns>The response from the PutJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobFailureResult">REST API Reference for PutJobFailureResult Operation</seealso>
PutJobFailureResultResponse PutJobFailureResult(PutJobFailureResultRequest request);
/// <summary>
/// Represents the failure of a job as returned to the pipeline by a job worker. Used
/// for custom actions only.
/// </summary>
/// <param name="jobId">The unique system-generated ID of the job that failed. This is the same ID returned from <code>PollForJobs</code>.</param>
/// <param name="failureDetails">The details about the failure of a job.</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 PutJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobFailureResult">REST API Reference for PutJobFailureResult Operation</seealso>
Task<PutJobFailureResultResponse> PutJobFailureResultAsync(string jobId, FailureDetails failureDetails, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Represents the failure of a job as returned to the pipeline by a job worker. Used
/// for custom actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutJobFailureResult 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 PutJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobFailureResult">REST API Reference for PutJobFailureResult Operation</seealso>
Task<PutJobFailureResultResponse> PutJobFailureResultAsync(PutJobFailureResultRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutJobSuccessResult
/// <summary>
/// Represents the success of a job as returned to the pipeline by a job worker. Used
/// for custom actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutJobSuccessResult service method.</param>
///
/// <returns>The response from the PutJobSuccessResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.OutputVariablesSizeExceededException">
/// Exceeded the total size limit for all variables in the pipeline.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobSuccessResult">REST API Reference for PutJobSuccessResult Operation</seealso>
PutJobSuccessResultResponse PutJobSuccessResult(PutJobSuccessResultRequest request);
/// <summary>
/// Represents the success of a job as returned to the pipeline by a job worker. Used
/// for custom actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutJobSuccessResult 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 PutJobSuccessResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.OutputVariablesSizeExceededException">
/// Exceeded the total size limit for all variables in the pipeline.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutJobSuccessResult">REST API Reference for PutJobSuccessResult Operation</seealso>
Task<PutJobSuccessResultResponse> PutJobSuccessResultAsync(PutJobSuccessResultRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutThirdPartyJobFailureResult
/// <summary>
/// Represents the failure of a third party job as returned to the pipeline by a job worker.
/// Used for partner actions only.
/// </summary>
/// <param name="jobId">The ID of the job that failed. This is the same ID returned from <code>PollForThirdPartyJobs</code>.</param>
/// <param name="clientToken">The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.</param>
/// <param name="failureDetails">Represents information about failure details.</param>
///
/// <returns>The response from the PutThirdPartyJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobFailureResult">REST API Reference for PutThirdPartyJobFailureResult Operation</seealso>
PutThirdPartyJobFailureResultResponse PutThirdPartyJobFailureResult(string jobId, string clientToken, FailureDetails failureDetails);
/// <summary>
/// Represents the failure of a third party job as returned to the pipeline by a job worker.
/// Used for partner actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutThirdPartyJobFailureResult service method.</param>
///
/// <returns>The response from the PutThirdPartyJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobFailureResult">REST API Reference for PutThirdPartyJobFailureResult Operation</seealso>
PutThirdPartyJobFailureResultResponse PutThirdPartyJobFailureResult(PutThirdPartyJobFailureResultRequest request);
/// <summary>
/// Represents the failure of a third party job as returned to the pipeline by a job worker.
/// Used for partner actions only.
/// </summary>
/// <param name="jobId">The ID of the job that failed. This is the same ID returned from <code>PollForThirdPartyJobs</code>.</param>
/// <param name="clientToken">The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.</param>
/// <param name="failureDetails">Represents information about failure details.</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 PutThirdPartyJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobFailureResult">REST API Reference for PutThirdPartyJobFailureResult Operation</seealso>
Task<PutThirdPartyJobFailureResultResponse> PutThirdPartyJobFailureResultAsync(string jobId, string clientToken, FailureDetails failureDetails, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Represents the failure of a third party job as returned to the pipeline by a job worker.
/// Used for partner actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutThirdPartyJobFailureResult 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 PutThirdPartyJobFailureResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobFailureResult">REST API Reference for PutThirdPartyJobFailureResult Operation</seealso>
Task<PutThirdPartyJobFailureResultResponse> PutThirdPartyJobFailureResultAsync(PutThirdPartyJobFailureResultRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutThirdPartyJobSuccessResult
/// <summary>
/// Represents the success of a third party job as returned to the pipeline by a job worker.
/// Used for partner actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutThirdPartyJobSuccessResult service method.</param>
///
/// <returns>The response from the PutThirdPartyJobSuccessResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobSuccessResult">REST API Reference for PutThirdPartyJobSuccessResult Operation</seealso>
PutThirdPartyJobSuccessResultResponse PutThirdPartyJobSuccessResult(PutThirdPartyJobSuccessResultRequest request);
/// <summary>
/// Represents the success of a third party job as returned to the pipeline by a job worker.
/// Used for partner actions only.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutThirdPartyJobSuccessResult 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 PutThirdPartyJobSuccessResult service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidClientTokenException">
/// The client token was specified in an invalid format
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidJobStateException">
/// The job state was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.JobNotFoundException">
/// The job was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutThirdPartyJobSuccessResult">REST API Reference for PutThirdPartyJobSuccessResult Operation</seealso>
Task<PutThirdPartyJobSuccessResultResponse> PutThirdPartyJobSuccessResultAsync(PutThirdPartyJobSuccessResultRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region PutWebhook
/// <summary>
/// Defines a webhook and returns a unique webhook URL generated by CodePipeline. This
/// URL can be supplied to third party source hosting providers to call every time there's
/// a code change. When CodePipeline receives a POST request on this URL, the pipeline
/// defined in the webhook is started as long as the POST request satisfied the authentication
/// and filtering requirements supplied when defining the webhook. RegisterWebhookWithThirdParty
/// and DeregisterWebhookWithThirdParty APIs can be used to automatically configure supported
/// third parties to call the generated webhook URL.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutWebhook service method.</param>
///
/// <returns>The response from the PutWebhook service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidWebhookAuthenticationParametersException">
/// The specified authentication type is in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidWebhookFilterPatternException">
/// The specified event filter rule is in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutWebhook">REST API Reference for PutWebhook Operation</seealso>
PutWebhookResponse PutWebhook(PutWebhookRequest request);
/// <summary>
/// Defines a webhook and returns a unique webhook URL generated by CodePipeline. This
/// URL can be supplied to third party source hosting providers to call every time there's
/// a code change. When CodePipeline receives a POST request on this URL, the pipeline
/// defined in the webhook is started as long as the POST request satisfied the authentication
/// and filtering requirements supplied when defining the webhook. RegisterWebhookWithThirdParty
/// and DeregisterWebhookWithThirdParty APIs can be used to automatically configure supported
/// third parties to call the generated webhook URL.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the PutWebhook 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 PutWebhook service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidWebhookAuthenticationParametersException">
/// The specified authentication type is in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidWebhookFilterPatternException">
/// The specified event filter rule is in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/PutWebhook">REST API Reference for PutWebhook Operation</seealso>
Task<PutWebhookResponse> PutWebhookAsync(PutWebhookRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RegisterWebhookWithThirdParty
/// <summary>
/// Configures a connection between the webhook that was created and the external tool
/// with events to be detected.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RegisterWebhookWithThirdParty service method.</param>
///
/// <returns>The response from the RegisterWebhookWithThirdParty service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.WebhookNotFoundException">
/// The specified webhook was entered in an invalid format or cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RegisterWebhookWithThirdParty">REST API Reference for RegisterWebhookWithThirdParty Operation</seealso>
RegisterWebhookWithThirdPartyResponse RegisterWebhookWithThirdParty(RegisterWebhookWithThirdPartyRequest request);
/// <summary>
/// Configures a connection between the webhook that was created and the external tool
/// with events to be detected.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RegisterWebhookWithThirdParty 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 RegisterWebhookWithThirdParty service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.WebhookNotFoundException">
/// The specified webhook was entered in an invalid format or cannot be found.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RegisterWebhookWithThirdParty">REST API Reference for RegisterWebhookWithThirdParty Operation</seealso>
Task<RegisterWebhookWithThirdPartyResponse> RegisterWebhookWithThirdPartyAsync(RegisterWebhookWithThirdPartyRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RetryStageExecution
/// <summary>
/// Resumes the pipeline execution by retrying the last failed actions in a stage. You
/// can retry a stage immediately if any of the actions in the stage fail. When you retry,
/// all actions that are still in progress continue working, and failed actions are triggered
/// again.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RetryStageExecution service method.</param>
///
/// <returns>The response from the RetryStageExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.NotLatestPipelineExecutionException">
/// The stage has failed in a later run of the pipeline and the pipelineExecutionId associated
/// with the request is out of date.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotRetryableException">
/// Unable to retry. The pipeline structure or stage state might have changed while actions
/// awaited retry, or the stage contains no failed actions.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RetryStageExecution">REST API Reference for RetryStageExecution Operation</seealso>
RetryStageExecutionResponse RetryStageExecution(RetryStageExecutionRequest request);
/// <summary>
/// Resumes the pipeline execution by retrying the last failed actions in a stage. You
/// can retry a stage immediately if any of the actions in the stage fail. When you retry,
/// all actions that are still in progress continue working, and failed actions are triggered
/// again.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RetryStageExecution 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 RetryStageExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.NotLatestPipelineExecutionException">
/// The stage has failed in a later run of the pipeline and the pipelineExecutionId associated
/// with the request is out of date.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotFoundException">
/// The stage was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.StageNotRetryableException">
/// Unable to retry. The pipeline structure or stage state might have changed while actions
/// awaited retry, or the stage contains no failed actions.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/RetryStageExecution">REST API Reference for RetryStageExecution Operation</seealso>
Task<RetryStageExecutionResponse> RetryStageExecutionAsync(RetryStageExecutionRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region StartPipelineExecution
/// <summary>
/// Starts the specified pipeline. Specifically, it begins processing the latest commit
/// to the source location specified as part of the pipeline.
/// </summary>
/// <param name="name">The name of the pipeline to start.</param>
///
/// <returns>The response from the StartPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StartPipelineExecution">REST API Reference for StartPipelineExecution Operation</seealso>
StartPipelineExecutionResponse StartPipelineExecution(string name);
/// <summary>
/// Starts the specified pipeline. Specifically, it begins processing the latest commit
/// to the source location specified as part of the pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartPipelineExecution service method.</param>
///
/// <returns>The response from the StartPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StartPipelineExecution">REST API Reference for StartPipelineExecution Operation</seealso>
StartPipelineExecutionResponse StartPipelineExecution(StartPipelineExecutionRequest request);
/// <summary>
/// Starts the specified pipeline. Specifically, it begins processing the latest commit
/// to the source location specified as part of the pipeline.
/// </summary>
/// <param name="name">The name of the pipeline to start.</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 StartPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StartPipelineExecution">REST API Reference for StartPipelineExecution Operation</seealso>
Task<StartPipelineExecutionResponse> StartPipelineExecutionAsync(string name, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Starts the specified pipeline. Specifically, it begins processing the latest commit
/// to the source location specified as part of the pipeline.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartPipelineExecution 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 StartPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StartPipelineExecution">REST API Reference for StartPipelineExecution Operation</seealso>
Task<StartPipelineExecutionResponse> StartPipelineExecutionAsync(StartPipelineExecutionRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region StopPipelineExecution
/// <summary>
/// Stops the specified pipeline execution. You choose to either stop the pipeline execution
/// by completing in-progress actions without starting subsequent actions, or by abandoning
/// in-progress actions. While completing or abandoning in-progress actions, the pipeline
/// execution is in a <code>Stopping</code> state. After all in-progress actions are completed
/// or abandoned, the pipeline execution is in a <code>Stopped</code> state.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopPipelineExecution service method.</param>
///
/// <returns>The response from the StopPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.DuplicatedStopRequestException">
/// The pipeline execution is already in a <code>Stopping</code> state. If you already
/// chose to stop and wait, you cannot make that request again. You can choose to stop
/// and abandon now, but be aware that this option can lead to failed tasks or out of
/// sequence tasks. If you already chose to stop and abandon, you cannot make that request
/// again.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineExecutionNotStoppableException">
/// Unable to stop the pipeline execution. The execution might already be in a <code>Stopped</code>
/// state, or it might no longer be in progress.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StopPipelineExecution">REST API Reference for StopPipelineExecution Operation</seealso>
StopPipelineExecutionResponse StopPipelineExecution(StopPipelineExecutionRequest request);
/// <summary>
/// Stops the specified pipeline execution. You choose to either stop the pipeline execution
/// by completing in-progress actions without starting subsequent actions, or by abandoning
/// in-progress actions. While completing or abandoning in-progress actions, the pipeline
/// execution is in a <code>Stopping</code> state. After all in-progress actions are completed
/// or abandoned, the pipeline execution is in a <code>Stopped</code> state.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopPipelineExecution 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 StopPipelineExecution service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.DuplicatedStopRequestException">
/// The pipeline execution is already in a <code>Stopping</code> state. If you already
/// chose to stop and wait, you cannot make that request again. You can choose to stop
/// and abandon now, but be aware that this option can lead to failed tasks or out of
/// sequence tasks. If you already chose to stop and abandon, you cannot make that request
/// again.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineExecutionNotStoppableException">
/// Unable to stop the pipeline execution. The execution might already be in a <code>Stopped</code>
/// state, or it might no longer be in progress.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.PipelineNotFoundException">
/// The pipeline was specified in an invalid format or cannot be found.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/StopPipelineExecution">REST API Reference for StopPipelineExecution Operation</seealso>
Task<StopPipelineExecutionResponse> StopPipelineExecutionAsync(StopPipelineExecutionRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region TagResource
/// <summary>
/// Adds to or modifies the tags of the given resource. Tags are metadata that can be
/// used to manage a 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 CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidArnException">
/// The specified resource ARN is invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ResourceNotFoundException">
/// The resource was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/TagResource">REST API Reference for TagResource Operation</seealso>
TagResourceResponse TagResource(TagResourceRequest request);
/// <summary>
/// Adds to or modifies the tags of the given resource. Tags are metadata that can be
/// used to manage a 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 CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidArnException">
/// The specified resource ARN is invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ResourceNotFoundException">
/// The resource was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.TooManyTagsException">
/// The tags limit for a resource has been exceeded.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/TagResource">REST API Reference for TagResource Operation</seealso>
Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UntagResource
/// <summary>
/// Removes tags 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 CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidArnException">
/// The specified resource ARN is invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ResourceNotFoundException">
/// The resource was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UntagResource">REST API Reference for UntagResource Operation</seealso>
UntagResourceResponse UntagResource(UntagResourceRequest request);
/// <summary>
/// Removes tags 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 CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.ConcurrentModificationException">
/// Unable to modify the tag due to a simultaneous update request.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidArnException">
/// The specified resource ARN is invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidTagsException">
/// The specified resource tags are invalid.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ResourceNotFoundException">
/// The resource was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UntagResource">REST API Reference for UntagResource Operation</seealso>
Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdatePipeline
/// <summary>
/// Updates a specified pipeline with edits or changes to its structure. Use a JSON file
/// with the pipeline structure and <code>UpdatePipeline</code> to provide the full structure
/// of the pipeline. Updating the pipeline increases the version number of the pipeline
/// by 1.
/// </summary>
/// <param name="pipeline">The name of the pipeline to be updated.</param>
///
/// <returns>The response from the UpdatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdatePipeline">REST API Reference for UpdatePipeline Operation</seealso>
UpdatePipelineResponse UpdatePipeline(PipelineDeclaration pipeline);
/// <summary>
/// Updates a specified pipeline with edits or changes to its structure. Use a JSON file
/// with the pipeline structure and <code>UpdatePipeline</code> to provide the full structure
/// of the pipeline. Updating the pipeline increases the version number of the pipeline
/// by 1.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdatePipeline service method.</param>
///
/// <returns>The response from the UpdatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdatePipeline">REST API Reference for UpdatePipeline Operation</seealso>
UpdatePipelineResponse UpdatePipeline(UpdatePipelineRequest request);
/// <summary>
/// Updates a specified pipeline with edits or changes to its structure. Use a JSON file
/// with the pipeline structure and <code>UpdatePipeline</code> to provide the full structure
/// of the pipeline. Updating the pipeline increases the version number of the pipeline
/// by 1.
/// </summary>
/// <param name="pipeline">The name of the pipeline to be updated.</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 UpdatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdatePipeline">REST API Reference for UpdatePipeline Operation</seealso>
Task<UpdatePipelineResponse> UpdatePipelineAsync(PipelineDeclaration pipeline, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a specified pipeline with edits or changes to its structure. Use a JSON file
/// with the pipeline structure and <code>UpdatePipeline</code> to provide the full structure
/// of the pipeline. Updating the pipeline increases the version number of the pipeline
/// by 1.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdatePipeline 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 UpdatePipeline service method, as returned by CodePipeline.</returns>
/// <exception cref="Amazon.CodePipeline.Model.InvalidActionDeclarationException">
/// The action declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidBlockerDeclarationException">
/// Reserved for future use.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStageDeclarationException">
/// The stage declaration was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.InvalidStructureException">
/// The structure was specified in an invalid format.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.LimitExceededException">
/// The number of pipelines associated with the AWS account has exceeded the limit allowed
/// for the account.
/// </exception>
/// <exception cref="Amazon.CodePipeline.Model.ValidationException">
/// The validation was specified in an invalid format.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/codepipeline-2015-07-09/UpdatePipeline">REST API Reference for UpdatePipeline Operation</seealso>
Task<UpdatePipelineResponse> UpdatePipelineAsync(UpdatePipelineRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
} | 58.696337 | 257 | 0.671428 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodePipeline/Generated/_bcl45/IAmazonCodePipeline.cs | 182,663 | C# |
using System;
using System.Runtime.Serialization;
namespace Sfa.Das.Sas.Indexer.Core.Exceptions
{
[System.Serializable]
public class MappingException : Exception
{
public MappingException()
{
}
public MappingException(string message)
: base(message)
{
}
public MappingException(string message, System.Exception inner)
: base(message, inner)
{
}
protected MappingException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 20.862069 | 84 | 0.591736 | [
"MIT"
] | SkillsFundingAgency/das-apprenticeship-programs-indexer | src/Sfa.Das.Sas.Indexer.Core/Shared/Exceptions/MappingException.cs | 607 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.SSO;
using OpenAuth.Repository.Domain;
namespace OpenAuth.App
{
public class MonthlyAssessmentApp : BaseApp<MonthlyAssessment>
{
public RevelanceManagerApp ReleManagerApp { get; set; }
/// <summary>
/// 加载列表
/// </summary>
public TableData Load(QueryMonthlyAssessmentListReq request)
{
return new TableData
{
count = Repository.GetCount(null),
data = Repository.Find(request.page, request.limit, "Id desc")
};
}
public void Add(MonthlyAssessment obj)
{
Repository.Add(obj);
}
public void Update(MonthlyAssessment obj)
{
UnitWork.Update<MonthlyAssessment>(u => u.Id == obj.Id, u => new MonthlyAssessment
{
//todo:要修改的字段赋值
});
}
}
} | 25.093023 | 95 | 0.549583 | [
"MIT"
] | zz110/andao | CodeSmith/CSharp/APP/MonthlyAssessmentApp.cs | 1,105 | 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.ApiManagement.V20170301.Outputs
{
[OutputType]
public sealed class TokenBodyParameterContractResponse
{
/// <summary>
/// body parameter name.
/// </summary>
public readonly string Name;
/// <summary>
/// body parameter value.
/// </summary>
public readonly string Value;
[OutputConstructor]
private TokenBodyParameterContractResponse(
string name,
string value)
{
Name = name;
Value = value;
}
}
}
| 24.75 | 81 | 0.618406 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ApiManagement/V20170301/Outputs/TokenBodyParameterContractResponse.cs | 891 | C# |
using System;
using Newtonsoft.Json;
namespace UClient
{
/// <summary>
/// Autogenerated TDLib APIs
/// </summary>
public static partial class UApi
{
public partial class ChatEventAction : Object
{
/// <summary>
/// A voice chat was discarded
/// </summary>
public class ChatEventVoiceChatDiscarded : ChatEventAction
{
/// <summary>
/// Data type for serialization
/// </summary>
[JsonProperty("@type")]
public override string DataType { get; set; } = "chatEventVoiceChatDiscarded";
/// <summary>
/// Extra data attached to the message
/// </summary>
[JsonProperty("@extra")]
public override string Extra { get; set; }
/// <summary>
/// Identifier of the voice chat. The voice chat can be received through the method getGroupCall
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("group_call_id")]
public int GroupCallId { get; set; }
}
}
}
}
| 27.190476 | 96 | 0.537653 | [
"MIT"
] | Userizyon/UClient | UClient.Api/Objects/ChatEventVoiceChatDiscarded.cs | 1,142 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="HTMLSpanElement" /> struct.</summary>
public static unsafe partial class HTMLSpanElementTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="HTMLSpanElement" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(HTMLSpanElement).GUID, Is.EqualTo(IID_HTMLSpanElement));
}
/// <summary>Validates that the <see cref="HTMLSpanElement" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<HTMLSpanElement>(), Is.EqualTo(sizeof(HTMLSpanElement)));
}
/// <summary>Validates that the <see cref="HTMLSpanElement" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(HTMLSpanElement).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="HTMLSpanElement" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(HTMLSpanElement), Is.EqualTo(1));
}
}
}
| 38.222222 | 145 | 0.661628 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/MsHTML/HTMLSpanElementTests.cs | 1,722 | C# |
//----------------------------------------------
// Flip Web Apps: Game Framework
// Copyright © 2016 Flip Web Apps / Mark Hewitt
//
// Please direct any bugs/comments/suggestions to http://www.flipwebapps.com
//
// The copyright owner grants to the end user a non-exclusive, worldwide, and perpetual license to this Asset
// to integrate only as incorporated and embedded components of electronic games and interactive media and
// distribute such electronic game and interactive media. End user may modify Assets. End user may otherwise
// not reproduce, distribute, sublicense, rent, lease or lend the Assets. It is emphasized that the end
// user shall not be entitled to distribute or transfer in any way (including, without, limitation by way of
// sublicense) the Assets in any other way than as integrated components of electronic games and interactive media.
// The above copyright notice and this permission notice must not be removed from any files.
// 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 UnityEngine;
namespace GameFramework.Display.Other.Components
{
/// <summary>
/// Creates a background for the camera, which is a simple gradient blend between two colors.
/// </summary>
/// Attach this script to your camera, and change the top and bottom colors in the inspector as desired. When run,
/// the clear flags for your camera is set to Depth Only, allowing a newly created background camera to show through.
/// A plane with the gradient colors is created, which only the background camera can see. This is done with GradientLayer,
/// which is the only layer that the background camera sees, and your camera is set to ignore. The default, 7, is a
/// built-in (non-user-editable) layer that's not used for anything as of Unity 3.1. It can be changed as necessary.
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Game Framework/Display/Other/GradientBackground")]
[HelpURL("http://www.flipwebapps.com/unity-assets/game-framework/display/")]
public class GradientBackground : MonoBehaviour
{
/// <summary>
/// The color to use at the top of the gradient
/// </summary>
[Tooltip("The color to use at the top of the gradient")]
public Color TopColor = Color.blue;
/// <summary>
/// The color to use at the bottom of the gradient
/// </summary>
[Tooltip("The color to use at the bottom of the gradient")]
public Color BottomColor = Color.white;
/// <summary>
/// The shader that should be used. Select GradientBackgroundShader here
/// </summary>
[Tooltip("The shader that should be used. Select GradientBackgroundShader here")]
public Shader Shader;
/// <summary>
/// The layer on which to generate the gradient
/// </summary>
[Tooltip("The layer on which to generate the gradient")]
public int GradientLayer = 7;
/// <summary>
/// The gradient normalised screen top position
/// </summary>
[Tooltip("The gradient normalised screen top position")]
[Range(0, 1)]
public float NormalisedTop = 1;
/// <summary>
/// The gradient normalised screen bottom position
/// </summary>
[Tooltip("The gradient normalised screen bottom position")]
[Range(0, 1)]
public float NormalisedBottom = 0;
GameObject _gradientPlaneGameObject;
void Awake()
{
var attachedCamera = gameObject.GetComponent<Camera>();
GradientLayer = Mathf.Clamp(GradientLayer, 0, 31);
if (!attachedCamera)
{
Debug.LogError("You must attach a GradientBackground script to the same gameobject as a Camera");
return;
}
attachedCamera.clearFlags = CameraClearFlags.Depth;
attachedCamera.cullingMask = attachedCamera.cullingMask & ~(1 << GradientLayer);
var gradientCam = new GameObject("Gradient Cam", typeof(Camera)).GetComponent<Camera>();
gradientCam.depth = attachedCamera.depth - 1;
gradientCam.cullingMask = 1 << GradientLayer;
DisplayGradient();
}
/// <summary>
/// Setup a new Gradient, destroying any old one that is already setup.
/// </summary>
public void DisplayGradient()
{
// destroy any old gradient place.
if (_gradientPlaneGameObject != null)
Destroy(_gradientPlaneGameObject);
//1.154 is the height of a plane at z=0 with the default camera field of view of 60. .577 is half this.
var top = -.577f + (NormalisedTop * 1.154f);
var bottom = -.577f + (NormalisedBottom * 1.154f);
var mesh = new Mesh
{
vertices =
new[]
{
new Vector3(-100f, top, 1f), new Vector3(100f, top, 1f), new Vector3(-100f, bottom, 1f),
new Vector3(100f, bottom, 1f)
},
colors = new[] { TopColor, TopColor, BottomColor, BottomColor },
triangles = new[] { 0, 1, 2, 1, 3, 2 }
};
var mat = new Material(Shader);
_gradientPlaneGameObject = new GameObject("Gradient Plane", typeof(MeshFilter), typeof(MeshRenderer));
((MeshFilter)_gradientPlaneGameObject.GetComponent(typeof(MeshFilter))).mesh = mesh;
var gradRend = _gradientPlaneGameObject.GetComponent<Renderer>();
gradRend.material = mat;
_gradientPlaneGameObject.layer = GradientLayer;
}
}
} | 47.419847 | 128 | 0.632646 | [
"MIT"
] | 517752548/UnityFramework | GameFrameWork/FastCore/Script/Display/Other/Components/GradientBackground.cs | 6,215 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace API.Models
{
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
}
| 18.142857 | 44 | 0.673228 | [
"MIT"
] | cristivasile/Prospect_Auto_Website | Backend/API/API/Models/Input/LoginModel.cs | 256 | C# |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Management.Automation.Language;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
using System.Text;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Diagnostics.CodeAnalysis; // for fxcop
using Dbg = System.Management.Automation.Diagnostics;
using System.Reflection.Emit;
#if !CORECLR
// System.DirectoryServices are not in CoreCLR
using System.DirectoryServices;
#endif
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
#region public type converters
/// <summary>
/// Defines a base class implemented when you need to customize the type conversion for a target class.
/// </summary>
/// <remarks>
/// There are two ways of associating the PSTypeConverter with its target class:
/// - Through the type configuration file.
/// - By applying a TypeConverterAttribute to the target class.
///
/// Unlike System.ComponentModel.TypeConverter, PSTypeConverter can be applied to a family of types (like all types derived from System.Enum).
/// PSTypeConverter has two main differences from TypeConverter:
/// - It can be applied to a family of types and not only the one type as in TypeConverter. In order to do that
/// ConvertFrom and CanConvertFrom receive destinationType to know to which type specifically we are converting sourceValue.
/// - ConvertTo and ConvertFrom receive formatProvider and ignoreCase.
/// Other differences to System.ComponentModel.TypeConverter:
/// - There is no ITypeDescriptorContext.
/// - This class is abstract
/// </remarks>
public abstract class PSTypeConverter
{
private static object GetSourceValueAsObject(PSObject sourceValue)
{
if (sourceValue == null)
{
return null;
}
if (sourceValue.BaseObject is PSCustomObject)
{
return sourceValue;
}
else
{
return PSObject.Base(sourceValue);
}
}
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter.
/// </summary>
/// <param name="sourceValue">value supposedly *not* of the types supported by this converted to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">one of the types supported by this converter to which the <paramref name="sourceValue"/> parameter should be converted</param>
/// <returns>True if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter, otherwise false.</returns>
public abstract bool CanConvertFrom(object sourceValue, Type destinationType);
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter.
/// </summary>
/// <param name="sourceValue">value supposedly *not* of the types supported by this converted to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">one of the types supported by this converter to which the <paramref name="sourceValue"/> parameter should be converted</param>
/// <returns>True if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter, otherwise false.</returns>
public virtual bool CanConvertFrom(PSObject sourceValue, Type destinationType)
{
return this.CanConvertFrom(GetSourceValueAsObject(sourceValue), destinationType);
}
/// <summary>
/// Converts the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase
/// </summary>
/// <param name="sourceValue">value supposedly *not* of the types supported by this converted to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">one of the types supported by this converter to which the <paramref name="sourceValue"/> parameter should be converted to</param>
/// <param name="formatProvider">The format provider to use like in IFormattable's ToString</param>
/// <param name="ignoreCase">true if case should be ignored</param>
/// <returns>the <paramref name="sourceValue"/> parameter converted to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase</returns>
/// <exception cref="InvalidCastException">if no conversion was possible</exception>
public abstract object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase);
/// <summary>
/// Converts the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase
/// </summary>
/// <param name="sourceValue">value supposedly *not* of the types supported by this converted to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">one of the types supported by this converter to which the <paramref name="sourceValue"/> parameter should be converted to</param>
/// <param name="formatProvider">The format provider to use like in IFormattable's ToString</param>
/// <param name="ignoreCase">true if case should be ignored</param>
/// <returns>the <paramref name="sourceValue"/> parameter converted to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase</returns>
/// <exception cref="InvalidCastException">if no conversion was possible</exception>
public virtual object ConvertFrom(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
{
return this.ConvertFrom(GetSourceValueAsObject(sourceValue), destinationType, formatProvider, ignoreCase);
}
/// <summary>
/// Returns true if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter
/// </summary>
/// <param name="sourceValue">value supposedly from one of the types supported by this converter to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">type to convert the <paramref name="sourceValue"/> parameter, supposedly not one of the types supported by the converter</param>
/// <returns>True if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter, otherwise false.</returns>
public abstract bool CanConvertTo(object sourceValue, Type destinationType);
/// <summary>
/// Returns true if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter
/// </summary>
/// <param name="sourceValue">value supposedly from one of the types supported by this converter to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">type to convert the <paramref name="sourceValue"/> parameter, supposedly not one of the types supported by the converter</param>
/// <returns>True if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter, otherwise false.</returns>
public virtual bool CanConvertTo(PSObject sourceValue, Type destinationType)
{
return this.CanConvertTo(GetSourceValueAsObject(sourceValue), destinationType);
}
/// <summary>
/// Converts the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase
/// </summary>
/// <param name="sourceValue">value supposedly from one of the types supported by this converter to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">type to convert the <paramref name="sourceValue"/> parameter, supposedly not one of the types supported by the converter</param>
/// <param name="formatProvider">The format provider to use like in IFormattable's ToString</param>
/// <param name="ignoreCase">true if case should be ignored</param>
/// <returns>sourceValue converted to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase</returns>
/// <exception cref="InvalidCastException">if no conversion was possible</exception>
public abstract object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase);
/// <summary>
/// Converts the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase
/// </summary>
/// <param name="sourceValue">value supposedly from one of the types supported by this converter to be converted to the <paramref name="destinationType"/> parameter</param>
/// <param name="destinationType">type to convert the <paramref name="sourceValue"/> parameter, supposedly not one of the types supported by the converter</param>
/// <param name="formatProvider">The format provider to use like in IFormattable's ToString</param>
/// <param name="ignoreCase">true if case should be ignored</param>
/// <returns>sourceValue converted to the <paramref name="destinationType"/> parameter using formatProvider and ignoreCase</returns>
/// <exception cref="InvalidCastException">if no conversion was possible</exception>
public virtual object ConvertTo(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
{
return this.ConvertTo(GetSourceValueAsObject(sourceValue), destinationType, formatProvider, ignoreCase);
}
}
/// <summary>
/// Enables a type that only has conversion from string to be converted from all other
/// types through string
/// </summary>
/// <remarks>
/// It is permitted to subclass <see cref="ConvertThroughString"/>
/// but there is no established scenario for doing this, nor has it been tested.
/// </remarks>
public class ConvertThroughString : PSTypeConverter
{
/// <summary>
/// This will return false only if sourceValue is string
/// </summary>
/// <param name="sourceValue">value to convert from</param>
/// <param name="destinationType">ignored</param>
/// <returns>false only if sourceValue is string</returns>
public override bool CanConvertFrom(object sourceValue, Type destinationType)
{
// This if avoids infinite recursion.
if (sourceValue is string)
{
return false;
}
return true;
}
/// <summary>
/// Converts to destinationType by first converting sourceValue to string
/// and then converting the result to destinationType.
/// </summary>
/// <param name="sourceValue">The value to convert from</param>
/// <param name="destinationType">The type this converter is associated with</param>
/// <param name="formatProvider">The IFormatProvider to use</param>
/// <param name="ignoreCase">true if case should be ignored</param>
/// <returns>sourceValue converted to destinationType</returns>
/// <exception cref="PSInvalidCastException">When no conversion was possible</exception>
public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
{
string sourceAsString = (string)LanguagePrimitives.ConvertTo(sourceValue, typeof(string), formatProvider);
return LanguagePrimitives.ConvertTo(sourceAsString, destinationType, formatProvider);
}
/// <summary>
/// Returns false, since this converter is not designed to be used to
/// convert from the type associated with the converted to other types.
/// </summary>
/// <param name="sourceValue">The value to convert from</param>
/// <param name="destinationType">The value to convert from</param>
/// <returns>false</returns>
public override bool CanConvertTo(object sourceValue, Type destinationType)
{
return false;
}
/// <summary>
/// Throws NotSupportedException, since this converter is not designed to be used to
/// convert from the type associated with the converted to other types.
/// </summary>
/// <param name="sourceValue">The value to convert from</param>
/// <param name="destinationType">The value to convert from</param>
/// <param name="formatProvider">The IFormatProvider to use</param>
/// <param name="ignoreCase">true if case should be ignored</param>
/// <returns>This method does not return a value.</returns>
/// <exception cref="NotSupportedException">NotSupportedException is always thrown</exception>
public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
{
throw PSTraceSource.NewNotSupportedException();
}
}
#endregion public type converters
/// <summary>
/// The ranking of versions for comparison purposes (used in overload resolution.)
/// A larger value means the conversion is better.
///
/// Note that the lower nibble is all ones for named conversion ranks. This allows for
/// conversions with rankings in between the named values. For example, int=>string[]
/// is value dependent, if the conversion from int=>string succeeds, then an array is
/// created, otherwise we try some other conversion. The int=>string[] conversion should
/// be worse than int=>string, but it is probably better than many other conversions, so
/// we want it to be only slightly worse than int=>string.
/// </summary>
/// <remarks>
/// ValueDependent is a flag, but we don't mark the enum as flags because it really isn't
/// a flags enum.
/// To make debugging easier, the "in between" conversions are all named, though there are
/// no references in the code. They all use the suffix S2A which means "scalar to array".
/// </remarks>
internal enum ConversionRank
{
None = 0x0000,
UnrelatedArraysS2A = 0x0007,
UnrelatedArrays = 0x000F,
ToStringS2A = 0x0017,
ToString = 0x001F,
CustomS2A = 0x0027,
Custom = 0x002F,
IConvertibleS2A = 0x0037,
IConvertible = 0x003F,
ImplicitCastS2A = 0x0047,
ImplicitCast = 0x004F,
ExplicitCastS2A = 0x0057,
ExplicitCast = 0x005F,
ConstructorS2A = 0x0067,
Constructor = 0x006F,
Create = 0x0073,
ParseS2A = 0x0077,
Parse = 0x007F,
PSObjectS2A = 0x0087,
PSObject = 0x008F,
LanguageS2A = 0x0097,
Language = 0x009F,
NullToValue = 0x00AF,
NullToRef = 0x00BF,
NumericExplicitS2A = 0x00C7,
NumericExplicit = 0x00CF,
NumericExplicit1S2A = 0x00D7,
NumericExplicit1 = 0x00DF,
NumericStringS2A = 0x00E7,
NumericString = 0x00EF,
NumericImplicitS2A = 0x00F7,
NumericImplicit = 0x00FF,
AssignableS2A = 0x0107,
Assignable = 0x010F,
IdentityS2A = 0x0117,
StringToCharArray = 0x011A,
Identity = 0x011F,
ValueDependent = 0xFFF7,
}
/// <summary>
/// Defines language support methods
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Refactoring LanguagePrimitives takes lot of dev/test effort. Since V1 code is already shipped, we tend to exclude this message.")]
public static class LanguagePrimitives
{
[TraceSource("ETS", "Extended Type System")]
private static PSTraceSource s_tracer = PSTraceSource.GetTracer("ETS", "Extended Type System");
internal delegate void MemberNotFoundError(PSObject pso, DictionaryEntry property, Type resultType);
internal delegate void MemberSetValueError(SetValueException e);
internal const String OrderedAttribute = "ordered";
internal static void CreateMemberNotFoundError(PSObject pso, DictionaryEntry property, Type resultType)
{
String availableProperties = GetAvailableProperties(pso);
string message = StringUtil.Format(ExtendedTypeSystem.PropertyNotFound, property.Key.ToString(), resultType.FullName, availableProperties);
typeConversion.WriteLine("Issuing an error message about not being able to create an object from hashtable.");
throw new InvalidOperationException(message);
}
internal static void CreateMemberSetValueError(SetValueException e)
{
typeConversion.WriteLine("Issuing an error message about not being able to set the properties for an object.");
throw e;
}
static LanguagePrimitives()
{
RebuildConversionCache();
InitializeGetEnumerableCache();
#if !CORECLR // AppDomain Not In CoreCLR
AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolveHelper;
#endif
}
internal static void UpdateTypeConvertFromTypeTable(string typeName)
{
lock (s_converterCache)
{
var toRemove = s_converterCache.Keys.Where(
conv => string.Equals(conv.to.FullName, typeName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(conv.from.FullName, typeName, StringComparison.OrdinalIgnoreCase)).ToArray();
foreach (var k in toRemove)
{
s_converterCache.Remove(k);
}
// Note we do not clear possibleTypeConverter even when removing.
//
// The conversion cache and the possibleTypeConverter cache are process wide, but
// the type table used for any specific conversion is runspace specific.
s_possibleTypeConverter[typeName] = true;
}
}
#region GetEnumerable/GetEnumerator
/// <summary>
/// This is a wrapper class that allows us to use the generic IEnumerable
/// implementation of an object when we can't use it's non-generic
/// implementation.
/// </summary>
private class EnumerableTWrapper : IEnumerable
{
private object _enumerable;
private Type _enumerableType;
private DynamicMethod _getEnumerator;
internal EnumerableTWrapper(object enumerable, Type enumerableType)
{
_enumerable = enumerable;
_enumerableType = enumerableType;
CreateGetEnumerator();
}
private void CreateGetEnumerator()
{
_getEnumerator = new DynamicMethod("GetEnumerator", typeof(object),
new Type[] { typeof(object) }, typeof(LanguagePrimitives).GetTypeInfo().Module, true);
ILGenerator emitter = _getEnumerator.GetILGenerator();
emitter.Emit(OpCodes.Ldarg_0);
emitter.Emit(OpCodes.Castclass, _enumerableType);
MethodInfo methodInfo = _enumerableType.GetMethod("GetEnumerator", new Type[] { });
emitter.Emit(OpCodes.Callvirt, methodInfo);
emitter.Emit(OpCodes.Ret);
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return (IEnumerator)_getEnumerator.Invoke(null, new object[] { _enumerable });
}
#endregion
}
private static IEnumerable GetEnumerableFromIEnumerableT(object obj)
{
foreach (Type i in obj.GetType().GetInterfaces())
{
TypeInfo typeinfo = i.GetTypeInfo();
if (typeinfo.IsGenericType && typeinfo.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
return new EnumerableTWrapper(obj, i);
}
}
return null;
}
private delegate IEnumerable GetEnumerableDelegate(object obj);
private static Dictionary<Type, GetEnumerableDelegate> s_getEnumerableCache = new Dictionary<Type, GetEnumerableDelegate>(32);
private static GetEnumerableDelegate GetOrCalculateEnumerable(Type type)
{
GetEnumerableDelegate getEnumerable = null;
lock (s_getEnumerableCache)
{
if (!s_getEnumerableCache.TryGetValue(type, out getEnumerable))
{
getEnumerable = CalculateGetEnumerable(type);
s_getEnumerableCache.Add(type, getEnumerable);
}
}
return getEnumerable;
}
private static void InitializeGetEnumerableCache()
{
lock (s_getEnumerableCache)
{
// PowerShell doesn't treat strings as enumerables so just return null.
// we also want to return null on common numeric types very quickly
s_getEnumerableCache.Clear();
s_getEnumerableCache.Add(typeof(string), LanguagePrimitives.ReturnNullEnumerable);
s_getEnumerableCache.Add(typeof(int), LanguagePrimitives.ReturnNullEnumerable);
s_getEnumerableCache.Add(typeof(double), LanguagePrimitives.ReturnNullEnumerable);
}
}
internal static bool IsTypeEnumerable(Type type)
{
GetEnumerableDelegate getEnumerable = GetOrCalculateEnumerable(type);
return (getEnumerable != LanguagePrimitives.ReturnNullEnumerable);
}
/// <summary>
/// Retrieves the IEnumerable of obj or null if the language does not consider obj to be IEnumerable
/// </summary>
/// <param name="obj">
/// IEnumerable or IEnumerable-like object
/// </param>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "Since V1 code is already shipped, excluding this message.")]
public static IEnumerable GetEnumerable(object obj)
{
if (obj == null)
{
return null;
}
Type objectType = obj.GetType();
// if the object passed is an PSObject,
// look at the base object. Notice that, if the
// object has been serialized, the base object
// will be there as an ArrayList if the original
// object was IEnumerable
if (objectType == typeof(PSObject))
{
PSObject mshObj = (PSObject)obj;
obj = mshObj.BaseObject;
objectType = obj.GetType();
}
GetEnumerableDelegate getEnumerable = GetOrCalculateEnumerable(objectType);
return getEnumerable(obj);
}
private static IEnumerable ReturnNullEnumerable(object obj)
{
return null;
}
#if !CORECLR
private static IEnumerable DataTableEnumerable(object obj)
{
return (((DataTable)obj).Rows);
}
#endif
private static IEnumerable TypicalEnumerable(object obj)
{
IEnumerable e = (IEnumerable)obj;
try
{
// Some IEnumerable implementations just return null. Others
// raise an exception. Either of these may have a perfectly
// good generic implementation, so we'll try those if the
// non-generic is no good.
if (e.GetEnumerator() == null)
{
return GetEnumerableFromIEnumerableT(obj);
}
return e;
}
catch (Exception innerException)
{
e = GetEnumerableFromIEnumerableT(obj);
if (e != null)
{
return e;
}
throw new ExtendedTypeSystemException(
"ExceptionInGetEnumerator",
innerException,
ExtendedTypeSystem.EnumerationException,
innerException.Message);
}
}
private static GetEnumerableDelegate CalculateGetEnumerable(Type objectType)
{
#if !CORECLR
if (typeof(DataTable).IsAssignableFrom(objectType))
{
return LanguagePrimitives.DataTableEnumerable;
}
#endif
// Don't treat IDictionary or XmlNode as enumerable...
if (typeof(IEnumerable).IsAssignableFrom(objectType)
&& !typeof(IDictionary).IsAssignableFrom(objectType)
&& !typeof(XmlNode).IsAssignableFrom(objectType))
{
return LanguagePrimitives.TypicalEnumerable;
}
return LanguagePrimitives.ReturnNullEnumerable;
}
private static readonly CallSite<Func<CallSite, object, IEnumerator>> s_getEnumeratorSite =
CallSite<Func<CallSite, object, IEnumerator>>.Create(PSEnumerableBinder.Get());
/// <summary>
/// Retrieves the IEnumerator of obj or null if the language does not consider obj as capable of returning an IEnumerator
/// </summary>
/// <param name="obj">
/// IEnumerable or IEnumerable-like object
/// </param>
/// <exception cref="ExtendedTypeSystemException">When the act of getting the enumerator throws an exception</exception>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "Since V1 code is already shipped, excluding this message for backward compatibility reasons.")]
public static IEnumerator GetEnumerator(object obj)
{
var result = s_getEnumeratorSite.Target.Invoke(s_getEnumeratorSite, obj);
return (result is EnumerableOps.NonEnumerableObjectEnumerator) ? null : result;
}
#endregion GetEnumerable/GetEnumerator
/// <summary>
/// This method takes a an arbitrary object and wraps it in a PSDataCollection of PSObject.
/// This simplifies interacting with the PowerShell workflow activities.
/// </summary>
/// <param name="inputValue"></param>
/// <returns></returns>
public static PSDataCollection<PSObject> GetPSDataCollection(object inputValue)
{
PSDataCollection<PSObject> result = new PSDataCollection<PSObject>();
if (inputValue != null)
{
IEnumerator e = GetEnumerator(inputValue);
if (e != null)
{
while (e.MoveNext())
{
result.Add(e.Current == null ? null : PSObject.AsPSObject(e.Current));
}
}
else
{
result.Add(PSObject.AsPSObject(inputValue));
}
}
result.Complete();
return result;
}
/// <summary>
/// Used to compare two objects for equality converting the second to the type of the first, if required.
/// </summary>
/// <param name="first">first object</param>
/// <param name="second">object to compare first to</param>
/// <returns>true if first is equal to the second</returns>
public new static bool Equals(object first, object second)
{
return Equals(first, second, false, CultureInfo.InvariantCulture);
}
/// <summary>
/// Used to compare two objects for equality converting the second to the type of the first, if required.
/// </summary>
/// <param name="first">first object</param>
/// <param name="second">object to compare first to</param>
/// <param name="ignoreCase">used only if first and second are strings
/// to specify the type of string comparison </param>
/// <returns>true if first is equal to the second</returns>
public static bool Equals(object first, object second, bool ignoreCase)
{
return Equals(first, second, ignoreCase, CultureInfo.InvariantCulture);
}
/// <summary>
/// Used to compare two objects for equality converting the second to the type of the first, if required.
/// </summary>
/// <param name="first">first object</param>
/// <param name="second">object to compare first to</param>
/// <param name="ignoreCase">used only if first and second are strings
/// to specify the type of string comparison </param>
/// <param name="formatProvider">the format/culture to be used. If this parameter is null,
/// CultureInfo.InvariantCulture will be used.
/// </param>
/// <returns>true if first is equal to the second</returns>
public static bool Equals(object first, object second, bool ignoreCase, IFormatProvider formatProvider)
{
// If both first and second are null it returns true.
// If one is null and the other is not it returns false.
// if (first.Equals(second)) it returns true otherwise it goes ahead with type conversion operations.
// If both first and second are strings it returns (String.Compare(firstString, secondString, ignoreCase) == 0).
// If second can be converted to the type of the first, it does so and returns first.Equals(secondConverted)
// Otherwise false is returned
if (formatProvider == null)
{
formatProvider = CultureInfo.InvariantCulture;
}
var culture = formatProvider as CultureInfo;
if (culture == null)
{
throw PSTraceSource.NewArgumentException("formatProvider");
}
first = PSObject.Base(first);
second = PSObject.Base(second);
if (first == null)
{
if (second == null) return true;
return false;
}
if (second == null)
{
return false; // first is not null
}
string firstString = first as string;
string secondString;
if (firstString != null)
{
secondString = second as string ?? (string)LanguagePrimitives.ConvertTo(second, typeof(string), culture);
return (culture.CompareInfo.Compare(firstString, secondString,
ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None) == 0);
}
if (first.Equals(second)) return true;
Type firstType = first.GetType();
Type secondType = second.GetType();
int firstIndex = LanguagePrimitives.TypeTableIndex(firstType);
int secondIndex = LanguagePrimitives.TypeTableIndex(secondType);
if ((firstIndex != -1) && (secondIndex != -1))
{
return LanguagePrimitives.NumericCompare(first, second, firstIndex, secondIndex) == 0;
}
if (firstType == typeof(char) && ignoreCase)
{
secondString = second as string;
if (secondString != null && secondString.Length == 1)
{
char firstAsUpper = culture.TextInfo.ToUpper((char)first);
char secondAsUpper = culture.TextInfo.ToUpper(secondString[0]);
return firstAsUpper.Equals(secondAsUpper);
}
else if (secondType == typeof(char))
{
char firstAsUpper = culture.TextInfo.ToUpper((char)first);
char secondAsUpper = culture.TextInfo.ToUpper((char)second);
return firstAsUpper.Equals(secondAsUpper);
}
}
try
{
object secondConverted = LanguagePrimitives.ConvertTo(second, firstType, culture);
return first.Equals(secondConverted);
}
catch (InvalidCastException)
{
}
return false;
}
/// <summary>
/// Compare first and second, converting second to the
/// type of the first, if necessary.
/// </summary>
/// <param name="first">first comparison value</param>
/// <param name="second">second comparison value</param>
/// <returns>less than zero if first is smaller than second, more than
/// zero if it is greater or zero if they are the same</returns>
/// <exception cref="System.ArgumentException">
/// <paramref name="first"/> does not implement IComparable or <paramref name="second"/> cannot be converted
/// to the type of <paramref name="first"/>.
/// </exception>
public static int Compare(object first, object second)
{
return LanguagePrimitives.Compare(first, second, false, CultureInfo.InvariantCulture);
}
/// <summary>
/// Compare first and second, converting second to the
/// type of the first, if necessary.
/// </summary>
/// <param name="first">first comparison value</param>
/// <param name="second">second comparison value</param>
/// <param name="ignoreCase">Used if both values are strings</param>
/// <returns>less than zero if first is smaller than second, more than
/// zero if it is greater or zero if they are the same</returns>
/// <exception cref="System.ArgumentException">
/// <paramref name="first"/> does not implement IComparable or <paramref name="second"/> cannot be converted
/// to the type of <paramref name="first"/>.
/// </exception>
public static int Compare(object first, object second, bool ignoreCase)
{
return LanguagePrimitives.Compare(first, second, ignoreCase, CultureInfo.InvariantCulture);
}
/// <summary>
/// Compare first and second, converting second to the
/// type of the first, if necessary.
/// </summary>
/// <param name="first">first comparison value</param>
/// <param name="second">second comparison value</param>
/// <param name="ignoreCase">Used if both values are strings</param>
/// <param name="formatProvider">Used in type conversions and if both values are strings</param>
/// <returns>less than zero if first is smaller than second, more than
/// zero if it is greater or zero if they are the same</returns>
/// <exception cref="System.ArgumentException">
/// <paramref name="first"/> does not implement IComparable or <paramref name="second"/> cannot be converted
/// to the type of <paramref name="first"/>.
/// </exception>
public static int Compare(object first, object second, bool ignoreCase, IFormatProvider formatProvider)
{
if (formatProvider == null)
{
formatProvider = CultureInfo.InvariantCulture;
}
var culture = formatProvider as CultureInfo;
if (culture == null)
{
throw PSTraceSource.NewArgumentException("formatProvider");
}
first = PSObject.Base(first);
second = PSObject.Base(second);
if (first == null)
{
if (second == null)
{
return 0;
}
else
{
// If it's a positive number, including 0, it's greater than null
// for everything else it's less than zero...
switch (LanguagePrimitives.GetTypeCode(second.GetType()))
{
case TypeCode.Int16: return System.Math.Sign((Int16)second) < 0 ? 1 : -1;
case TypeCode.Int32: return System.Math.Sign((Int32)second) < 0 ? 1 : -1;
case TypeCode.Int64: return System.Math.Sign((Int64)second) < 0 ? 1 : -1;
case TypeCode.SByte: return System.Math.Sign((sbyte)second) < 0 ? 1 : -1;
case TypeCode.Single: return System.Math.Sign((System.Single)second) < 0 ? 1 : -1;
case TypeCode.Double: return System.Math.Sign((System.Double)second) < 0 ? 1 : -1;
case TypeCode.Decimal: return System.Math.Sign((System.Decimal)second) < 0 ? 1 : -1;
default: return -1;
}
}
}
if (second == null)
{
// If it's a positive number, including 0, it's greater than null
// for everything else it's less than zero...
switch (LanguagePrimitives.GetTypeCode(first.GetType()))
{
case TypeCode.Int16: return System.Math.Sign((Int16)first) < 0 ? -1 : 1;
case TypeCode.Int32: return System.Math.Sign((Int32)first) < 0 ? -1 : 1;
case TypeCode.Int64: return System.Math.Sign((Int64)first) < 0 ? -1 : 1;
case TypeCode.SByte: return System.Math.Sign((sbyte)first) < 0 ? -1 : 1;
case TypeCode.Single: return System.Math.Sign((System.Single)first) < 0 ? -1 : 1;
case TypeCode.Double: return System.Math.Sign((System.Double)first) < 0 ? -1 : 1;
case TypeCode.Decimal: return System.Math.Sign((System.Decimal)first) < 0 ? -1 : 1;
default: return 1;
}
}
string firstString = first as string;
if (firstString != null)
{
string secondString = second as string;
if (secondString == null)
{
try
{
secondString = (string)LanguagePrimitives.ConvertTo(second, typeof(string), culture);
}
catch (PSInvalidCastException e)
{
throw PSTraceSource.NewArgumentException("second", ExtendedTypeSystem.ComparisonFailure,
first.ToString(), second.ToString(), e.Message);
}
}
return culture.CompareInfo.Compare(firstString, secondString,
ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
Type firstType = first.GetType();
Type secondType = second.GetType();
int firstIndex = LanguagePrimitives.TypeTableIndex(firstType);
int secondIndex = LanguagePrimitives.TypeTableIndex(secondType);
if ((firstIndex != -1) && (secondIndex != -1))
{
return LanguagePrimitives.NumericCompare(first, second, firstIndex, secondIndex);
}
object secondConverted;
try
{
secondConverted = LanguagePrimitives.ConvertTo(second, firstType, culture);
}
catch (PSInvalidCastException e)
{
throw PSTraceSource.NewArgumentException("second", ExtendedTypeSystem.ComparisonFailure,
first.ToString(), second.ToString(), e.Message);
}
IComparable firstComparable = first as IComparable;
if (firstComparable != null)
{
return firstComparable.CompareTo(secondConverted);
}
if (first.Equals(second))
{
return 0;
}
// At this point, we know that they aren't equal but we have no way of
// knowing which should compare greater than the other so we throw an exception.
throw PSTraceSource.NewArgumentException("first", ExtendedTypeSystem.NotIcomparable, first.ToString());
}
/// <summary>
/// Returns true if the language considers obj to be true
/// </summary>
/// <param name="obj">obj to verify if it is true</param>
/// <returns>true if obj is true</returns>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "Since V1 code is already shipped, excluding this message for backward compatibility reasons")]
public static bool IsTrue(object obj)
{
// null is a valid argument - it converts to false...
if (obj == null || obj == AutomationNull.Value)
return false;
obj = PSObject.Base(obj);
Type objType = obj.GetType();
if (objType == typeof(bool))
{
return (bool)obj;
}
if (objType == typeof(string))
{
return IsTrue((string)obj);
}
if (LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(objType)))
{
ConversionData data = GetConversionData(objType, typeof(bool)) ??
CacheConversion(objType, typeof(bool), CreateNumericToBoolConverter(objType), ConversionRank.Language);
return (bool)data.Invoke(obj, typeof(bool), false, null, null, null);
}
if (objType == typeof(SwitchParameter))
return ((SwitchParameter)obj).ToBool();
IList objectArray = obj as IList;
if (objectArray != null)
{
return IsTrue(objectArray);
}
return true;
}
internal static bool IsTrue(string s)
{
return (s.Length != 0);
}
internal static bool IsTrue(IList objectArray)
{
switch (objectArray.Count)
{
// a zero length array is false, so condition is false
case 0:
return false;
// if the result is an array of length 1, treat it as a scalar...
case 1:
// A possible implementation would be just
// return IsTrue(objectArray[0]);
// but since we don't want this to recurse indefinitely
// we explicitly check the case where it would recurse
// and deal with it.
IList firstElement = PSObject.Base(objectArray[0]) as IList;
if (firstElement == null)
{
return IsTrue(objectArray[0]);
}
if (firstElement.Count < 1) return false;
// the first element is an array with more than zero elements
return true;
default:
return true;
}
}
/// <summary>
/// Internal routine that determines if an object meets any of our criteria for null.
/// </summary>
/// <param name="obj">The object to test</param>
/// <returns>true if the object is null</returns>
internal static bool IsNull(object obj)
{
return (obj == null || obj == AutomationNull.Value);
}
/// <summary>
/// Auxiliary for the cases where we want a new PSObject or null
/// </summary>
internal static PSObject AsPSObjectOrNull(object obj)
{
if (obj == null)
{
return null;
}
return PSObject.AsPSObject(obj);
}
internal static int TypeTableIndex(Type type)
{
switch (LanguagePrimitives.GetTypeCode(type))
{
case TypeCode.Int16: return 0;
case TypeCode.Int32: return 1;
case TypeCode.Int64: return 2;
case TypeCode.UInt16: return 3;
case TypeCode.UInt32: return 4;
case TypeCode.UInt64: return 5;
case TypeCode.SByte: return 6;
case TypeCode.Byte: return 7;
case TypeCode.Single: return 8;
case TypeCode.Double: return 9;
case TypeCode.Decimal: return 10;
default: return -1;
}
}
/// <summary>
/// Table of the largest safe type to which both types can be converted without exceptions.
/// This table is used for numeric comparisons.
/// The 4 entries marked as not used, are explicitly dealt with in NumericCompareDecimal.
/// NumericCompareDecimal exists because doubles and singles can throw
/// an exception when converted to decimal.
/// The order of lines and columns cannot be changed since NumericCompare depends on it.
/// </summary>
internal static Type[][] LargestTypeTable = new Type[][]
{
// System.Int16 System.Int32 System.Int64 System.UInt16 System.UInt32 System.UInt64 System.SByte System.Byte System.Single System.Double System.Decimal
/* System.Int16 */new Type[] { typeof(System.Int16), typeof(System.Int32), typeof(System.Int64), typeof(System.Int32), typeof(System.Int64), typeof(System.Double), typeof(System.Int16), typeof(System.Int16), typeof(System.Single), typeof(System.Double), typeof(System.Decimal) },
/* System.Int32 */new Type[] { typeof(System.Int32), typeof(System.Int32), typeof(System.Int64), typeof(System.Int32), typeof(System.Int64), typeof(System.Double), typeof(System.Int32), typeof(System.Int32), typeof(System.Double), typeof(System.Double), typeof(System.Decimal) },
/* System.Int64 */new Type[] { typeof(System.Int64), typeof(System.Int64), typeof(System.Int64), typeof(System.Int64), typeof(System.Int64), typeof(System.Decimal), typeof(System.Int64), typeof(System.Int64), typeof(System.Double), typeof(System.Double), typeof(System.Decimal) },
/* System.UInt16 */new Type[] { typeof(System.Int32), typeof(System.Int32), typeof(System.Int64), typeof(System.UInt16), typeof(System.UInt32), typeof(System.UInt64), typeof(System.Int32), typeof(System.UInt16), typeof(System.Single), typeof(System.Double), typeof(System.Decimal) },
/* System.UInt32 */new Type[] { typeof(System.Int64), typeof(System.Int64), typeof(System.Int64), typeof(System.UInt32), typeof(System.UInt32), typeof(System.UInt64), typeof(System.Int64), typeof(System.UInt32), typeof(System.Double), typeof(System.Double), typeof(System.Decimal) },
/* System.UInt64 */new Type[] { typeof(System.Double), typeof(System.Double), typeof(System.Decimal), typeof(System.UInt64), typeof(System.UInt64), typeof(System.UInt64), typeof(System.Double), typeof(System.UInt64), typeof(System.Double), typeof(System.Double), typeof(System.Decimal) },
/* System.SByte */new Type[] { typeof(System.Int16), typeof(System.Int32), typeof(System.Int64), typeof(System.Int32), typeof(System.Int64), typeof(System.Double), typeof(System.SByte), typeof(System.Int16), typeof(System.Single), typeof(System.Double), typeof(System.Decimal) },
/* System.Byte */new Type[] { typeof(System.Int16), typeof(System.Int32), typeof(System.Int64), typeof(System.UInt16), typeof(System.UInt32), typeof(System.UInt64), typeof(System.Int16), typeof(System.Byte), typeof(System.Single), typeof(System.Double), typeof(System.Decimal) },
/* System.Single */new Type[] { typeof(System.Single), typeof(System.Double), typeof(System.Double), typeof(System.Single), typeof(System.Double), typeof(System.Double), typeof(System.Single), typeof(System.Single), typeof(System.Single), typeof(System.Double), null/*not used*/ },
/* System.Double */new Type[] { typeof(System.Double), typeof(System.Double), typeof(System.Double), typeof(System.Double), typeof(System.Double), typeof(System.Double), typeof(System.Double), typeof(System.Double), typeof(System.Double), typeof(System.Double), null/*not used*/ },
/* System.Decimal */new Type[] { typeof(System.Decimal), typeof(System.Decimal), typeof(System.Decimal), typeof(System.Decimal), typeof(System.Decimal), typeof(System.Decimal), typeof(System.Decimal), typeof(System.Decimal), null/*not used*/, null/*not used*/, typeof(System.Decimal) },
};
private static int NumericCompareDecimal(decimal decimalNumber, object otherNumber)
{
object otherDecimal = null;
try
{
otherDecimal = Convert.ChangeType(otherNumber, typeof(System.Decimal), CultureInfo.InvariantCulture);
}
catch (OverflowException)
{
try
{
double wasDecimal = (double)Convert.ChangeType(decimalNumber, typeof(System.Double), CultureInfo.InvariantCulture);
double otherDouble = (double)Convert.ChangeType(otherNumber, typeof(System.Double), CultureInfo.InvariantCulture);
return ((IComparable)wasDecimal).CompareTo(otherDouble);
}
catch (Exception) // We need to catch the generic exception because ChangeType throws unadvertised exceptions
{
return -1;
}
}
catch (Exception) // We need to catch the generic exception because ChangeType throws unadvertised exceptions
{
return -1;
}
return ((IComparable)decimalNumber).CompareTo(otherDecimal);
}
private static int NumericCompare(object number1, object number2, int index1, int index2)
{
// Conversion from single or double to decimal might throw
// if the double is greater than the decimal's maximum so
// we special case it in NumericCompareDecimal
if ((index1 == 10) && ((index2 == 8) || (index2 == 9)))
{
return NumericCompareDecimal((decimal)number1, number2);
}
if ((index2 == 10) && ((index1 == 8) || (index1 == 9)))
{
return -NumericCompareDecimal((decimal)number2, number1);
}
Type commonType = LargestTypeTable[index1][index2];
object number1Converted = Convert.ChangeType(number1, commonType, CultureInfo.InvariantCulture);
object number2Converted = Convert.ChangeType(number2, commonType, CultureInfo.InvariantCulture);
return ((IComparable)number1Converted).CompareTo(number2Converted);
}
/// <summary>
/// Necessary not to return an integer type code for enums
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
internal static TypeCode GetTypeCode(Type type)
{
return type.GetTypeCode();
}
/// <summary>
/// Emulates the "As" C# language primitive, but will unwrap
/// the PSObject if required.
/// </summary>
/// <typeparam name="T">The type for which to convert</typeparam>
/// <param name="castObject">The object from which to convert</param>
/// <returns>An object of the specified type, if the conversion was successful. Returns null otherwise.</returns>
internal static T FromObjectAs<T>(Object castObject)
{
T returnType = default(T);
// First, see if we can cast the direct type
PSObject wrapperObject = castObject as PSObject;
if (wrapperObject == null)
{
try
{
returnType = (T)castObject;
}
catch (InvalidCastException)
{
returnType = default(T);
}
}
// Then, see if it is an PSObject wrapping the object
else
{
try
{
returnType = (T)wrapperObject.BaseObject;
}
catch (InvalidCastException)
{
returnType = default(T);
}
}
return returnType;
}
[Flags]
private enum TypeCodeTraits
{
None = 0x00,
SignedInteger = 0x01,
UnsignedInteger = 0x02,
Floating = 0x04,
CimIntrinsicType = 0x08,
Decimal = 0x10,
Integer = SignedInteger | UnsignedInteger,
Numeric = Integer | Floating | Decimal,
}
private static readonly TypeCodeTraits[] s_typeCodeTraits = new TypeCodeTraits[]
{
/* Empty = 0 */ TypeCodeTraits.None,
/* Object = 1 */ TypeCodeTraits.None,
/* DBNull = 2 */ TypeCodeTraits.None,
/* Boolean = 3 */ TypeCodeTraits.CimIntrinsicType,
/* Char = 4 */ TypeCodeTraits.CimIntrinsicType,
/* SByte = 5 */ TypeCodeTraits.SignedInteger | TypeCodeTraits.CimIntrinsicType,
/* Byte = 6 */ TypeCodeTraits.UnsignedInteger | TypeCodeTraits.CimIntrinsicType,
/* Int16 = 7 */ TypeCodeTraits.SignedInteger | TypeCodeTraits.CimIntrinsicType,
/* UInt16 = 8 */ TypeCodeTraits.UnsignedInteger | TypeCodeTraits.CimIntrinsicType,
/* Int32 = 9 */ TypeCodeTraits.SignedInteger | TypeCodeTraits.CimIntrinsicType,
/* UInt32 = 10 */ TypeCodeTraits.UnsignedInteger | TypeCodeTraits.CimIntrinsicType,
/* Int64 = 11 */ TypeCodeTraits.SignedInteger | TypeCodeTraits.CimIntrinsicType,
/* UInt64 = 12 */ TypeCodeTraits.UnsignedInteger | TypeCodeTraits.CimIntrinsicType,
/* Single = 13 */ TypeCodeTraits.Floating | TypeCodeTraits.CimIntrinsicType,
/* Double = 14 */ TypeCodeTraits.Floating | TypeCodeTraits.CimIntrinsicType,
/* Decimal = 15 */ TypeCodeTraits.Decimal,
/* DateTime = 16 */ TypeCodeTraits.None | TypeCodeTraits.CimIntrinsicType,
/* = 17 */ TypeCodeTraits.None,
/* String = 18 */ TypeCodeTraits.None | TypeCodeTraits.CimIntrinsicType,
};
/// <summary>
/// Verifies if type is a signed integer
/// </summary>
/// <param name="typeCode">type code to check</param>
/// <returns>true if type is a signed integer, false otherwise</returns>
internal static bool IsSignedInteger(TypeCode typeCode)
{
return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.SignedInteger) != 0;
}
/// <summary>
/// Verifies if type is an unsigned integer
/// </summary>
/// <param name="typeCode">type code to check</param>
/// <returns>true if type is an unsigned integer, false otherwise</returns>
internal static bool IsUnsignedInteger(TypeCode typeCode)
{
return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.UnsignedInteger) != 0;
}
/// <summary>
/// Verifies if type is integer
/// </summary>
/// <param name="typeCode">type code to check</param>
/// <returns>true if type is integer, false otherwise</returns>
internal static bool IsInteger(TypeCode typeCode)
{
return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.Integer) != 0;
}
/// <summary>
/// Verifies if type is a floating point number
/// </summary>
/// <param name="typeCode">type code to check</param>
/// <returns>true if type is floating point, false otherwise</returns>
internal static bool IsFloating(TypeCode typeCode)
{
return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.Floating) != 0;
}
/// <summary>
/// Verifies if type is an integer or floating point number
/// </summary>
/// <param name="typeCode">type code to check</param>
/// <returns>true if type is integer or floating point, false otherwise</returns>
internal static bool IsNumeric(TypeCode typeCode)
{
return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.Numeric) != 0;
}
/// <summary>
/// Verifies if type is a CIM intrinsic type
/// </summary>
/// <param name="typeCode">type code to check</param>
/// <returns>true if type is CIM intrinsic type, false otherwise</returns>
internal static bool IsCimIntrinsicScalarType(TypeCode typeCode)
{
return (s_typeCodeTraits[(int)typeCode] & TypeCodeTraits.CimIntrinsicType) != 0;
}
internal static bool IsCimIntrinsicScalarType(Type type)
{
Dbg.Assert(type != null, "Caller should verify type != null");
// using type code we can cover all intrinsic types from the table
// on page 11 of DSP0004, except:
// - TimeSpan part of "datetime"
// - <classname> ref
TypeCode typeCode = LanguagePrimitives.GetTypeCode(type);
if (LanguagePrimitives.IsCimIntrinsicScalarType(typeCode) && !type.GetTypeInfo().IsEnum)
{
return true;
}
if (type == typeof(TimeSpan))
{
return true;
}
return false;
}
/// <summary>
/// Verifies if type is one of the boolean types
/// </summary>
/// <param name="type">type to check</param>
/// <returns>true if type is one of boolean types, false otherwise</returns>
internal static bool IsBooleanType(Type type)
{
if (type == typeof(bool) ||
type == typeof(Nullable<bool>))
return true;
else
return false;
}
/// <summary>
/// Verifies if type is one of switch parameter types
/// </summary>
/// <param name="type">type to check</param>
/// <returns>true if type is one of switch parameter types, false otherwise</returns>
internal static bool IsSwitchParameterType(Type type)
{
if (type == typeof(SwitchParameter) || type == typeof(Nullable<SwitchParameter>))
return true;
else
return false;
}
/// <summary>
/// Verifies if type is one of boolean or switch parameter types
/// </summary>
/// <param name="type">type to check</param>
/// <returns>true if type if one of boolean or switch parameter types,
/// false otherwise</returns>
internal static bool IsBoolOrSwitchParameterType(Type type)
{
if (IsBooleanType(type) || IsSwitchParameterType(type))
return true;
else
return false;
}
/// <summary>
/// Do the necessary conversions when using property or array assignment to a generic dictionary:
///
/// $dict.Prop = value
/// $dict[$Prop] = value
///
/// The property typically won't need conversion, but it could. The value is more likely in
/// need of conversion.
/// </summary>
/// <param name="dictionary">The dictionary that potentially implement <see cref="IDictionary<TKey,TValue>"/></param>
/// <param name="key">The object representing the key</param>
/// <param name="value">The value to assign</param>
internal static void DoConversionsForSetInGenericDictionary(IDictionary dictionary, ref object key, ref object value)
{
foreach (Type i in dictionary.GetType().GetInterfaces())
{
TypeInfo typeInfo = i.GetTypeInfo();
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
// If we get here, we know the target implements IDictionary. We will assume
// that the non-generic implementation of the indexer property just forwards
// to the generic version, after checking the types of the key and value.
// This assumption holds for System.Collections.Generic.Dictionary<TKey,TValue>.
// If we did not make this assumption, we would be forced to generate code
// to call the generic indexer directly, somewhat analogous to what we do
// in GetEnumeratorFromIEnumeratorT.
Type[] genericArguments = i.GetGenericArguments();
key = LanguagePrimitives.ConvertTo(key, genericArguments[0], CultureInfo.InvariantCulture);
value = LanguagePrimitives.ConvertTo(value, genericArguments[1], CultureInfo.InvariantCulture);
}
}
}
#region type converter
internal static PSTraceSource typeConversion = PSTraceSource.GetTracer("TypeConversion", "Traces the type conversion algorithm", false);
private static TypeConverter GetIntegerSystemConverter(Type type)
{
if (type == typeof(Int16))
{
return new Int16Converter();
}
else if (type == typeof(Int32))
{
return new Int32Converter();
}
else if (type == typeof(Int64))
{
return new Int64Converter();
}
else if (type == typeof(UInt16))
{
return new UInt16Converter();
}
else if (type == typeof(UInt32))
{
return new UInt32Converter();
}
else if (type == typeof(UInt64))
{
return new UInt64Converter();
}
else if (type == typeof(Byte))
{
return new ByteConverter();
}
else if (type == typeof(SByte))
{
return new SByteConverter();
}
return null;
}
/// backupTypeTable:
/// Used by Remoting Rehydration Logic. While Deserializing a remote object,
/// LocalPipeline.ExecutionContextFromTLS() might return null..In which case this
/// TypeTable will be used to do the conversion.
internal static object GetConverter(Type type, TypeTable backupTypeTable)
{
object typesXmlConverter = null;
ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS();
if (ecFromTLS != null)
{
s_tracer.WriteLine("ecFromTLS != null");
typesXmlConverter = ecFromTLS.TypeTable.GetTypeConverter(type.FullName);
}
if ((typesXmlConverter == null) && (backupTypeTable != null))
{
s_tracer.WriteLine("Using provided TypeTable to get the type converter");
typesXmlConverter = backupTypeTable.GetTypeConverter(type.FullName);
}
if (typesXmlConverter != null)
{
s_tracer.WriteLine("typesXmlConverter != null");
return typesXmlConverter;
}
var typeConverters = type.GetTypeInfo().GetCustomAttributes(typeof(TypeConverterAttribute), false);
foreach (var typeConverter in typeConverters)
{
var attr = (TypeConverterAttribute)typeConverter;
string assemblyQualifiedtypeName = attr.ConverterTypeName;
typeConversion.WriteLine("{0}'s TypeConverterAttribute points to {1}.", type, assemblyQualifiedtypeName);
// The return statement makes sure we only process the first TypeConverterAttribute
return NewConverterInstance(assemblyQualifiedtypeName);
}
return null;
}
private static object NewConverterInstance(string assemblyQualifiedTypeName)
{
int typeSeparator = assemblyQualifiedTypeName.IndexOf(",", StringComparison.Ordinal);
if (typeSeparator == -1)
{
typeConversion.WriteLine("Type name \"{0}\" should be assembly qualified.", assemblyQualifiedTypeName);
return null;
}
string assemblyName = assemblyQualifiedTypeName.Substring(typeSeparator + 2);
string typeName = assemblyQualifiedTypeName.Substring(0, typeSeparator);
foreach (Assembly assembly in ClrFacade.GetAssemblies(typeName))
{
if (assembly.FullName == assemblyName)
{
Type converterType = null;
try
{
converterType = assembly.GetType(typeName, false, false);
}
catch (ArgumentException e)
{
typeConversion.WriteLine("Assembly \"{0}\" threw an exception when retrieving the type \"{1}\": \"{2}\".", assemblyName, typeName, e.Message);
return null;
}
try
{
return Activator.CreateInstance(converterType);
}
catch (Exception e)
{
TargetInvocationException inner = e as TargetInvocationException;
string message = (inner == null) || (inner.InnerException == null) ? e.Message : inner.InnerException.Message;
typeConversion.WriteLine("Creating an instance of type \"{0}\" caused an exception to be thrown: \"{1}\"", assemblyQualifiedTypeName, message);
return null;
}
}
}
typeConversion.WriteLine("Could not create an instance of type \"{0}\".", assemblyQualifiedTypeName);
return null;
}
/// <summary>
/// BUGBUG - brucepay Mar. 2013 - I don't think this is general enough for dynamic keywords to support arbitrary target
/// languages with arbitrary type representations so we may need an extension point here...
///
/// Maps a .NET or CIM type name string (e.g. SInt32) to the form expected by PowerShell users, namely "[typename]"
/// If there is no mapping, then it returns null.
/// If the string to convert is null or empty then the function returns "[object]" as the default typeless type.
/// </summary>
/// <param name="typeName">The typename string to convert.</param>
/// <returns>The equivalent PowerShell representation of that type.</returns>
public static string ConvertTypeNameToPSTypeName(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return "[object]";
}
string mappedType;
if (s_nameMap.TryGetValue(typeName, out mappedType))
{
return ('[' + mappedType + ']');
}
// Then check dot net types
Type dotNetType;
if (TypeResolver.TryResolveType(typeName, out dotNetType))
{
// Pass through the canonicalize type name we get back from the type converter...
return '[' + LanguagePrimitives.ConvertTo<string>(dotNetType) + ']';
}
// No mapping is found, return null
return null;
}
//
// CIM name string to .NET namestring mapping table
// (Considered using the MI routines but they didn't do quite the right thing.
//
private static Dictionary<string, string> s_nameMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "SInt8", "SByte" },
{ "UInt8", "Byte" },
{ "SInt16", "Int16" },
{ "UInt16", "UInt16" },
{ "SInt32", "Int32" },
{ "UInt32", "UInt32" },
{ "SInt64", "Int64" },
{ "UInt64", "UInt64" },
{ "Real32", "Single" },
{ "Real64", "double" },
{ "Boolean", "bool" },
{ "String", "string" },
{ "DateTime", "DateTime" },
{ "Reference", "CimInstance" },
{ "Char16", "char" },
{ "Instance", "CimInstance" },
{ "BooleanArray", "bool[]" },
{ "UInt8Array", "byte[]" },
{ "SInt8Array", "Sbyte[]" },
{ "UInt16Array", "uint16[]" },
{ "SInt16Array", "int64[]" },
{ "UInt32Array", "UInt32[]" },
{ "SInt32Array", "Int32[]" },
{ "UInt64Array", "UInt64[]" },
{ "SInt64Array", "Int64[]" },
{ "Real32Array", "Single[]" },
{ "Real64Array", "double[]" },
{ "Char16Array", "char[]" },
{ "DateTimeArray", "DateTime[]" },
{ "StringArray", "string[]" },
{ "ReferenceArray", "CimInstance[]" },
{ "InstanceArray", "CimInstance[]" },
{ "Unknown", "UnknownType" },
};
#region public type conversion
/// <summary>
/// Converts valueToConvert to resultType
/// </summary>
/// <remarks>
/// A null valueToConvert can be converted to :
/// string - returns ""
/// char - returns '\0'
/// numeric types - returns 0 converted to the appropriate type
/// boolean - returns LanguagePrimitives.IsTrue(null)
/// PSObject - returns new PSObject())
/// array - returns an array with null in array[0]
/// non value types - returns null
///
/// The following conversions are considered language standard and cannot be customized:
/// - from derived to base class - returns valueToConvert intact
/// - to PSObject - returns PSObject.AsPSObject(valueToConvert)
/// - to void - returns AutomationNull.Value
/// - from array/IEnumerable to array - tries to convert array/IEnumerable elements
/// - from object of type X to array of X - returns an array with object as its only element
/// - to bool - returns LanguagePrimitives.IsTrue(valueToConvert)
/// - to string - returns a string representation of the object.
/// In the particular case of a number to string,
/// the conversion is culture invariant.
/// - from IDictionary to Hashtable - uses the Hashtable constructor
/// - to XmlDocument - creates a new XmlDocument with the
/// string representation of valueToConvert
/// - from string to char[] - returns ((string)valueToConvert).ToCharArray()
/// - from string to RegEx - creates a new RegEx with the string
/// - from string to Type - looks up the type in the minishell's assemblies
/// - from empty string to numeric - returns 0 converted to the appropriate type
/// - from string to numeric - returns a culture invariant conversion
/// - from ScriptBlock to Delegate - returns a delegate wrapping that scriptblock.
/// - from Integer to Enumeration - Uses Enum.ToObject
/// - to WMI - Instantiate a WMI instance using
/// System.Management.ManagementObject
/// - to WMISearcher - returns objects from running WQL query with the
/// string representation of valueToConvert. The
/// query is run using ManagementObjectSearcher Class.
/// - to WMIClass - returns ManagementClass represented by the
/// string representation of valueToConvert.
/// - to ADSI - returns DirectoryEntry represented by the
/// string representation of valueToConvert.
/// - to ADSISearcher - return DirectorySearcher represented by the
/// string representation of valueToConvert.
///
/// If none of the cases above is true, the following is considered in order:
///
/// 1) TypeConverter and PSTypeConverter
/// 2) the Parse methods if the valueToConvert is a string
/// 3) Constructors in resultType that take one parameter with type valueToConvert.GetType()
/// 4) Implicit and explicit cast operators
/// 5) IConvertible
///
/// If any operation above throws an exception, this exception will be wrapped into a
/// PSInvalidCastException and thrown resulting in no further conversion attempt.
/// </remarks>
/// <param name="valueToConvert">value to be converted and returned</param>
/// <param name="resultType">type to convert valueToConvert</param>
/// <returns>converted value</returns>
/// <exception cref="ArgumentNullException">if resultType is null</exception>
/// <exception cref="PSInvalidCastException">if the conversion failed</exception>
public static object ConvertTo(object valueToConvert, Type resultType)
{
return ConvertTo(valueToConvert, resultType, true, CultureInfo.InvariantCulture, null);
}
/// <summary>
/// Converts valueToConvert to resultType possibly considering formatProvider
/// </summary>
/// <remarks>
/// A null valueToConvert can be converted to :
/// string - returns ""
/// char - returns '\0'
/// numeric types - returns 0 converted to the appropriate type
/// boolean - returns LanguagePrimitives.IsTrue(null)
/// PSObject - returns new PSObject())
/// array - returns an array with null in array[0]
/// non value types - returns null
///
/// The following conversions are considered language standard and cannot be customized:
/// - from derived to base class - returns valueToConvert intact
/// - to PSObject - returns PSObject.AsPSObject(valueToConvert)
/// - to void - returns AutomationNull.Value
/// - from array/IEnumerable to array - tries to convert array/IEnumerable elements
/// - from object of type X to array of X - returns an array with object as its only element
/// - to bool - returns LanguagePrimitives.IsTrue(valueToConvert)
/// - to string - returns a string representation of the object.
/// In the particular case of a number to string,
/// the conversion is culture invariant.
/// - from IDictionary to Hashtable - uses the Hashtable constructor
/// - to XmlDocument - creates a new XmlDocument with the
/// string representation of valueToConvert
/// - from string to char[] - returns ((string)valueToConvert).ToCharArray()
/// - from string to RegEx - creates a new RegEx with the string
/// - from string to Type - looks up the type in the minishell's assemblies
/// - from empty string to numeric - returns 0 converted to the appropriate type
/// - from string to numeric - returns a culture invariant conversion
/// - from ScriptBlock to Delegate - returns a delegate wrapping that scriptblock.
/// - from Integer to Enumeration - Uses Enum.ToObject
///
/// If none of the cases above is true, the following is considered in order:
///
/// 1) TypeConverter and PSTypeConverter
/// 2) the Parse methods if the valueToConvert is a string
/// 3) Constructors in resultType that take one parameter with type valueToConvert.GetType()
/// 4) Implicit and explicit cast operators
/// 5) IConvertible
///
/// If any operation above throws an exception, this exception will be wrapped into a
/// PSInvalidCastException and thrown resulting in no further conversion attempt.
/// </remarks>
/// <param name="valueToConvert">value to be converted and returned</param>
/// <param name="resultType">type to convert valueToConvert</param>
/// <param name="formatProvider">To be used in custom type conversions, to call parse and to call Convert.ChangeType</param>
/// <returns>converted value</returns>
/// <exception cref="ArgumentNullException">if resultType is null</exception>
/// <exception cref="PSInvalidCastException">if the conversion failed</exception>
public static object ConvertTo(object valueToConvert, Type resultType, IFormatProvider formatProvider)
{
return ConvertTo(valueToConvert, resultType, true, formatProvider, null);
}
/// <summary>
/// Converts PSObject to resultType.
/// </summary>
/// <param name="valueToConvert">value to be converted and returned.</param>
/// <param name="resultType">type to convert psobject.</param>
/// <param name="recursion">Indicates if inner properties have to be recursively converted.</param>
/// <param name="formatProvider">To be used in custom type conversions, to call parse and to call Convert.ChangeType</param>
/// <param name="ignoreUnknownMembers">Indicates if Unknown members in the psobject have to be ignored if the corresponding members in resultType do not exist.</param>
/// <returns>converted value.</returns>
public static object ConvertPSObjectToType(PSObject valueToConvert, Type resultType, bool recursion, IFormatProvider formatProvider, bool ignoreUnknownMembers)
{
if (valueToConvert != null)
{
ConstructorInfo toConstructor = resultType.GetConstructor(PSTypeExtensions.EmptyTypes);
ConvertViaNoArgumentConstructor noArgumentConstructorConverter = new ConvertViaNoArgumentConstructor(toConstructor, resultType);
return noArgumentConstructorConverter.Convert(PSObject.Base(valueToConvert), resultType, recursion, (PSObject)valueToConvert, formatProvider, null, ignoreUnknownMembers);
}
return null;
}
/// <summary>
/// Generic convertto that simplifies working with workflow.
/// </summary>
/// <typeparam name="T">The type of object to return</typeparam>
/// <param name="valueToConvert"></param>
/// <returns></returns>
public static T ConvertTo<T>(object valueToConvert)
{
if (valueToConvert is T)
{
return (T)valueToConvert;
}
return (T)ConvertTo(valueToConvert, typeof(T), true, CultureInfo.InvariantCulture, null);
}
/// <summary>
/// Sets result to valueToConvert converted to resultType.
/// </summary>
/// <remarks>
/// This method is a variant of ConvertTo that does not throw exceptions if the conversion fails.
/// </remarks>
/// <param name="valueToConvert">value to be converted and returned</param>
/// <param name="result">result of the conversion. This is valid only if the return is true.</param>
/// <returns>false for conversion failure, true for success</returns>
public static bool TryConvertTo<T>(object valueToConvert, out T result)
{
if (valueToConvert is T)
{
result = (T)valueToConvert;
return true;
}
return TryConvertTo(valueToConvert, CultureInfo.InvariantCulture, out result);
}
/// <summary>
/// Sets result to valueToConvert converted to resultType considering formatProvider
/// for custom conversions, calling the Parse method and calling Convert.ChangeType.
/// </summary>
/// <remarks>
/// This method is a variant of ConvertTo that does not throw exceptions if the conversion fails.
/// </remarks>
/// <param name="valueToConvert">value to be converted and returned</param>
/// <param name="formatProvider">governing conversion of types</param>
/// <param name="result">result of the conversion. This is valid only if the return is true.</param>
/// <returns>false for conversion failure, true for success</returns>
public static bool TryConvertTo<T>(object valueToConvert, IFormatProvider formatProvider, out T result)
{
result = default(T);
try
{
result = (T)ConvertTo(valueToConvert, typeof(T), formatProvider);
}
catch (InvalidCastException)
{
return false;
}
catch (ArgumentException)
{
return false;
}
return true;
}
/// <summary>
/// Sets result to valueToConvert converted to resultType.
/// </summary>
/// <remarks>
/// This method is a variant of ConvertTo that does not throw exceptions if the conversion fails.
/// </remarks>
/// <param name="valueToConvert">value to be converted and returned</param>
/// <param name="resultType">type to convert valueToConvert</param>
/// <param name="result">result of the conversion. This is valid only if the return is true.</param>
/// <returns>false for conversion failure, true for success</returns>
public static bool TryConvertTo(object valueToConvert, Type resultType, out object result)
{
return TryConvertTo(valueToConvert, resultType, CultureInfo.InvariantCulture, out result);
}
/// <summary>
/// Sets result to valueToConvert converted to resultType considering formatProvider
/// for custom conversions, calling the Parse method and calling Convert.ChangeType.
/// </summary>
/// <remarks>
/// This method is a variant of ConvertTo that does not throw exceptions if the conversion fails.
/// </remarks>
/// <param name="valueToConvert">value to be converted and returned</param>
/// <param name="resultType">type to convert valueToConvert</param>
/// <param name="formatProvider">governing conversion of types</param>
/// <param name="result">result of the conversion. This is valid only if the return is true.</param>
/// <returns>false for conversion failure, true for success</returns>
public static bool TryConvertTo(object valueToConvert, Type resultType, IFormatProvider formatProvider, out object result)
{
result = null;
try
{
result = ConvertTo(valueToConvert, resultType, formatProvider);
}
catch (InvalidCastException)
{
return false;
}
catch (ArgumentException)
{
return false;
}
return true;
}
#endregion public type conversion
internal class EnumMultipleTypeConverter : EnumSingleTypeConverter
{
public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
{
return EnumSingleTypeConverter.BaseConvertFrom(sourceValue, destinationType, formatProvider, ignoreCase, true);
}
}
internal class EnumSingleTypeConverter : PSTypeConverter
{
private class EnumHashEntry
{
internal EnumHashEntry(String[] names, Array values, UInt64 allValues, bool hasNegativeValue, bool hasFlagsAttribute)
{
this.names = names;
this.values = values;
this.allValues = allValues;
this.hasNegativeValue = hasNegativeValue;
this.hasFlagsAttribute = hasFlagsAttribute;
}
internal String[] names;
internal Array values;
internal UInt64 allValues;
internal bool hasNegativeValue;
internal bool hasFlagsAttribute;
}
// This static is thread safe based on the lock in GetEnumHashEntry
// It can be shared by Runspaces in different MiniShells
private static readonly Dictionary<Type, EnumHashEntry> s_enumTable = new Dictionary<Type, EnumHashEntry>();
private const int maxEnumTableSize = 100;
private static EnumHashEntry GetEnumHashEntry(Type enumType)
{
lock (s_enumTable)
{
EnumHashEntry returnValue;
if (s_enumTable.TryGetValue(enumType, out returnValue))
{
return returnValue;
}
if (s_enumTable.Count == maxEnumTableSize)
{
s_enumTable.Clear();
}
UInt64 allValues = 0;
bool hasNegativeValue = false;
Array values = Enum.GetValues(enumType);
// Type.GetTypeCode will return the integer type code for enumType
if (LanguagePrimitives.IsSignedInteger(enumType.GetTypeCode()))
{
foreach (object value in values)
{
Int64 valueInt64 = Convert.ToInt64(value, CultureInfo.CurrentCulture);
// A negative value cannot be flag
if (valueInt64 < 0)
{
hasNegativeValue = true;
break;
}
// we know the value is not negative, so this conversion
// always succeed
allValues |= Convert.ToUInt64(value, CultureInfo.CurrentCulture);
}
}
else
{
foreach (object value in values)
{
allValues |= Convert.ToUInt64(value, CultureInfo.CurrentCulture);
}
}
// See if the [Flag] attribute is set on this type...
// MemberInfo.GetCustomAttributes returns IEnumerable<Attribute> in CoreCLR.
bool hasFlagsAttribute = enumType.GetTypeInfo().GetCustomAttributes(typeof(FlagsAttribute), false).Any();
returnValue = new EnumHashEntry(Enum.GetNames(enumType), values, allValues, hasNegativeValue, hasFlagsAttribute);
s_enumTable.Add(enumType, returnValue);
return returnValue;
}
}
public override bool CanConvertFrom(object sourceValue, Type destinationType)
{
return sourceValue is string && destinationType.GetTypeInfo().IsEnum;
}
/// <summary>
/// Checks if the enumValue is defined or not in enumType.
/// </summary>
/// <param name="enumType">some enumeration</param>
/// <param name="enumValue">supposed to be an integer</param>
/// <returns>
/// </returns>
private static bool IsDefinedEnum(object enumValue, Type enumType)
{
bool isDefined;
do
{
if (enumValue == null)
{
isDefined = false;
break;
}
EnumHashEntry enumHashEntry = EnumSingleTypeConverter.GetEnumHashEntry(enumType);
// An enumeration with a negative value should not be treated as flags
// so IsValueFlagDefined cannot determine the result, and as far as it knows,
// it is defined.
if (enumHashEntry.hasNegativeValue)
{
isDefined = true;
break;
}
// Type.GetTypeCode will return the integer type code for enumValue.GetType()
if (LanguagePrimitives.IsSignedInteger(enumValue.GetType().GetTypeCode()))
{
Int64 enumValueInt64 = Convert.ToInt64(enumValue, CultureInfo.CurrentCulture);
// A negative value cannot be flag, so we return false
if (enumValueInt64 < 0)
{
isDefined = false;
break;
}
}
// the if above, guarantees that even if it is an Int64 it is > 0
// so the conversion should always work.
UInt64 enumValueUInt64 = Convert.ToUInt64(enumValue, CultureInfo.CurrentCulture);
if (enumHashEntry.hasFlagsAttribute)
{
// This expression will result in a "1 bit" for bits that are
// set in enumValueInt64 but not set in enumHashEntry.allValues,
// and a "0 bit" otherwise. Any "bit 1" in the result, indicates this is not defined.
isDefined = ((enumValueUInt64 | enumHashEntry.allValues) ^ enumHashEntry.allValues) == 0;
}
else
{
// If flags is not set, then see if this value is in the list
// of valid values.
if (Array.IndexOf(enumHashEntry.values, enumValue) >= 0)
isDefined = true;
else
isDefined = false;
}
} while (false);
return isDefined;
}
/// <summary>
/// Throws if the enumType enumeration has no negative values, but the enumValue is not
/// defined in enumType.
/// </summary>
/// <param name="enumType">some enumeration</param>
/// <param name="enumValue">supposed to be an integer</param>
/// <param name="errorId">the error id to be used when throwing an exception</param>
internal static void ThrowForUndefinedEnum(string errorId, object enumValue, Type enumType)
{
ThrowForUndefinedEnum(errorId, enumValue, enumValue, enumType);
}
/// <summary>
/// Throws if the enumType enumeration has no negative values, but the enumValue is not
/// defined in enumType.
/// </summary>
/// <param name="errorId">The error id to be used when throwing an exception</param>
/// <param name="enumValue">value to validate</param>
/// <param name="valueToUseToThrow">value to use while throwing an exception</param>
/// <param name="enumType">the enum type to validate the enumValue with.</param>
/// <remarks>
/// <paramref name="valueToUseToThrow"/> is used by those callers who want the exception
/// to contain a different value than the one that is validated.
/// This will enable callers to take different forms of input -> convert to enum using
/// Enum.Object -> then validate using this method.
/// </remarks>
internal static void ThrowForUndefinedEnum(string errorId, object enumValue, object valueToUseToThrow, Type enumType)
{
if (!IsDefinedEnum(enumValue, enumType))
{
typeConversion.WriteLine("Value {0} is not defined in the Enum {1}.", valueToUseToThrow, enumType);
throw new PSInvalidCastException(errorId, null,
ExtendedTypeSystem.InvalidCastExceptionEnumerationNoValue,
valueToUseToThrow, enumType, EnumSingleTypeConverter.EnumValues(enumType));
}
}
internal static string EnumValues(Type enumType)
{
EnumHashEntry enumHashEntry = EnumSingleTypeConverter.GetEnumHashEntry(enumType);
return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, enumHashEntry.names);
}
public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
{
return EnumSingleTypeConverter.BaseConvertFrom(sourceValue, destinationType, formatProvider, ignoreCase, false);
}
protected static object BaseConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase, bool multipleValues)
{
Diagnostics.Assert(sourceValue != null, "the type converter has a special case for null source values");
string sourceValueString = sourceValue as string;
if (sourceValueString == null)
{
throw new PSInvalidCastException("InvalidCastEnumFromTypeNotAString", null,
ExtendedTypeSystem.InvalidCastException,
sourceValue, ObjectToTypeNameString(sourceValue), destinationType);
}
Diagnostics.Assert(destinationType.GetTypeInfo().IsEnum, "EnumSingleTypeConverter is only applied to enumerations");
if (sourceValueString.Length == 0)
{
throw new PSInvalidCastException("InvalidCastEnumFromEmptyString", null,
ExtendedTypeSystem.InvalidCastException,
sourceValue, ObjectToTypeNameString(sourceValue), destinationType);
}
sourceValueString = sourceValueString.Trim();
if (sourceValueString.Length == 0)
{
throw new PSInvalidCastException("InvalidEnumCastFromEmptyStringAfterTrim", null,
ExtendedTypeSystem.InvalidCastException,
sourceValue, ObjectToTypeNameString(sourceValue), destinationType);
}
if (Char.IsDigit(sourceValueString[0]) || sourceValueString[0] == '+' || sourceValueString[0] == '-')
{
Type underlyingType = Enum.GetUnderlyingType(destinationType);
try
{
object result = Enum.ToObject(destinationType, Convert.ChangeType(sourceValueString, underlyingType, formatProvider));
ThrowForUndefinedEnum("UndefinedInEnumSingleTypeConverter", result, sourceValueString, destinationType);
return result;
}
catch (Exception) // Enum.ToObject and Convert.ChangeType might throw unadvertised exceptions
{
// we still want to try non numeric match
}
}
string[] sourceValueEntries;
WildcardPattern[] fromValuePatterns;
if (!multipleValues)
{
if (sourceValueString.Contains(","))
{
throw new PSInvalidCastException("InvalidCastEnumCommaAndNoFlags", null,
ExtendedTypeSystem.InvalidCastExceptionEnumerationNoFlagAndComma,
sourceValue, destinationType);
}
sourceValueEntries = new string[] { sourceValueString };
fromValuePatterns = new WildcardPattern[1];
if (WildcardPattern.ContainsWildcardCharacters(sourceValueString))
{
fromValuePatterns[0] = WildcardPattern.Get(sourceValueString, ignoreCase ? WildcardOptions.IgnoreCase : WildcardOptions.None);
}
else
{
fromValuePatterns[0] = null;
}
}
else
{
sourceValueEntries = sourceValueString.Split(Utils.Separators.Comma);
fromValuePatterns = new WildcardPattern[sourceValueEntries.Length];
for (int i = 0; i < sourceValueEntries.Length; i++)
{
string sourceValueEntry = sourceValueEntries[i];
if (WildcardPattern.ContainsWildcardCharacters(sourceValueEntry))
{
fromValuePatterns[i] = WildcardPattern.Get(sourceValueEntry,
ignoreCase ? WildcardOptions.IgnoreCase : WildcardOptions.None);
}
else
{
fromValuePatterns[i] = null;
}
}
}
EnumHashEntry enumHashEntry = EnumSingleTypeConverter.GetEnumHashEntry(destinationType);
string[] names = enumHashEntry.names;
Array values = enumHashEntry.values;
UInt64 returnUInt64 = 0;
StringComparison ignoreCaseOpt;
if (ignoreCase)
ignoreCaseOpt = StringComparison.OrdinalIgnoreCase;
else
ignoreCaseOpt = StringComparison.Ordinal;
for (int i = 0; i < sourceValueEntries.Length; i++)
{
string sourceValueEntry = sourceValueEntries[i];
WildcardPattern fromValuePattern = fromValuePatterns[i];
bool foundOne = false;
for (int j = 0; j < names.Length; j++)
{
string name = names[j];
if (fromValuePattern != null)
{
if (!fromValuePattern.IsMatch(name))
continue;
}
else
{
if (String.Compare(sourceValueEntry, name, ignoreCaseOpt) != 0)
continue;
}
if (!multipleValues && foundOne)
{
object firstValue = Enum.ToObject(destinationType, returnUInt64);
object secondValue = Enum.ToObject(destinationType, Convert.ToUInt64(values.GetValue(i), CultureInfo.CurrentCulture));
throw new PSInvalidCastException("InvalidCastEnumTwoStringsFoundAndNoFlags", null,
ExtendedTypeSystem.InvalidCastExceptionEnumerationMoreThanOneValue,
sourceValue, destinationType, firstValue, secondValue);
}
foundOne = true;
returnUInt64 |= Convert.ToUInt64(values.GetValue(j), CultureInfo.CurrentCulture);
}
if (!foundOne)
{
throw new PSInvalidCastException("InvalidCastEnumStringNotFound", null,
ExtendedTypeSystem.InvalidCastExceptionEnumerationNoValue,
sourceValueEntry, destinationType, EnumSingleTypeConverter.EnumValues(destinationType));
}
}
return Enum.ToObject(destinationType, returnUInt64);
}
public override bool CanConvertTo(object sourceValue, Type destinationType)
{
return false;
}
public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
{
throw PSTraceSource.NewNotSupportedException();
}
}
/// <summary>
/// There might be many cast operators in a Type A that take Type A. Each operator will have a
/// different return type. Because of that we cannot call GetMethod since it would cause a
/// AmbiguousMatchException. This auxiliary method calls GetMember to find the right method
/// </summary>
/// <param name="methodName">Either op_Explicit or op_Implicit, at the moment</param>
/// <param name="targetType">the type to look for an operator</param>
/// <param name="originalType">Type of the only parameter the operator method should have</param>
/// <param name="resultType">Return type of the operator method</param>
/// <returns>A cast operator method, or null if not found</returns>
private static MethodInfo FindCastOperator(string methodName, Type targetType, Type originalType, Type resultType)
{
using (typeConversion.TraceScope("Looking for \"{0}\" cast operator.", methodName))
{
// Get multiple matched Public & Static methods
var methods = ClrFacade.GetMethods(targetType, methodName);
foreach (MethodInfo method in methods)
{
if (!resultType.IsAssignableFrom(method.ReturnType))
{
continue;
}
System.Reflection.ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 1 || !parameters[0].ParameterType.IsAssignableFrom(originalType))
{
continue;
}
typeConversion.WriteLine("Found \"{0}\" cast operator in type {1}.", methodName, targetType.FullName);
return method;
}
typeConversion.TraceScope("Cast operator for \"{0}\" not found.", methodName);
return null;
}
}
private static object ConvertNumericThroughDouble(object valueToConvert, Type resultType)
{
using (typeConversion.TraceScope("Numeric Conversion through System.Double."))
{
// Eventual exceptions here are caught by the caller
object intermediate = Convert.ChangeType(valueToConvert, typeof(double),
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
return Convert.ChangeType(intermediate, resultType,
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
}
}
#if !CORECLR
// No Following Types In CoreCLR
// ManagementObject
// ManagementObjectSearcher
// ManagementClass
// CommaDelimitedStringCollection
// DirectoryEntry
#region Converters_Not_Available_In_CorePS
private static ManagementObject ConvertToWMI(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Standard type conversion to a ManagementObject.");
string valueToConvertString;
try
{
valueToConvertString = PSObject.ToString(null, valueToConvert, "\n", null, null, true, true);
}
catch (ExtendedTypeSystemException e)
{
typeConversion.WriteLine("Exception converting value to string: {0}", e.Message);
throw new PSInvalidCastException("InvalidCastGetStringToWMI", e,
ExtendedTypeSystem.InvalidCastExceptionNoStringForConversion,
resultType.ToString(), e.Message);
}
try
{
ManagementObject wmiObject = new ManagementObject(valueToConvertString);
// ManagementObject will not throw if path does not contain valid key
if (wmiObject.SystemProperties["__CLASS"] == null)
{
string message = StringUtil.Format(ExtendedTypeSystem.InvalidWMIPath, valueToConvertString);
throw new PSInvalidCastException(message);
}
return wmiObject;
}
catch (Exception wmiObjectException)
{
typeConversion.WriteLine("Exception creating WMI object: \"{0}\".", wmiObjectException.Message);
throw new PSInvalidCastException("InvalidCastToWMI", wmiObjectException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), wmiObjectException.Message);
}
}
private static ManagementObjectSearcher ConvertToWMISearcher(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Standard type conversion to a collection of ManagementObjects.");
string valueToConvertString;
try
{
valueToConvertString = PSObject.ToString(null, valueToConvert, "\n", null, null, true, true);
}
catch (ExtendedTypeSystemException e)
{
typeConversion.WriteLine("Exception converting value to string: {0}", e.Message);
throw new PSInvalidCastException("InvalidCastGetStringToWMISearcher", e,
ExtendedTypeSystem.InvalidCastExceptionNoStringForConversion,
resultType.ToString(), e.Message);
}
try
{
ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(valueToConvertString);
return objectSearcher;
}
catch (Exception objectSearcherException)
{
typeConversion.WriteLine("Exception running WMI object query: \"{0}\".", objectSearcherException.Message);
throw new PSInvalidCastException("InvalidCastToWMISearcher", objectSearcherException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), objectSearcherException.Message);
}
}
private static ManagementClass ConvertToWMIClass(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Standard type conversion to a ManagementClass.");
string valueToConvertString;
try
{
valueToConvertString = PSObject.ToString(null, valueToConvert, "\n", null, null, true, true);
}
catch (ExtendedTypeSystemException e)
{
typeConversion.WriteLine("Exception converting value to string: {0}", e.Message);
throw new PSInvalidCastException("InvalidCastGetStringToWMIClass", e,
ExtendedTypeSystem.InvalidCastExceptionNoStringForConversion,
resultType.ToString(), e.Message);
}
try
{
ManagementClass wmiClass = new System.Management.ManagementClass(valueToConvertString);
// ManagementClass will not throw if the path specified is not
// a valid class.
if (wmiClass.SystemProperties["__CLASS"] == null)
{
string message = StringUtil.Format(ExtendedTypeSystem.InvalidWMIClassPath, valueToConvertString);
throw new PSInvalidCastException(message);
}
return wmiClass;
}
catch (Exception wmiClassException)
{
typeConversion.WriteLine("Exception creating WMI class: \"{0}\".", wmiClassException.Message);
throw new PSInvalidCastException("InvalidCastToWMIClass", wmiClassException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), wmiClassException.Message);
}
}
// System.Configuration.CommaDelimitedStringCollection is derived from the StringCollection class
private static System.Configuration.CommaDelimitedStringCollection ConvertToCommaDelimitedStringCollection(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Standard type conversion to a CommaDelimitedStringCollection.");
var commaDelimitedStringCollection = new System.Configuration.CommaDelimitedStringCollection();
AddItemsToCollection(valueToConvert, resultType, formatProvider, backupTable, commaDelimitedStringCollection);
return commaDelimitedStringCollection;
}
private static DirectoryEntry ConvertToADSI(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Standard type conversion to DirectoryEntry.");
string valueToConvertString;
try
{
valueToConvertString = PSObject.ToString(null, valueToConvert, "\n", null, null, true, true);
}
catch (ExtendedTypeSystemException e)
{
typeConversion.WriteLine("Exception converting value to string: {0}", e.Message);
throw new PSInvalidCastException("InvalidCastGetStringToADSIClass", e,
ExtendedTypeSystem.InvalidCastExceptionNoStringForConversion,
resultType.ToString(), e.Message);
}
try
{
DirectoryEntry entry = new DirectoryEntry(valueToConvertString);
return entry;
}
catch (Exception adsiClassException)
{
typeConversion.WriteLine("Exception creating ADSI class: \"{0}\".", adsiClassException.Message);
throw new PSInvalidCastException("InvalidCastToADSIClass", adsiClassException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), adsiClassException.Message);
}
}
private static DirectorySearcher ConvertToADSISearcher(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Standard type conversion to ADSISearcher");
try
{
return new DirectorySearcher((string)valueToConvert);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception creating ADSI searcher: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastToADSISearcher", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
#endregion Converters_Not_Available_In_CorePS
#endif
private static StringCollection ConvertToStringCollection(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Standard type conversion to a StringCollection.");
var stringCollection = new StringCollection();
AddItemsToCollection(valueToConvert, resultType, formatProvider, backupTable, stringCollection);
return stringCollection;
}
private static void AddItemsToCollection(object valueToConvert, Type resultType, IFormatProvider formatProvider, TypeTable backupTable, StringCollection stringCollection)
{
try
{
var stringArrayValue = (string[])ConvertTo(valueToConvert, typeof(string[]), false, formatProvider, backupTable);
stringCollection.AddRange(stringArrayValue);
}
catch (PSInvalidCastException)
{
typeConversion.WriteLine("valueToConvert contains non-string type values");
var argEx = new ArgumentException(StringUtil.Format(ExtendedTypeSystem.CannotConvertValueToStringArray, valueToConvert.ToString()));
throw new PSInvalidCastException(StringUtil.Format("InvalidCastTo{0}Class", resultType.Name), argEx,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException, valueToConvert.ToString(), resultType.ToString(), argEx.Message);
}
catch (Exception ex)
{
typeConversion.WriteLine("Exception creating StringCollection class: \"{0}\".", ex.Message);
throw new PSInvalidCastException(StringUtil.Format("InvalidCastTo{0}Class", resultType.Name), ex,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException, valueToConvert.ToString(), resultType.ToString(), ex.Message);
}
}
private static XmlDocument ConvertToXml(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
using (typeConversion.TraceScope("Standard type conversion to XmlDocument."))
{
string valueToConvertString;
try
{
valueToConvertString = PSObject.ToString(null, valueToConvert, "\n", null, null, true, true);
}
catch (ExtendedTypeSystemException e)
{
typeConversion.WriteLine("Exception converting value to string: {0}", e.Message);
throw new PSInvalidCastException("InvalidCastGetStringToXmlDocument", e,
ExtendedTypeSystem.InvalidCastExceptionNoStringForConversion,
resultType.ToString(), e.Message);
}
try
{
using (TextReader textReader = new StringReader(valueToConvertString))
{
// Win8: 481571 Enforcing "PreserveWhitespace" breaks XML pretty printing
XmlReaderSettings settings = InternalDeserializer.XmlReaderSettingsForUntrustedXmlDocument.Clone();
settings.IgnoreWhitespace = true;
settings.IgnoreProcessingInstructions = false;
settings.IgnoreComments = false;
XmlReader xmlReader = XmlReader.Create(textReader, settings);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = false;
xmlDocument.Load(xmlReader);
return xmlDocument;
}
}
catch (Exception loadXmlException)
{
typeConversion.WriteLine("Exception loading XML: \"{0}\".", loadXmlException.Message);
throw new PSInvalidCastException("InvalidCastToXmlDocument", loadXmlException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), loadXmlException.Message);
}
}
}
private static CultureInfo GetCultureFromFormatProvider(IFormatProvider formatProvider)
{
CultureInfo returnValue = formatProvider as CultureInfo ?? CultureInfo.InvariantCulture;
return returnValue;
}
/// backupTypeTable:
/// Used by Remoting Rehydration Logic. While Deserializing a remote object,
/// LocalPipeline.ExecutionContextFromTLS() might return null..In which case this
/// TypeTable will be used to do the conversion.
private static bool IsCustomTypeConversion(object valueToConvert,
Type resultType,
IFormatProvider formatProvider,
out object result,
TypeTable backupTypeTable)
{
using (typeConversion.TraceScope("Custom type conversion."))
{
object baseValueToConvert = PSObject.Base(valueToConvert);
Type originalType = baseValueToConvert.GetType();
// first using ConvertTo for the original type
object valueConverter = GetConverter(originalType, backupTypeTable);
if ((valueConverter != null))
{
TypeConverter valueTypeConverter = valueConverter as TypeConverter;
if (valueTypeConverter != null)
{
typeConversion.WriteLine("Original type's converter is TypeConverter.");
if (valueTypeConverter.CanConvertTo(resultType))
{
typeConversion.WriteLine("TypeConverter can convert to resultType.");
try
{
result = valueTypeConverter.ConvertTo(null, GetCultureFromFormatProvider(formatProvider), baseValueToConvert, resultType);
return true;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting with Original type's TypeConverter: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastTypeConvertersConvertTo", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
else
{
typeConversion.WriteLine("TypeConverter cannot convert to resultType.");
}
}
PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter;
if (valuePSTypeConverter != null)
{
typeConversion.WriteLine("Original type's converter is PSTypeConverter.");
PSObject psValueToConvert = PSObject.AsPSObject(valueToConvert);
if (valuePSTypeConverter.CanConvertTo(psValueToConvert, resultType))
{
typeConversion.WriteLine("Original type's PSTypeConverter can convert to resultType.");
try
{
result = valuePSTypeConverter.ConvertTo(psValueToConvert, resultType, formatProvider, true);
return true;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting with Original type's PSTypeConverter: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastPSTypeConvertersConvertTo", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
else
{
typeConversion.WriteLine("Original type's PSTypeConverter cannot convert to resultType.");
}
}
}
s_tracer.WriteLine("No converter found in original type.");
// now ConvertFrom for the destination type
valueConverter = GetConverter(resultType, backupTypeTable);
if (valueConverter != null)
{
TypeConverter valueTypeConverter = valueConverter as TypeConverter;
if (valueTypeConverter != null)
{
typeConversion.WriteLine("Destination type's converter is TypeConverter that can convert from originalType.");
if (valueTypeConverter.CanConvertFrom(originalType))
{
typeConversion.WriteLine("Destination type's converter can convert from originalType.");
try
{
result = valueTypeConverter.ConvertFrom(null, GetCultureFromFormatProvider(formatProvider), baseValueToConvert);
return true;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting with Destination type's TypeConverter: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastTypeConvertersConvertFrom", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
else
{
typeConversion.WriteLine("Destination type's converter cannot convert from originalType.");
}
}
PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter;
if (valuePSTypeConverter != null)
{
typeConversion.WriteLine("Destination type's converter is PSTypeConverter.");
PSObject psValueToConvert = PSObject.AsPSObject(valueToConvert);
if (valuePSTypeConverter.CanConvertFrom(psValueToConvert, resultType))
{
typeConversion.WriteLine("Destination type's converter can convert from originalType.");
try
{
result = valuePSTypeConverter.ConvertFrom(psValueToConvert, resultType, formatProvider, true);
return true;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting with Destination type's PSTypeConverter: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastPSTypeConvertersConvertFrom", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
else
{
typeConversion.WriteLine("Destination type's converter cannot convert from originalType.");
}
}
}
result = null;
return false;
}
}
private static object ConvertNumericChar(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
// Convert char through int to float/double.
object result = Convert.ChangeType(
Convert.ChangeType(valueToConvert, typeof(int), formatProvider), resultType, formatProvider);
typeConversion.WriteLine("Numeric conversion succeeded.");
return result;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting with IConvertible: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastIConvertible", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static object ConvertNumeric(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
object result = Convert.ChangeType(valueToConvert, resultType, formatProvider);
typeConversion.WriteLine("Numeric conversion succeeded.");
return result;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting with IConvertible: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastIConvertible", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static char[] ConvertStringToCharArray(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Diagnostics.Assert(valueToConvert is string, "Value to convert must be string");
typeConversion.WriteLine("Returning value to convert's ToCharArray().");
// This conversion is not wrapped in a try/catch because it can't raise an exception
// unless the string object has been corrupted.
return ((string)valueToConvert).ToCharArray();
}
private static Regex ConvertStringToRegex(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Diagnostics.Assert(valueToConvert is string, "Value to convert must be string");
typeConversion.WriteLine("Returning new RegEx(value to convert).");
try
{
return new Regex((string)valueToConvert);
}
catch (Exception regexException)
{
typeConversion.WriteLine("Exception in RegEx constructor: \"{0}\".", regexException.Message);
throw new PSInvalidCastException("InvalidCastFromStringToRegex", regexException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), regexException.Message);
}
}
private static Microsoft.Management.Infrastructure.CimSession ConvertStringToCimSession(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Diagnostics.Assert(valueToConvert is string, "Value to convert must be string");
typeConversion.WriteLine("Returning CimSession.Create(value to convert).");
try
{
return Microsoft.Management.Infrastructure.CimSession.Create((string)valueToConvert);
}
catch (Microsoft.Management.Infrastructure.CimException cimException)
{
typeConversion.WriteLine("Exception in CimSession.Create: \"{0}\".", cimException.Message);
throw new PSInvalidCastException("InvalidCastFromStringToCimSession", cimException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), cimException.Message);
}
}
private static Type ConvertStringToType(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Diagnostics.Assert(valueToConvert is string, "Value to convert must be a string");
Exception exception;
Type namedType = TypeResolver.ResolveType((string)valueToConvert, out exception);
if (namedType == null)
{
if (exception is PSInvalidCastException)
{
throw exception;
}
throw new PSInvalidCastException("InvalidCastFromStringToType", exception,
ExtendedTypeSystem.InvalidCastException,
valueToConvert.ToString(), ObjectToTypeNameString(valueToConvert), resultType.ToString());
}
return namedType;
}
/// <summary>
/// We need to add this built-in converter because in FullCLR, System.Uri has a TypeConverter attribute
/// declared: [TypeConverter(typeof(UriTypeConverter))], so the conversion from 'string' to 'Uri' is
/// actually taken care of by 'UriTypeConverter'. However, the type 'UriTypeConverter' is not available
/// in CoreCLR, and thus the conversion from 'string' to 'Uri' would show a different behavior.
///
/// Therefore, we just add this built-in string-to-uri converter using the same logic 'UriTypeConverter'
/// is using in FullCLR, so the conversion behavior will be the same on desktop powershell and powershell core.
/// </summary>
private static Uri ConvertStringToUri(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
Diagnostics.Assert(valueToConvert is string, "Value to convert must be a string");
return new Uri((string)valueToConvert, UriKind.RelativeOrAbsolute);
}
catch (Exception uriException)
{
typeConversion.WriteLine("Exception in Uri constructor: \"{0}\".", uriException.Message);
throw new PSInvalidCastException("InvalidCastFromStringToUri", uriException,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), uriException.Message);
}
}
private static object ConvertStringToInteger(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
var strToConvert = valueToConvert as string;
Diagnostics.Assert(strToConvert != null, "Value to convert must be a string");
Diagnostics.Assert(IsNumeric(GetTypeCode(resultType)), "Result type must be numeric");
if (strToConvert.Length == 0)
{
typeConversion.WriteLine("Returning numeric zero.");
// This is not wrapped in a try/catch because it can't fail.
return System.Convert.ChangeType(0, resultType, CultureInfo.InvariantCulture);
}
typeConversion.WriteLine("Converting to integer.");
TypeConverter integerConverter = LanguagePrimitives.GetIntegerSystemConverter(resultType);
try
{
return integerConverter.ConvertFrom(strToConvert);
}
catch (Exception e)
{
// This catch has one extra reason to be generic (Exception e).
// integerConverter.ConvertFrom warps its exceptions in a System.Exception.
if (e.InnerException != null)
{
e = e.InnerException;
}
typeConversion.WriteLine("Exception converting to integer: \"{0}\".", e.Message);
if (e is FormatException)
{
typeConversion.WriteLine("Converting to integer passing through double.");
try
{
return ConvertNumericThroughDouble(strToConvert, resultType);
}
catch (Exception ex) // swallow non-severe exceptions
{
typeConversion.WriteLine("Exception converting to integer through double: \"{0}\".", ex.Message);
}
}
throw new PSInvalidCastException("InvalidCastFromStringToInteger", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
strToConvert, resultType.ToString(), e.Message);
}
}
private static object ConvertStringToDecimal(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Diagnostics.Assert(valueToConvert is string, "Value to convert must be a string");
if (((string)valueToConvert).Length == 0)
{
typeConversion.WriteLine("Returning numeric zero.");
// This is not wrapped in a try/catch because it can't fail.
return System.Convert.ChangeType(0, resultType, CultureInfo.InvariantCulture);
}
typeConversion.WriteLine("Converting to decimal.");
try
{
return Convert.ChangeType(valueToConvert, resultType,
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting to decimal: \"{0}\". Converting to decimal passing through double.", e.Message);
if (e is FormatException)
{
try
{
return ConvertNumericThroughDouble(valueToConvert, resultType);
}
catch (Exception ex)
{
typeConversion.WriteLine("Exception converting to integer through double: \"{0}\".", ex.Message);
}
}
throw new PSInvalidCastException("InvalidCastFromStringToDecimal", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static object ConvertStringToReal(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Diagnostics.Assert(valueToConvert is string, "Value to convert must be a string");
if (((string)valueToConvert).Length == 0)
{
typeConversion.WriteLine("Returning numeric zero.");
// This is not wrapped in a try/catch because it can't fail.
return System.Convert.ChangeType(0, resultType, CultureInfo.InvariantCulture);
}
typeConversion.WriteLine("Converting to double or single.");
try
{
return Convert.ChangeType(valueToConvert, resultType,
System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting to double or single: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastFromStringToDoubleOrSingle", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static object ConvertAssignableFrom(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Result type is assignable from value to convert's type");
return valueToConvert;
}
private static PSObject ConvertToPSObject(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Returning PSObject.AsPSObject(valueToConvert).");
return PSObject.AsPSObject(valueToConvert);
}
private static object ConvertToVoid(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("returning AutomationNull.Value.");
return AutomationNull.Value;
}
private static bool ConvertClassToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting ref to boolean.");
return valueToConvert != null;
}
private static bool ConvertValueToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting value to boolean.");
return true;
}
private static bool ConvertStringToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting string to boolean.");
return LanguagePrimitives.IsTrue((string)valueToConvert);
}
private static bool ConvertInt16ToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((Int16)valueToConvert) != default(Int16);
}
private static bool ConvertInt32ToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((Int32)valueToConvert) != default(Int32);
}
private static bool ConvertInt64ToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((Int64)valueToConvert) != default(Int64);
}
private static bool ConvertUInt16ToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((UInt16)valueToConvert) != default(UInt16);
}
private static bool ConvertUInt32ToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((UInt32)valueToConvert) != default(UInt32);
}
private static bool ConvertUInt64ToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((UInt64)valueToConvert) != default(UInt64);
}
private static bool ConvertSByteToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((SByte)valueToConvert) != default(SByte);
}
private static bool ConvertByteToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((Byte)valueToConvert) != default(Byte);
}
private static bool ConvertSingleToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((Single)valueToConvert) != default(Single);
}
private static bool ConvertDoubleToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((Double)valueToConvert) != default(Double);
}
private static bool ConvertDecimalToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return ((Decimal)valueToConvert) != default(Decimal);
}
private static PSConverter<bool> CreateNumericToBoolConverter(Type fromType)
{
Diagnostics.Assert(LanguagePrimitives.IsNumeric(fromType.GetTypeCode()), "Can only convert numeric types");
var valueToConvert = Expression.Parameter(typeof(object));
var parameters = new ParameterExpression[]
{
valueToConvert,
Expression.Parameter(typeof(Type)),
Expression.Parameter(typeof(bool)),
Expression.Parameter(typeof(PSObject)),
Expression.Parameter(typeof(IFormatProvider)),
Expression.Parameter(typeof(TypeTable))
};
return Expression.Lambda<PSConverter<bool>>(
Expression.NotEqual(Expression.Default(fromType), valueToConvert.Cast(fromType)),
parameters).Compile();
}
private static bool ConvertCharToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting char to boolean.");
char c = (char)valueToConvert;
return c != '\0';
}
private static bool ConvertSwitchParameterToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting SwitchParameter to boolean.");
return ((SwitchParameter)valueToConvert).ToBool();
}
private static bool ConvertIListToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting IList to boolean.");
return IsTrue((IList)valueToConvert);
}
private static string ConvertNumericToString(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
if (originalValueToConvert != null && originalValueToConvert.TokenText != null)
{
return originalValueToConvert.TokenText;
}
typeConversion.WriteLine("Converting numeric to string.");
try
{
// Ignore formatProvider here, the conversion should be culture invariant.
return (string)Convert.ChangeType(valueToConvert, resultType, CultureInfo.InvariantCulture.NumberFormat);
}
catch (Exception e)
{
typeConversion.WriteLine("Converting numeric to string Exception: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastFromNumericToString", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static string ConvertNonNumericToString(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS();
try
{
typeConversion.WriteLine("Converting object to string.");
return PSObject.ToStringParser(ecFromTLS, valueToConvert);
}
catch (ExtendedTypeSystemException e)
{
typeConversion.WriteLine("Converting object to string Exception: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", e,
ExtendedTypeSystem.InvalidCastCannotRetrieveString);
}
}
private static Hashtable ConvertIDictionaryToHashtable(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting to Hashtable.");
return new Hashtable(valueToConvert as IDictionary);
}
private static PSReference ConvertToPSReference(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting to PSReference.");
Dbg.Assert(valueToConvert != null, "[ref]$null cast should be handler earlier with a separate ConvertNullToPSReference method");
return PSReference.CreateInstance(valueToConvert, valueToConvert.GetType());
}
private static Delegate ConvertScriptBlockToDelegate(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Exception exception = null;
try
{
return ((ScriptBlock)valueToConvert).GetDelegate(resultType);
}
catch (ArgumentNullException e)
{
exception = e;
}
catch (ArgumentException e)
{
exception = e;
}
catch (MissingMethodException e)
{
exception = e;
}
catch (MemberAccessException e)
{
exception = e;
}
typeConversion.WriteLine("Converting script block to delegate Exception: \"{0}\".", exception.Message);
throw new PSInvalidCastException("InvalidCastFromScriptBlockToDelegate", exception,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), exception.Message);
}
private static object ConvertToNullable(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
// The CLR doesn't support boxed Nullable<T>. Instead, languages convert to T and box.
return ConvertTo(valueToConvert, Nullable.GetUnderlyingType(resultType), recursion, formatProvider, backupTable);
}
private static object ConvertRelatedArrays(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("The element type of result is assignable from the element type of the value to convert");
var originalAsArray = (Array)valueToConvert;
var newValue = Array.CreateInstance(resultType.GetElementType(), originalAsArray.Length);
originalAsArray.CopyTo(newValue, 0);
return newValue;
}
private static object ConvertUnrelatedArrays(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
Array valueAsArray = valueToConvert as Array;
Type resultElementType = resultType.GetElementType();
Array resultArray = Array.CreateInstance(resultElementType, valueAsArray.Length);
for (int i = 0; i < valueAsArray.Length; i++)
{
object resultElement = ConvertTo(valueAsArray.GetValue(i), resultElementType, false, formatProvider, backupTable);
resultArray.SetValue(resultElement, i);
}
return resultArray;
}
private static object ConvertEnumerableToArray(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
ArrayList result = new ArrayList();
Type resultElementType = resultType == typeof(Array) ? typeof(object) : resultType.GetElementType();
typeConversion.WriteLine("Converting elements in the value to convert to the result's element type.");
foreach (object obj in LanguagePrimitives.GetEnumerable(valueToConvert))
{
// false means no further recursions and therefore no cycles
result.Add(ConvertTo(obj, resultElementType, false, formatProvider, backupTable));
}
return result.ToArray(resultElementType);
}
catch (Exception e)
{
typeConversion.WriteLine("Element conversion exception: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastExceptionEnumerableToArray", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static object ConvertScalarToArray(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Value to convert is scalar.");
if (originalValueToConvert != null && originalValueToConvert.TokenText != null)
{
valueToConvert = originalValueToConvert;
}
try
{
Type resultElementType = resultType == typeof(Array) ? typeof(object) : resultType.GetElementType();
ArrayList result = new ArrayList();
// false means no further recursions and therefore no cycles
result.Add(ConvertTo(valueToConvert, resultElementType, false, formatProvider, backupTable));
return result.ToArray(resultElementType);
}
catch (Exception e)
{
typeConversion.WriteLine("Element conversion exception: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastExceptionScalarToArray", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static object ConvertIntegerToEnum(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
object result;
try
{
result = System.Enum.ToObject(resultType, valueToConvert);
}
catch (Exception e)
{
typeConversion.WriteLine("Integer to System.Enum exception: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastExceptionIntegerToEnum", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
// Check if the result is a defined enum..otherwise throw an error
// valueToConvert is the user supplied value. Use that in the error message.
EnumSingleTypeConverter.ThrowForUndefinedEnum("UndefinedIntegerToEnum", result, valueToConvert, resultType);
return result;
}
private static object ConvertStringToEnum(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
string valueAsString = valueToConvert as string;
object result = null;
typeConversion.WriteLine("Calling case sensitive Enum.Parse");
try
{
result = Enum.Parse(resultType, valueAsString);
}
catch (ArgumentException e)
{
typeConversion.WriteLine("Enum.Parse Exception: \"{0}\".", e.Message);
// Enum.Parse will always throw this kind of exception.
// Even when no map exists. We want to try without case sensitivity
// If it works, we will return it, otherwise a new exception will
// be thrown and we will use it to set exceptionToWrap
try
{
typeConversion.WriteLine("Calling case insensitive Enum.Parse");
result = Enum.Parse(resultType, valueAsString, true);
}
catch (ArgumentException inner)
{
typeConversion.WriteLine("Enum.Parse Exception: \"{0}\".", inner.Message);
}
catch (Exception ex) // Enum.Parse might throw unadvertised exceptions
{
typeConversion.WriteLine("Case insensitive Enum.Parse threw an exception.");
throw new PSInvalidCastException("CaseInsensitiveEnumParseThrewAnException", ex,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), ex.Message);
}
}
catch (Exception e) // Enum.Parse might throw unadvertised exceptions
{
typeConversion.WriteLine("Case Sensitive Enum.Parse threw an exception.");
throw new PSInvalidCastException("CaseSensitiveEnumParseThrewAnException", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
if (result == null)
{
typeConversion.WriteLine("Calling substring disambiguation.");
try
{
string enumValue = EnumMinimumDisambiguation.EnumDisambiguate(valueAsString, resultType);
result = Enum.Parse(resultType, enumValue);
}
catch (Exception e) // Wrap exceptions in type conversion exceptions
{
typeConversion.WriteLine("Substring disambiguation threw an exception.");
throw new PSInvalidCastException("SubstringDisambiguationEnumParseThrewAnException", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
EnumSingleTypeConverter.ThrowForUndefinedEnum("EnumParseUndefined", result, valueToConvert, resultType);
s_tracer.WriteLine("returning \"{0}\" from conversion to Enum.", result);
return result;
}
private static object ConvertEnumerableToEnum(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
IEnumerator e = LanguagePrimitives.GetEnumerator(valueToConvert);
StringBuilder sbResult = new StringBuilder();
bool notFirst = false;
while (ParserOps.MoveNext(null, null, e))
{
if (notFirst)
sbResult.Append(',');
else
notFirst = true;
string current = e.Current as string;
if (current == null)
{
// If the object wasn't a string, then we'll try and convert it into an enum value,
// then convert the enum back to a string and finally append it to the string builder to
// preserve consistent semantics between quoted and unquoted lists...
object tempResult = ConvertTo(e.Current, resultType, recursion, formatProvider, backupTable);
if (tempResult != null)
{
sbResult.Append(tempResult.ToString());
}
else
{
throw new PSInvalidCastException("InvalidCastEnumStringNotFound", null,
ExtendedTypeSystem.InvalidCastExceptionEnumerationNoValue,
e.Current, resultType, EnumSingleTypeConverter.EnumValues(resultType));
}
}
sbResult.Append(current);
}
return ConvertStringToEnum(sbResult.ToString(), resultType, recursion, originalValueToConvert, formatProvider, backupTable);
}
private class ConvertViaParseMethod
{
// TODO - use an ETS wrapper that generates a dynamic method
internal MethodInfo parse;
internal object ConvertWithCulture(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
object result = parse.Invoke(null, new object[2] { valueToConvert, formatProvider });
typeConversion.WriteLine("Parse result: {0}", result);
return result;
}
catch (TargetInvocationException ex)
{
Exception inner = ex.InnerException ?? ex;
typeConversion.WriteLine("Exception calling Parse method with CultureInfo: \"{0}\".", inner.Message);
throw new PSInvalidCastException("InvalidCastParseTargetInvocationWithFormatProvider", inner,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), inner.Message);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception calling Parse method with CultureInfo: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastParseExceptionWithFormatProvider", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
internal object ConvertWithoutCulture(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
object result = parse.Invoke(null, new object[1] { valueToConvert });
typeConversion.WriteLine("Parse result: \"{0}\".", result);
return result;
}
catch (TargetInvocationException ex)
{
Exception inner = ex.InnerException ?? ex;
typeConversion.WriteLine("Exception calling Parse method: \"{0}\".", inner.Message);
throw new PSInvalidCastException("InvalidCastParseTargetInvocation", inner,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), inner.Message);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception calling Parse method: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastParseException", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
}
private class ConvertViaConstructor
{
internal Func<object, object> TargetCtorLambda;
internal object Convert(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
object result = TargetCtorLambda(valueToConvert);
typeConversion.WriteLine("Constructor result: \"{0}\".", result);
return result;
}
catch (TargetInvocationException ex)
{
Exception inner = ex.InnerException ?? ex;
typeConversion.WriteLine("Exception invoking Constructor: \"{0}\".", inner.Message);
throw new PSInvalidCastException("InvalidCastConstructorTargetInvocationException", inner,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), inner.Message);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception invoking Constructor: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastConstructorException", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
}
/// <summary>
/// Create a IList to hold all elements, and use the IList to create the object of the resultType.
/// The reason for using IList is that it can work on constructors that takes IEnumerable[T], ICollection[T] or IList[T].
/// </summary>
/// <remark>
/// When get to this method, we know the fromType and the toType meet the following two conditions:
/// 1. toType is a closed generic type and it has a constructor that takes IEnumerable[T], ICollection[T] or IList[T]
/// 2. fromType is System.Array, System.Object[] or it's the same as the element type of toType
/// </remark>
private class ConvertViaIEnumerableConstructor
{
internal Func<int, IList> ListCtorLambda;
internal Func<IList, object> TargetCtorLambda;
internal Type ElementType;
internal bool IsScalar;
internal object Convert(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
IList resultAsList = null;
Array array = null;
try
{
int listSize = 0;
if (IsScalar)
{
listSize = 1;
}
else
{
// typeof(Array).IsAssignableFrom(typeof(object[])) == true
array = valueToConvert as Array;
listSize = array != null ? array.Length : 1;
}
resultAsList = ListCtorLambda(listSize);
}
catch (Exception)
{
ThrowInvalidCastException(valueToConvert, resultType);
Diagnostics.Assert(false, "ThrowInvalidCastException always throws");
return null;
}
if (IsScalar)
{
resultAsList.Add(valueToConvert);
}
else if (array == null)
{
object convertedValue = LanguagePrimitives.ConvertTo(valueToConvert, ElementType, formatProvider);
resultAsList.Add(convertedValue);
}
else
{
foreach (object item in array)
{
object baseObj = PSObject.Base(item);
object convertedValue;
if (!LanguagePrimitives.TryConvertTo(baseObj, ElementType, formatProvider, out convertedValue))
{
ThrowInvalidCastException(valueToConvert, resultType);
Diagnostics.Assert(false, "ThrowInvalidCastException always throws");
return null;
}
else
{
resultAsList.Add(convertedValue);
}
}
}
try
{
object result = TargetCtorLambda(resultAsList);
typeConversion.WriteLine("IEnumerable Constructor result: \"{0}\".", result);
return result;
}
catch (TargetInvocationException ex)
{
Exception inner = ex.InnerException ?? ex;
typeConversion.WriteLine("Exception invoking IEnumerable Constructor: \"{0}\".", inner.Message);
throw new PSInvalidCastException("InvalidCastConstructorTargetInvocationException", inner,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), inner.Message);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception invoking IEnumerable Constructor: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastConstructorException", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
}
private class ConvertViaNoArgumentConstructor
{
private readonly Func<object> _constructor;
internal ConvertViaNoArgumentConstructor(ConstructorInfo constructor, Type type)
{
var newExpr = (constructor != null) ? Expression.New(constructor) : Expression.New(type);
_constructor = Expression.Lambda<Func<object>>(newExpr.Cast(typeof(object))).Compile();
}
internal object Convert(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return Convert(valueToConvert, resultType, recursion, originalValueToConvert, formatProvider, backupTable, false);
}
internal object Convert(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable, bool ignoreUnknownMembers)
{
try
{
ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS();
object result = null;
if ((ecFromTLS == null) || (ecFromTLS != null && ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage))
{
result = _constructor();
var psobject = valueToConvert as PSObject;
if (psobject != null)
{
// Use PSObject properties to perform conversion.
SetObjectProperties(result, psobject, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, formatProvider, recursion, ignoreUnknownMembers);
}
else
{
// Use provided property dictionary to perform conversion.
// The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2
IDictionary properties = valueToConvert as IDictionary;
SetObjectProperties(result, properties, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: false);
}
typeConversion.WriteLine("Constructor result: \"{0}\".", result);
}
else
{
RuntimeException rte = InterpreterError.NewInterpreterException(valueToConvert, typeof(RuntimeException), null,
"HashtableToObjectConversionNotSupportedInDataSection", ParserStrings.HashtableToObjectConversionNotSupportedInDataSection, resultType.ToString());
throw rte;
}
return result;
}
catch (TargetInvocationException ex)
{
Exception inner = ex.InnerException ?? ex;
typeConversion.WriteLine("Exception invoking Constructor: \"{0}\".", inner.Message);
throw new PSInvalidCastException("InvalidCastConstructorTargetInvocationException", inner,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), inner.Message);
}
catch (InvalidOperationException e)
{
Exception inner = e.InnerException ?? e;
throw new PSInvalidCastException("ObjectCreationError", e,
ExtendedTypeSystem.ObjectCreationError, resultType.ToString(), inner.Message);
}
catch (SetValueException e)
{
Exception inner = e.InnerException ?? e;
throw new PSInvalidCastException("ObjectCreationError", inner,
ExtendedTypeSystem.ObjectCreationError, resultType.ToString(), inner.Message);
}
catch (RuntimeException ex)
{
Exception inner = ex.InnerException ?? ex;
typeConversion.WriteLine("Exception invoking Constructor: \"{0}\".", inner.Message);
throw new PSInvalidCastException("InvalidCastConstructorException", inner,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), inner.Message);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception invoking Constructor: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastConstructorException", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
}
private class ConvertViaCast
{
internal MethodInfo cast;
internal object Convert(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
return cast.Invoke(null, new object[1] { valueToConvert });
}
catch (TargetInvocationException ex)
{
Exception inner = ex.InnerException ?? ex;
typeConversion.WriteLine("Cast operator exception: \"{0}\".", inner.Message);
throw new PSInvalidCastException("InvalidCastTargetInvocationException" + cast.Name, inner,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), inner.Message);
}
catch (Exception e)
{
typeConversion.WriteLine("Cast operator exception: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastException" + cast.Name, e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
}
private static object ConvertIConvertible(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
try
{
object result = Convert.ChangeType(valueToConvert, resultType, formatProvider);
typeConversion.WriteLine("Conversion using IConvertible succeeded.");
return result;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception converting with IConvertible: \"{0}\".", e.Message);
throw new PSInvalidCastException("InvalidCastIConvertible", e,
ExtendedTypeSystem.InvalidCastExceptionWithInnerException,
valueToConvert.ToString(), resultType.ToString(), e.Message);
}
}
private static object ConvertNumericIConvertible(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
// If the original object was a number, then try and do a conversion on the string
// equivalent of that number...
if (originalValueToConvert != null && originalValueToConvert.TokenText != null)
{
return LanguagePrimitives.ConvertTo(originalValueToConvert.TokenText,
resultType, recursion, formatProvider, backupTable);
}
else
{
// Convert the source object to a string...
string s = (string)LanguagePrimitives.ConvertTo(valueToConvert,
typeof(string), recursion, formatProvider, backupTable);
// And try and convert that string to the target type...
return LanguagePrimitives.ConvertTo(s,
resultType, recursion, formatProvider, backupTable);
}
}
private class ConvertCheckingForCustomConverter
{
internal PSConverter<object> tryfirstConverter;
internal PSConverter<object> fallbackConverter;
internal object Convert(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
object result = null;
if (tryfirstConverter != null)
{
try
{
return tryfirstConverter(valueToConvert, resultType, recursion, originalValueToConvert, formatProvider, backupTable);
}
catch (InvalidCastException)
{
}
}
if (IsCustomTypeConversion(originalValueToConvert ?? valueToConvert, resultType, formatProvider, out result, backupTable))
{
typeConversion.WriteLine("Custom Type Conversion succeeded.");
return result;
}
if (fallbackConverter != null)
{
return fallbackConverter(valueToConvert, resultType, recursion, originalValueToConvert, formatProvider, backupTable);
}
throw new PSInvalidCastException("ConvertToFinalInvalidCastException", null,
ExtendedTypeSystem.InvalidCastException,
valueToConvert.ToString(), ObjectToTypeNameString(valueToConvert), resultType.ToString());
}
}
#region Delegates converting null
private static object ConvertNullToNumeric(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting null to zero.");
// If the destination type is numeric, convert 0 to resultType
return System.Convert.ChangeType(0, resultType, CultureInfo.InvariantCulture);
}
private static char ConvertNullToChar(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting null to '0'.");
return '\0';
}
private static string ConvertNullToString(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting null to \"\".");
// if the destination type is string, return an empty string...
return String.Empty;
}
private static PSReference ConvertNullToPSReference(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return new PSReference<Null>(null);
}
private static object ConvertNullToRef(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
// if the target type is not a value type, return the original
// "null" object. Don't just return null because we want to preserve
// an msh object if possible.
return valueToConvert;
}
private static bool ConvertNullToBool(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting null to boolean.");
return false;
}
private static object ConvertNullToNullable(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
return null;
}
private static SwitchParameter ConvertNullToSwitch(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting null to SwitchParameter(false).");
return new SwitchParameter(false);
}
private static object ConvertNullToVoid(object valueToConvert,
Type resultType,
bool recursion,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
typeConversion.WriteLine("Converting null to AutomationNull.Value.");
return AutomationNull.Value;
}
#endregion Delegates converting null
private static object ConvertNoConversion(object valueToConvert,
Type resultType,
bool recurse,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
ThrowInvalidCastException(valueToConvert, resultType);
Diagnostics.Assert(false, "ThrowInvalidCastException always throws");
return null;
}
private static object ConvertNotSupportedConversion(object valueToConvert,
Type resultType,
bool recurse,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable)
{
ThrowInvalidConversionException(valueToConvert, resultType);
Diagnostics.Assert(false, "ThrowInvalidCastException always throws");
return null;
}
private struct ConversionTypePair
{
internal Type from;
internal Type to;
internal ConversionTypePair(Type fromType, Type toType)
{
from = fromType;
to = toType;
}
public override int GetHashCode()
{
unchecked
{
// To prevent to/from == from/to, multiply and add rather than use
// an operation that won't overflow, like bitwise xor.
return from.GetHashCode() + 37 * to.GetHashCode();
}
}
public override bool Equals(object other)
{
if (!(other is ConversionTypePair))
return false;
var ctp = (ConversionTypePair)other;
return this.from == ctp.from && this.to == ctp.to;
}
}
internal delegate T PSConverter<T>(object valueToConvert,
Type resultType,
bool recurse,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable);
internal delegate object PSNullConverter(object nullOrAutomationNull);
internal interface ConversionData
{
object Converter { get; }
ConversionRank Rank { get; }
object Invoke(object valueToConvert,
Type resultType,
bool recurse,
PSObject originalValueToConvert,
IFormatProvider formatProvider,
TypeTable backupTable);
}
internal class ConversionData<T> : ConversionData
{
private readonly PSConverter<T> _converter;
public ConversionData(PSConverter<T> converter, ConversionRank rank)
{
_converter = converter;
Rank = rank;
}
public object Converter
{
get { return _converter; }
}
public ConversionRank Rank { get; }
public object Invoke(object valueToConvert, Type resultType, bool recurse, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
{
return _converter.Invoke(valueToConvert, resultType, recurse, originalValueToConvert, formatProvider, backupTable);
}
}
private static Dictionary<ConversionTypePair, ConversionData> s_converterCache
= new Dictionary<ConversionTypePair, ConversionData>(256);
private static ConversionData CacheConversion<T>(Type fromType, Type toType, PSConverter<T> converter, ConversionRank rank)
{
ConversionTypePair pair = new ConversionTypePair(fromType, toType);
ConversionData data = null;
lock (s_converterCache)
{
if (!s_converterCache.TryGetValue(pair, out data))
{
data = new ConversionData<T>(converter, rank);
s_converterCache.Add(pair, data);
}
else
{
Dbg.Assert(((Delegate)(data.Converter)).GetMethodInfo().Equals(converter.GetMethodInfo()),
"Existing conversion isn't the same as new conversion");
}
}
return data;
}
private static ConversionData GetConversionData(Type fromType, Type toType)
{
lock (s_converterCache)
{
ConversionData result = null;
s_converterCache.TryGetValue(new ConversionTypePair(fromType, toType), out result);
return result;
}
}
internal static ConversionRank GetConversionRank(Type fromType, Type toType)
{
return FigureConversion(fromType, toType).Rank;
}
private static Type[] s_numericTypes = new Type[] {
typeof(Int16), typeof(Int32), typeof(Int64),
typeof(UInt16), typeof(UInt32), typeof(UInt64),
typeof(SByte), typeof(Byte),
typeof(Single), typeof(Double), typeof(Decimal)
};
private static Type[] s_integerTypes = new Type[] {
typeof(Int16), typeof(Int32), typeof(Int64),
typeof(UInt16), typeof(UInt32), typeof(UInt64),
typeof(SByte), typeof(Byte)
};
// Do not reorder the elements of these arrays, we depend on them being ordered by increasing size.
private static Type[] s_signedIntegerTypes = new Type[] { typeof(SByte), typeof(Int16), typeof(Int32), typeof(Int64) };
private static Type[] s_unsignedIntegerTypes = new Type[] { typeof(Byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) };
private static Type[] s_realTypes = new Type[] { typeof(Single), typeof(Double), typeof(Decimal) };
internal static void RebuildConversionCache()
{
lock (s_converterCache)
{
s_converterCache.Clear();
Type typeofString = typeof(string);
Type typeofNull = typeof(Null);
Type typeofFloat = typeof(float);
Type typeofDouble = typeof(double);
Type typeofDecimal = typeof(Decimal);
Type typeofBool = typeof(bool);
Type typeofChar = typeof(char);
foreach (Type type in LanguagePrimitives.s_numericTypes)
{
CacheConversion<string>(type, typeofString, LanguagePrimitives.ConvertNumericToString, ConversionRank.NumericString);
CacheConversion<object>(type, typeofChar, LanguagePrimitives.ConvertIConvertible, ConversionRank.NumericString);
CacheConversion<object>(typeofNull, type, LanguagePrimitives.ConvertNullToNumeric, ConversionRank.NullToValue);
}
CacheConversion<bool>(typeof(Int16), typeofBool, ConvertInt16ToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(Int32), typeofBool, ConvertInt32ToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(Int64), typeofBool, ConvertInt64ToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(UInt16), typeofBool, ConvertUInt16ToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(UInt32), typeofBool, ConvertUInt32ToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(UInt64), typeofBool, ConvertUInt64ToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(SByte), typeofBool, ConvertSByteToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(Byte), typeofBool, ConvertByteToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(Single), typeofBool, ConvertSingleToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(Double), typeofBool, ConvertDoubleToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(Decimal), typeofBool, ConvertDecimalToBool, ConversionRank.Language);
for (int i = 0; i < LanguagePrimitives.s_unsignedIntegerTypes.Length; i++)
{
// Identical types are an identity conversion.
CacheConversion<object>(s_unsignedIntegerTypes[i], s_unsignedIntegerTypes[i],
LanguagePrimitives.ConvertAssignableFrom, ConversionRank.Identity);
CacheConversion<object>(s_signedIntegerTypes[i], s_signedIntegerTypes[i],
LanguagePrimitives.ConvertAssignableFrom, ConversionRank.Identity);
// Unsigned to signed same size is explicit
CacheConversion<object>(s_unsignedIntegerTypes[i], s_signedIntegerTypes[i],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
// Signed to unsigned same size is explicit, but better than the reverse (because it is "more specific")
CacheConversion<object>(s_signedIntegerTypes[i], s_unsignedIntegerTypes[i],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit1);
for (int j = i + 1; j < LanguagePrimitives.s_unsignedIntegerTypes.Length; j++)
{
// Conversions where the sign doesn't change, but the size is bigger, is implicit
CacheConversion<object>(s_unsignedIntegerTypes[i], s_unsignedIntegerTypes[j],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit);
CacheConversion<object>(s_signedIntegerTypes[i], s_signedIntegerTypes[j],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit);
// Conversion from smaller unsigned to bigger signed is implicit
CacheConversion<object>(s_unsignedIntegerTypes[i], s_signedIntegerTypes[j],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit);
// Conversion from smaller signed to bigger unsigned is the "better" explicit conversion
CacheConversion<object>(s_signedIntegerTypes[i], s_unsignedIntegerTypes[j],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit1);
// Conversion to a smaller type is explicit
CacheConversion<object>(s_unsignedIntegerTypes[j], s_unsignedIntegerTypes[i],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
CacheConversion<object>(s_signedIntegerTypes[j], s_signedIntegerTypes[i],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
CacheConversion<object>(s_unsignedIntegerTypes[j], s_signedIntegerTypes[i],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
CacheConversion<object>(s_signedIntegerTypes[j], s_unsignedIntegerTypes[i],
LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
}
}
foreach (Type integerType in s_integerTypes)
{
CacheConversion<object>(typeofString, integerType, LanguagePrimitives.ConvertStringToInteger, ConversionRank.NumericString);
foreach (Type realType in s_realTypes)
{
CacheConversion<object>(integerType, realType, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit);
CacheConversion<object>(realType, integerType, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
}
}
CacheConversion<object>(typeofFloat, typeofDouble, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericImplicit);
CacheConversion<object>(typeofDouble, typeofFloat, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
CacheConversion<object>(typeofFloat, typeofDecimal, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
CacheConversion<object>(typeofDouble, typeofDecimal, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit);
CacheConversion<object>(typeofDecimal, typeofFloat, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit1);
CacheConversion<object>(typeofDecimal, typeofDouble, LanguagePrimitives.ConvertNumeric, ConversionRank.NumericExplicit1);
CacheConversion<Regex>(typeofString, typeof(Regex), LanguagePrimitives.ConvertStringToRegex, ConversionRank.Language);
CacheConversion<char[]>(typeofString, typeof(char[]), LanguagePrimitives.ConvertStringToCharArray, ConversionRank.StringToCharArray);
CacheConversion<Type>(typeofString, typeof(Type), LanguagePrimitives.ConvertStringToType, ConversionRank.Language);
CacheConversion<Uri>(typeofString, typeof(Uri), LanguagePrimitives.ConvertStringToUri, ConversionRank.Language);
CacheConversion<object>(typeofString, typeofDecimal, LanguagePrimitives.ConvertStringToDecimal, ConversionRank.NumericString);
CacheConversion<object>(typeofString, typeofFloat, LanguagePrimitives.ConvertStringToReal, ConversionRank.NumericString);
CacheConversion<object>(typeofString, typeofDouble, LanguagePrimitives.ConvertStringToReal, ConversionRank.NumericString);
CacheConversion<object>(typeofChar, typeofFloat, LanguagePrimitives.ConvertNumericChar, ConversionRank.Language);
CacheConversion<object>(typeofChar, typeofDouble, LanguagePrimitives.ConvertNumericChar, ConversionRank.Language);
CacheConversion<bool>(typeofChar, typeofBool, LanguagePrimitives.ConvertCharToBool, ConversionRank.Language);
// Conversions from null
CacheConversion<char>(typeofNull, typeofChar, LanguagePrimitives.ConvertNullToChar, ConversionRank.NullToValue);
CacheConversion<string>(typeofNull, typeofString, LanguagePrimitives.ConvertNullToString, ConversionRank.ToString);
CacheConversion<bool>(typeofNull, typeofBool, LanguagePrimitives.ConvertNullToBool, ConversionRank.NullToValue);
CacheConversion<PSReference>(typeofNull, typeof(PSReference), LanguagePrimitives.ConvertNullToPSReference, ConversionRank.NullToRef);
CacheConversion<SwitchParameter>(typeofNull, typeof(SwitchParameter), LanguagePrimitives.ConvertNullToSwitch, ConversionRank.NullToValue);
CacheConversion<object>(typeofNull, typeof(void), LanguagePrimitives.ConvertNullToVoid, ConversionRank.NullToValue);
// Conversions to bool
CacheConversion<object>(typeofBool, typeofBool, LanguagePrimitives.ConvertAssignableFrom, ConversionRank.Identity);
CacheConversion<bool>(typeofString, typeofBool, LanguagePrimitives.ConvertStringToBool, ConversionRank.Language);
CacheConversion<bool>(typeof(SwitchParameter), typeofBool, LanguagePrimitives.ConvertSwitchParameterToBool, ConversionRank.Language);
#if !CORECLR // No DirectoryService && WMIv1 In CoreCLR
CacheConversion<ManagementObjectSearcher>(typeofString, typeof(ManagementObjectSearcher), LanguagePrimitives.ConvertToWMISearcher, ConversionRank.Language);
CacheConversion<ManagementClass>(typeofString, typeof(ManagementClass), LanguagePrimitives.ConvertToWMIClass, ConversionRank.Language);
CacheConversion<ManagementObject>(typeofString, typeof(ManagementObject), LanguagePrimitives.ConvertToWMI, ConversionRank.Language);
CacheConversion<DirectoryEntry>(typeofString, typeof(DirectoryEntry), LanguagePrimitives.ConvertToADSI, ConversionRank.Language);
CacheConversion<DirectorySearcher>(typeofString, typeof(DirectorySearcher), LanguagePrimitives.ConvertToADSISearcher, ConversionRank.Language);
#endif
}
}
internal static PSObject SetObjectProperties(object o, PSObject psObject, Type resultType, MemberNotFoundError memberNotFoundErrorAction, MemberSetValueError memberSetValueErrorAction, IFormatProvider formatProvider, bool recursion = false, bool ignoreUnknownMembers = false)
{
// Type conversion from object properties only supported for deserialized types.
if (Deserializer.IsDeserializedInstanceOfType(psObject, resultType))
{
try
{
Dictionary<string, object> properties = new Dictionary<string, object>();
foreach (var item in psObject.Properties)
{
if (item is PSProperty)
{
properties.Add(item.Name, item.Value);
}
}
// Win8:649519
return SetObjectProperties(o, properties, resultType, memberNotFoundErrorAction, memberSetValueErrorAction, enableMethodCall: false);
}
catch (SetValueException)
{ }
catch (InvalidOperationException)
{ }
}
else
{
object baseObj = PSObject.Base(psObject);
var dictionary = baseObj as IDictionary;
if (dictionary != null)
{
// Win8:649519
return SetObjectProperties(o, dictionary, resultType, memberNotFoundErrorAction, memberSetValueErrorAction, enableMethodCall: false);
}
else
{
// Support PSObject to Strong type conversion.
PSObject psBaseObject = baseObj as PSObject;
if (psBaseObject != null)
{
Dictionary<string, object> properties = new Dictionary<string, object>();
foreach (var item in psBaseObject.Properties)
{
properties.Add(item.Name, item.Value);
}
try
{
return SetObjectProperties(o, properties, resultType, memberNotFoundErrorAction, memberSetValueErrorAction, false, formatProvider, recursion, ignoreUnknownMembers);
}
catch (InvalidOperationException exception)
{
throw new PSInvalidCastException("ConvertToFinalInvalidCastException", exception,
ExtendedTypeSystem.InvalidCastException,
psObject.ToString(), ObjectToTypeNameString(psObject),
resultType.ToString());
}
}
}
}
ThrowInvalidCastException(psObject, resultType);
return null;
}
internal static PSObject SetObjectProperties(object o, IDictionary properties, Type resultType, MemberNotFoundError memberNotFoundErrorAction, MemberSetValueError memberSetValueErrorAction, bool enableMethodCall)
{
return SetObjectProperties(o, properties, resultType, memberNotFoundErrorAction, memberSetValueErrorAction, enableMethodCall, CultureInfo.InvariantCulture, false, false);
}
internal static PSObject SetObjectProperties(object o, IDictionary properties, Type resultType, MemberNotFoundError memberNotFoundErrorAction, MemberSetValueError memberSetValueErrorAction, bool enableMethodCall, IFormatProvider formatProvider, bool recursion = false, bool ignoreUnknownMembers = false)
{
PSObject pso = PSObject.AsPSObject(o);
if (properties != null)
{
foreach (DictionaryEntry prop in properties)
{
PSMethodInfo method = enableMethodCall ? pso.Methods[prop.Key.ToString()] : null;
try
{
if (method != null)
{
method.Invoke(new object[] { prop.Value });
}
else
{
PSPropertyInfo property = pso.Properties[prop.Key.ToString()];
if (property != null)
{
object propValue = prop.Value;
if (recursion && prop.Value != null)
{
Type propType;
if (TypeResolver.TryResolveType(property.TypeNameOfValue, out propType))
{
if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; }
try
{
PSObject propertyValue = prop.Value as PSObject;
if (propertyValue != null)
{
propValue = LanguagePrimitives.ConvertPSObjectToType(propertyValue, propType, recursion, formatProvider, ignoreUnknownMembers);
}
else if (prop.Value is PSCustomObject)
{
propValue = LanguagePrimitives.ConvertPSObjectToType(new PSObject(prop.Value), propType, recursion, formatProvider, ignoreUnknownMembers);
}
else
{
propValue = LanguagePrimitives.ConvertTo(prop.Value, propType, recursion, formatProvider, null);
}
}
catch (SetValueException)
{
// We don't care. We will assign the value as is.
}
}
}
property.Value = propValue;
}
else
{
if (pso.BaseObject is PSCustomObject)
{
var key = prop.Key as string;
var value = prop.Value as string;
if (key != null && value != null && key.Equals("PSTypeName", StringComparison.OrdinalIgnoreCase))
{
pso.TypeNames.Insert(0, value);
}
else
{
pso.Properties.Add(new PSNoteProperty(prop.Key.ToString(), prop.Value));
}
}
else
{
if (!ignoreUnknownMembers)
{
memberNotFoundErrorAction(pso, prop, resultType);
}
}
}
}
}
catch (SetValueException e)
{
memberSetValueErrorAction(e);
}
}
}
return pso;
}
private static String GetAvailableProperties(PSObject pso)
{
StringBuilder availableProperties = new StringBuilder();
bool first = true;
if (pso != null && pso.Properties != null)
{
foreach (PSPropertyInfo p in pso.Properties)
{
if (first == false)
{
availableProperties.Append(" , ");
}
availableProperties.Append("[" + p.Name + " <" + p.TypeNameOfValue + ">]");
if (first == true)
{
first = false;
}
}
}
return availableProperties.ToString();
}
internal static ConversionData FigureConversion(object valueToConvert, Type resultType, out bool debase)
{
PSObject valueAsPsObj;
Type originalType;
if (valueToConvert == null || valueToConvert == AutomationNull.Value)
{
valueAsPsObj = null;
originalType = typeof(Null);
}
else
{
valueAsPsObj = valueToConvert as PSObject;
originalType = valueToConvert.GetType();
}
debase = false;
ConversionData data = FigureConversion(originalType, resultType);
if (data.Rank != ConversionRank.None)
{
return data;
}
if (valueAsPsObj != null)
{
debase = true;
// Now try converting PSObject.Base instead.
valueToConvert = PSObject.Base(valueToConvert);
Dbg.Assert(valueToConvert != AutomationNull.Value, "PSObject.Base converts AutomationNull.Value to null");
if (valueToConvert == null)
{
originalType = typeof(Null);
}
else
{
// If the original value was a property bag (empty PSObject), we won't find a conversion because
// all PSObject conversions have already been checked.
//
// Still, there are many valid conversions to allow, such as PSObject to bool, void, or
// a custom type converter. To find those, we consider InternalPSObject=>resultType instead.
//
// We use a different type because we can't keep PSObject as the from type in the cache.
originalType = (valueToConvert is PSObject) ? typeof(InternalPSObject) : valueToConvert.GetType();
}
data = FigureConversion(originalType, resultType);
}
return data;
}
/// <summary>
///
/// </summary>
/// <param name="valueToConvert">the same as in the public version</param>
/// <param name="resultType">the same as in the public version</param>
/// <param name="recursion">true if we should perform any recursive calls to ConvertTo</param>
/// <param name="formatProvider">governing conversion of types</param>
/// <param name="backupTypeTable">
/// Used by Remoting Rehydration Logic. While Deserializing a remote object,
/// LocalPipeline.ExecutionContextFromTLS() might return null..In which case this
/// TypeTable will be used to do the conversion.
/// </param>
/// <returns>the value converted</returns>
/// <exception cref="ArgumentNullException">if resultType is null</exception>
/// <exception cref="PSInvalidCastException">if the conversion failed</exception>
internal static object ConvertTo(object valueToConvert,
Type resultType,
bool recursion,
IFormatProvider formatProvider,
TypeTable backupTypeTable)
{
using (typeConversion.TraceScope("Converting \"{0}\" to \"{1}\".", valueToConvert, resultType))
{
if (resultType == null)
{
throw PSTraceSource.NewArgumentNullException("resultType");
}
bool debase;
var conversion = FigureConversion(valueToConvert, resultType, out debase);
return conversion.Invoke(debase ? PSObject.Base(valueToConvert) : valueToConvert,
resultType, recursion, debase ? (PSObject)valueToConvert : null,
formatProvider, backupTypeTable);
}
}
/// <summary>
/// Get the errorId and errorMessage for an InvalidCastException
/// </summary>
/// <param name="valueToConvert"></param>
/// <param name="resultType"></param>
/// <returns>
/// A two-element tuple indicating [errorId, errorMsg]
/// </returns>
internal static Tuple<string, string> GetInvalidCastMessages(object valueToConvert, Type resultType)
{
string errorId, errorMsg;
if (PSObject.Base(valueToConvert) == null)
{
if (resultType.GetTypeInfo().IsEnum)
{
typeConversion.WriteLine("Issuing an error message about not being able to convert null to an Enum type.");
// a nice error message specifically for null being converted to enum
errorId = "nullToEnumInvalidCast";
errorMsg = StringUtil.Format(ExtendedTypeSystem.InvalidCastExceptionEnumerationNull, resultType,
EnumSingleTypeConverter.EnumValues(resultType));
return Tuple.Create(errorId, errorMsg);
}
typeConversion.WriteLine("Cannot convert null.");
// finally throw of all other value types...
errorId = "nullToObjectInvalidCast";
errorMsg = StringUtil.Format(ExtendedTypeSystem.InvalidCastFromNull, resultType.ToString());
return Tuple.Create(errorId, errorMsg);
}
typeConversion.WriteLine("Type Conversion failed.");
errorId = "ConvertToFinalInvalidCastException";
errorMsg = StringUtil.Format(ExtendedTypeSystem.InvalidCastException, valueToConvert.ToString(),
ObjectToTypeNameString(valueToConvert), resultType.ToString());
return Tuple.Create(errorId, errorMsg);
}
// Even though this never returns, expression trees expect non-void values in places, and so it's easier
// to claim it returns object than to add extra expressions to keep the trees type safe.
internal static object ThrowInvalidCastException(object valueToConvert, Type resultType)
{
// Get exception messages (in order): errorId, errorMsg
var errorMsgTuple = GetInvalidCastMessages(valueToConvert, resultType);
throw new PSInvalidCastException(errorMsgTuple.Item1, errorMsgTuple.Item2, innerException: null);
}
// Even though this never returns, expression trees expect non-void values in places, and so it's easier
// to claim it returns object than to add extra expressions to keep the trees type safe.
internal static object ThrowInvalidConversionException(object valueToConvert, Type resultType)
{
typeConversion.WriteLine("Issuing an error message about not being able to convert to non-core type.");
throw new PSInvalidCastException("ConversionSupportedOnlyToCoreTypes", null, ExtendedTypeSystem.InvalidCastExceptionNonCoreType, resultType.ToString());
}
private static ConversionData FigureLanguageConversion(Type fromType, Type toType,
out PSConverter<object> valueDependentConversion,
out ConversionRank valueDependentRank)
{
valueDependentConversion = null;
valueDependentRank = ConversionRank.None;
Type underlyingType = Nullable.GetUnderlyingType(toType);
if (underlyingType != null)
{
ConversionData nullableConversion = FigureConversion(fromType, underlyingType);
if (nullableConversion.Rank != ConversionRank.None)
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertToNullable, nullableConversion.Rank);
}
}
if (toType == typeof(void))
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertToVoid, ConversionRank.Language);
}
if (toType == typeof(bool))
{
PSConverter<bool> converter;
if (typeof(IList).IsAssignableFrom(fromType))
{
converter = LanguagePrimitives.ConvertIListToBool;
}
else if (fromType.GetTypeInfo().IsEnum)
{
converter = LanguagePrimitives.CreateNumericToBoolConverter(fromType);
}
else if (fromType.GetTypeInfo().IsValueType)
{
converter = LanguagePrimitives.ConvertValueToBool;
}
else
{
converter = LanguagePrimitives.ConvertClassToBool;
}
return CacheConversion<bool>(fromType, toType, converter, ConversionRank.Language);
}
if (toType == typeof(string))
{
Dbg.Assert(!LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(fromType)) || fromType.GetTypeInfo().IsEnum,
"Number to string should be cached on initialization of cache table");
return CacheConversion<string>(fromType, toType, LanguagePrimitives.ConvertNonNumericToString, ConversionRank.ToString);
}
if (toType.IsArray)
{
Type toElementType = toType.GetElementType();
if (fromType.IsArray)
{
if (toElementType.IsAssignableFrom(fromType.GetElementType()))
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertRelatedArrays, ConversionRank.Language);
}
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertUnrelatedArrays, ConversionRank.UnrelatedArrays);
}
if (LanguagePrimitives.IsTypeEnumerable(fromType))
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertEnumerableToArray, ConversionRank.Language);
}
ConversionData data = FigureConversion(fromType, toElementType);
if (data.Rank != ConversionRank.None)
{
valueDependentRank = data.Rank & ConversionRank.ValueDependent;
valueDependentConversion = LanguagePrimitives.ConvertScalarToArray;
return null;
}
}
if (toType == typeof(Array))
{
if (fromType.IsArray || fromType == typeof(Array))
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertAssignableFrom, ConversionRank.Assignable);
}
if (LanguagePrimitives.IsTypeEnumerable(fromType))
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertEnumerableToArray, ConversionRank.Language);
}
valueDependentRank = ConversionRank.Assignable & ConversionRank.ValueDependent;
valueDependentConversion = LanguagePrimitives.ConvertScalarToArray;
return null;
}
if (toType == typeof(Hashtable))
{
if (typeof(IDictionary).IsAssignableFrom(fromType))
{
return CacheConversion<Hashtable>(fromType, toType, LanguagePrimitives.ConvertIDictionaryToHashtable, ConversionRank.Language);
}
else
{
return null;
}
}
if (toType == typeof(PSReference))
{
return CacheConversion<PSReference>(fromType, toType, LanguagePrimitives.ConvertToPSReference, ConversionRank.Language);
}
if (toType == typeof(XmlDocument))
{
return CacheConversion<XmlDocument>(fromType, toType, LanguagePrimitives.ConvertToXml, ConversionRank.Language);
}
if (toType == typeof(StringCollection))
{
ConversionRank rank = (fromType.IsArray || IsTypeEnumerable(fromType)) ? ConversionRank.Language : ConversionRank.LanguageS2A;
return CacheConversion<StringCollection>(fromType, toType, LanguagePrimitives.ConvertToStringCollection, rank);
}
#if !CORECLR // No CommaDelimitedStringCollection In CoreCLR
if (toType == typeof(System.Configuration.CommaDelimitedStringCollection))
{
ConversionRank rank = (fromType.IsArray || IsTypeEnumerable(fromType)) ? ConversionRank.Language : ConversionRank.LanguageS2A;
return CacheConversion<System.Configuration.CommaDelimitedStringCollection>(fromType, toType, LanguagePrimitives.ConvertToCommaDelimitedStringCollection, rank);
}
#endif
if (toType.IsSubclassOf(typeof(System.Delegate))
&& (fromType == typeof(ScriptBlock) || fromType.IsSubclassOf(typeof(ScriptBlock))))
{
return CacheConversion<Delegate>(fromType, toType, LanguagePrimitives.ConvertScriptBlockToDelegate, ConversionRank.Language);
}
if (toType == typeof(InternalPSCustomObject))
{
Type actualResultType = typeof(PSObject);
ConstructorInfo resultConstructor = actualResultType.GetConstructor(PSTypeExtensions.EmptyTypes);
var converterObj = new ConvertViaNoArgumentConstructor(resultConstructor, actualResultType);
return CacheConversion(fromType, toType, converterObj.Convert, ConversionRank.Language);
}
TypeCode fromTypeCode = LanguagePrimitives.GetTypeCode(fromType);
if (LanguagePrimitives.IsInteger(fromTypeCode) && toType.GetTypeInfo().IsEnum)
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertIntegerToEnum, ConversionRank.Language);
}
return null;
}
private static PSConverter<object> FigureStaticCreateMethodConversion(Type fromType, Type toType)
{
// after discussing this with Jason, we decided that for now we only want to support string->CimSession conversion
// and we don't want to add a Parse-like conversion based on a static Create method
if (fromType == typeof(string) && toType == typeof(Microsoft.Management.Infrastructure.CimSession))
{
return LanguagePrimitives.ConvertStringToCimSession;
}
return null;
}
private static PSConverter<object> FigureParseConversion(Type fromType, Type toType)
{
if (toType.GetTypeInfo().IsEnum)
{
if (fromType == typeof(string))
{
return LanguagePrimitives.ConvertStringToEnum;
}
if (LanguagePrimitives.IsTypeEnumerable(fromType))
{
return LanguagePrimitives.ConvertEnumerableToEnum;
}
}
else if (fromType == typeof(string))
{
const BindingFlags parseFlags = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static;
// GetMethod could throw for more than one match, for instance
MethodInfo parse = null;
try
{
parse = toType.GetMethod("Parse", parseFlags, null, new Type[2] { typeof(string), typeof(IFormatProvider) }, null);
}
catch (AmbiguousMatchException e)
{
typeConversion.WriteLine("Exception finding Parse method with CultureInfo: \"{0}\".", e.Message);
}
catch (ArgumentException e)
{
typeConversion.WriteLine("Exception finding Parse method with CultureInfo: \"{0}\".", e.Message);
}
if (parse != null)
{
ConvertViaParseMethod converter = new ConvertViaParseMethod();
converter.parse = parse;
return converter.ConvertWithCulture;
}
try
{
parse = toType.GetMethod("Parse", parseFlags, null, new Type[1] { typeof(string) }, null);
}
catch (AmbiguousMatchException e)
{
typeConversion.WriteLine("Exception finding Parse method: \"{0}\".", e.Message);
}
catch (ArgumentException e)
{
typeConversion.WriteLine("Exception finding Parse method: \"{0}\".", e.Message);
}
if (parse != null)
{
ConvertViaParseMethod converter = new ConvertViaParseMethod();
converter.parse = parse;
return converter.ConvertWithoutCulture;
}
}
return null;
}
/// <summary>
/// Figure conversion when following conditions are satisfied:
/// 1. toType is a closed generic type and it has a constructor that takes IEnumerable[T], ICollection[T] or IList[T]
/// 2. fromType is System.Array, System.Object[] or it's the same as the element type of toType
/// </summary>
/// <param name="fromType"></param>
/// <param name="toType"></param>
/// <returns></returns>
internal static Tuple<PSConverter<object>, ConversionRank> FigureIEnumerableConstructorConversion(Type fromType, Type toType)
{
// Win8: 653180. If toType is an Abstract type then we cannot construct it anyway. So, bailing out fast.
TypeInfo toTypeInfo = toType.GetTypeInfo();
if (toTypeInfo.IsAbstract == true)
{
return null;
}
try
{
bool result = false;
bool isScalar = false;
Type elementType = null;
ConstructorInfo resultConstructor = null;
if (toTypeInfo.IsGenericType && !toTypeInfo.ContainsGenericParameters &&
(typeof(IList).IsAssignableFrom(toType) ||
typeof(ICollection).IsAssignableFrom(toType) ||
typeof(IEnumerable).IsAssignableFrom(toType)))
{
Type[] argTypes = toType.GetGenericArguments();
if (argTypes.Length != 1)
{
typeConversion
.WriteLine(
"toType has more than one generic arguments. Here we only care about the toType which contains only one generic argument and whose constructor takes IEnumerable<T>, ICollection<T> or IList<T>.");
return null;
}
elementType = argTypes[0];
if (typeof(Array) == fromType || typeof(object[]) == fromType ||
elementType.IsAssignableFrom(fromType) ||
// WinBlue: 423899 : To support scenario like [list[int]]"4"
(FigureConversion(fromType, elementType) != null))
{
isScalar = elementType.IsAssignableFrom(fromType);
ConstructorInfo[] ctors = toType.GetConstructors();
Type iEnumerableClosedType = typeof(IEnumerable<>).MakeGenericType(elementType);
Type iCollectionClosedType = typeof(ICollection<>).MakeGenericType(elementType);
Type iListClosedType = typeof(IList<>).MakeGenericType(elementType);
foreach (var ctor in ctors)
{
ParameterInfo[] param = ctor.GetParameters();
if (param.Length != 1)
continue;
Type paramType = param[0].ParameterType;
if (iEnumerableClosedType == paramType ||
iCollectionClosedType == paramType ||
iListClosedType == paramType)
{
resultConstructor = ctor;
result = true;
break;
}
}
}
}
if (result)
{
var converter = new ConvertViaIEnumerableConstructor();
try
{
Type listClosedType = typeof(List<>).MakeGenericType(elementType);
ConstructorInfo listCtor = listClosedType.GetConstructor(new Type[] { typeof(int) });
converter.ListCtorLambda = CreateCtorLambdaClosure<int, IList>(listCtor, typeof(int), false);
ParameterInfo[] targetParams = resultConstructor.GetParameters();
Type targetParamType = targetParams[0].ParameterType;
converter.TargetCtorLambda = CreateCtorLambdaClosure<IList, object>(resultConstructor,
targetParamType, false);
converter.ElementType = elementType;
converter.IsScalar = isScalar;
}
catch (Exception e)
{
typeConversion.WriteLine("Exception building constructor lambda: \"{0}\"", e.Message);
return null;
}
ConversionRank rank = isScalar ? ConversionRank.ConstructorS2A : ConversionRank.Constructor;
typeConversion.WriteLine("Conversion is figured out. Conversion rank: \"{0}\"", rank);
return new Tuple<PSConverter<object>, ConversionRank>(converter.Convert, rank);
}
else
{
typeConversion.WriteLine("Fail to figure out the conversion from \"{0}\" to \"{1}\"",
fromType.FullName, toType.FullName);
return null;
}
}
catch (ArgumentException ae)
{
typeConversion.WriteLine("Exception finding IEnumerable conversion: \"{0}\".", ae.Message);
}
catch (InvalidOperationException ie)
{
typeConversion.WriteLine("Exception finding IEnumerable conversion: \"{0}\".", ie.Message);
}
catch (NotSupportedException ne)
{
typeConversion.WriteLine("Exception finding IEnumerable conversion: \"{0}\".", ne.Message);
}
return null;
}
private static Func<T1, T2> CreateCtorLambdaClosure<T1, T2>(ConstructorInfo ctor, Type realParamType, bool useExplicitConversion)
{
ParameterExpression paramExpr = Expression.Parameter(typeof(T1), "args");
Expression castParamExpr = useExplicitConversion
? (Expression)Expression.Call(CachedReflectionInfo.Convert_ChangeType, paramExpr, Expression.Constant(realParamType, typeof(Type)))
: Expression.Convert(paramExpr, realParamType);
NewExpression ctorExpr = Expression.New(ctor, castParamExpr.Cast(realParamType));
return Expression.Lambda<Func<T1, T2>>(ctorExpr.Cast(typeof(T2)), paramExpr).Compile();
}
internal static PSConverter<object> FigureConstructorConversion(Type fromType, Type toType)
{
if (IsIntegralType(fromType) &&
(typeof(IList).IsAssignableFrom(toType) || typeof(ICollection).IsAssignableFrom(toType)))
{
typeConversion.WriteLine("Ignoring the collection constructor that takes an integer, since this is not semantically a conversion.");
return null;
}
ConstructorInfo resultConstructor = null;
try
{
resultConstructor = toType.GetConstructor(new Type[] { fromType });
}
catch (AmbiguousMatchException e)
{
typeConversion.WriteLine("Exception finding Constructor: \"{0}\".", e.Message);
}
catch (ArgumentException e)
{
typeConversion.WriteLine("Exception finding Constructor: \"{0}\".", e.Message);
}
if (resultConstructor == null)
{
return null;
}
typeConversion.WriteLine("Found Constructor.");
var converter = new ConvertViaConstructor();
try
{
ParameterInfo[] targetParams = resultConstructor.GetParameters();
Type targetParamType = targetParams[0].ParameterType;
bool useExplicitConversion = targetParamType.GetTypeInfo().IsValueType && fromType != targetParamType && Nullable.GetUnderlyingType(targetParamType) == null;
converter.TargetCtorLambda = CreateCtorLambdaClosure<object, object>(resultConstructor, targetParamType, useExplicitConversion);
}
catch (Exception e)
{
typeConversion.WriteLine("Exception building constructor lambda: \"{0}\"", e.Message);
return null;
}
typeConversion.WriteLine("Conversion is figured out.");
return converter.Convert;
}
private static bool IsIntegralType(Type type)
{
return
type == typeof(sbyte) ||
type == typeof(byte) ||
type == typeof(short) ||
type == typeof(ushort) ||
type == typeof(int) ||
type == typeof(uint) ||
type == typeof(long) ||
type == typeof(ulong);
}
internal static PSConverter<object> FigurePropertyConversion(Type fromType, Type toType, ref ConversionRank rank)
{
TypeInfo toTypeInfo = toType.GetTypeInfo();
if ((!typeof(PSObject).IsAssignableFrom(fromType)) || (toTypeInfo.IsAbstract))
{
return null;
}
ConstructorInfo toConstructor = null;
try
{
toConstructor = toType.GetConstructor(PSTypeExtensions.EmptyTypes);
}
catch (AmbiguousMatchException e)
{
typeConversion.WriteLine("Exception finding Constructor: \"{0}\".", e.Message);
}
catch (ArgumentException e)
{
typeConversion.WriteLine("Exception finding Constructor: \"{0}\".", e.Message);
}
if (toConstructor == null && !toTypeInfo.IsValueType)
{
return null;
}
if (toType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Length == 0 &&
toType.GetFields(BindingFlags.Public | BindingFlags.Instance).Length == 0)
{
// fromType is PSObject, toType has no properties/fields to set, so conversion should fail.
return null;
}
typeConversion.WriteLine("Found Constructor.");
try
{
ConvertViaNoArgumentConstructor noArgumentConstructorConverter =
new ConvertViaNoArgumentConstructor(toConstructor, toType);
rank = ConversionRank.Constructor;
return noArgumentConstructorConverter.Convert;
}
catch (ArgumentException ae)
{
typeConversion.WriteLine("Exception converting via no argument constructor: \"{0}\".", ae.Message);
}
catch (InvalidOperationException ie)
{
typeConversion.WriteLine("Exception converting via no argument constructor: \"{0}\".", ie.Message);
}
rank = ConversionRank.None;
return null;
}
internal static PSConverter<object> FigureCastConversion(Type fromType, Type toType, ref ConversionRank rank)
{
MethodInfo castOperator = FindCastOperator("op_Implicit", toType, fromType, toType);
if (castOperator == null)
{
castOperator = FindCastOperator("op_Explicit", toType, fromType, toType);
if (castOperator == null)
{
castOperator = FindCastOperator("op_Implicit", fromType, fromType, toType) ??
FindCastOperator("op_Explicit", fromType, fromType, toType);
}
}
if (castOperator != null)
{
rank = castOperator.Name.Equals("op_Implicit", StringComparison.OrdinalIgnoreCase)
? ConversionRank.ImplicitCast : ConversionRank.ExplicitCast;
ConvertViaCast converter = new ConvertViaCast();
converter.cast = castOperator;
return converter.Convert;
}
return null;
}
private static bool TypeConverterPossiblyExists(Type type)
{
lock (s_possibleTypeConverter)
{
if (s_possibleTypeConverter.ContainsKey(type.FullName))
{
return true;
}
}
// GetCustomAttributes returns IEnumerable<Attribute> in CoreCLR
var typeConverters = type.GetTypeInfo().GetCustomAttributes(typeof(TypeConverterAttribute), false);
if (typeConverters.Any())
{
return true;
}
return false;
}
private static Dictionary<string, bool> s_possibleTypeConverter = new Dictionary<string, bool>(16);
// This is the internal dummy type used when an IDictionary is converted to a pscustomobject
// PS C:\> $ps = [pscustomobject]@{a=10;b=5}
// PS C:\> $ps = [pscustomobject][ordered]@{a=10;b=5}
// Whenever we see a conversion to PSCustomObject, we represent it as a conversion to InternalPSCustomObject
// This is introduced to avoid breaking PSObject behavior.
// (Because PSCustomObject is a typeaccelerator for PSObject, we needed a separate type to represent type conversions to PSCustomObject)
internal class InternalPSCustomObject
{
}
internal class InternalPSObject : PSObject { }
internal static ConversionData FigureConversion(Type fromType, Type toType)
{
ConversionData data = GetConversionData(fromType, toType);
if (data != null)
{
return data;
}
if (fromType == typeof(Null))
{
return FigureConversionFromNull(toType);
}
if (toType.IsAssignableFrom(fromType))
{
return CacheConversion<object>(fromType, toType, LanguagePrimitives.ConvertAssignableFrom,
toType == fromType ? ConversionRank.Identity : ConversionRank.Assignable);
}
if (typeof(PSObject).IsAssignableFrom(fromType) && typeof(InternalPSObject) != fromType)
{
// We don't attempt converting PSObject (or derived) to anything else,
// instead we go straight to PSObject.Base (which is only a PSObject
// when no object is wrapped, in which case we try conversions from object)
// and convert that instead.
return CacheConversion(fromType, toType, ConvertNoConversion, ConversionRank.None);
}
if (toType == typeof(PSObject))
{
return CacheConversion<PSObject>(fromType, toType, LanguagePrimitives.ConvertToPSObject, ConversionRank.PSObject);
}
PSConverter<object> converter = null;
ConversionRank rank = ConversionRank.None;
// If we've ever used ConstrainedLanguage, check if the target type is allowed
if (ExecutionContext.HasEverUsedConstrainedLanguage)
{
var context = LocalPipeline.GetExecutionContextFromTLS();
if ((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage))
{
if ((toType != typeof(Object)) &&
(toType != typeof(Object[])) &&
(!CoreTypes.Contains(toType)))
{
converter = ConvertNotSupportedConversion;
rank = ConversionRank.None;
return CacheConversion(fromType, toType, converter, rank);
}
}
}
#if CORECLR
// Assemblies in CoreCLR might not allow reflection execution on their internal types.
TypeInfo typeInfo = toType.GetTypeInfo();
if (!TypeResolver.IsPublic(typeInfo) && DotNetAdapter.DisallowPrivateReflection(typeInfo))
{
// If the type is non-public and reflection execution is not allowed on it, then we return
// 'ConvertNoConversion', because we won't be able to invoke constructor, methods or set
// properties on an instance of this type through reflection.
return CacheConversion(fromType, toType, ConvertNoConversion, ConversionRank.None);
}
#endif
PSConverter<object> valueDependentConversion = null;
ConversionRank valueDependentRank = ConversionRank.None;
ConversionData conversionData = FigureLanguageConversion(fromType, toType, out valueDependentConversion, out valueDependentRank);
if (conversionData != null)
{
return conversionData;
}
rank = valueDependentConversion != null ? ConversionRank.Language : ConversionRank.None;
converter = FigureParseConversion(fromType, toType);
if (converter == null)
{
converter = FigureStaticCreateMethodConversion(fromType, toType);
if (converter == null)
{
converter = FigureConstructorConversion(fromType, toType);
rank = ConversionRank.Constructor;
if (converter == null)
{
converter = FigureCastConversion(fromType, toType, ref rank);
if (converter == null)
{
if (typeof(IConvertible).IsAssignableFrom(fromType))
{
if (LanguagePrimitives.IsNumeric(GetTypeCode(fromType)) && !fromType.GetTypeInfo().IsEnum)
{
if (!toType.IsArray)
{
if (GetConversionRank(typeof(string), toType) != ConversionRank.None)
{
converter = LanguagePrimitives.ConvertNumericIConvertible;
rank = ConversionRank.IConvertible;
}
}
}
else if (fromType != typeof(string))
{
converter = LanguagePrimitives.ConvertIConvertible;
rank = ConversionRank.IConvertible;
}
}
else if (typeof(IDictionary).IsAssignableFrom(fromType))
{
// We need to call the null argument constructor only if the following 2 conditions satisfy
// 1) if the fromType is either a hashtable or OrderedDictionary
// 2) if the ToType does not already have a constructor that takes a hashtable or OrderedDictionary. (This is to avoid breaking existing apps.)
// If the ToType has a constructor that takes a hashtable or OrderedDictionary,
// then it would have been returned as the constructor during FigureConstructorConversion
// So, we need to check only for the first condition
ConstructorInfo resultConstructor = toType.GetConstructor(PSTypeExtensions.EmptyTypes);
TypeInfo toTypeInfo = toType.GetTypeInfo();
if (resultConstructor != null || (toTypeInfo.IsValueType && !toTypeInfo.IsPrimitive))
{
ConvertViaNoArgumentConstructor noArgumentConstructorConverter = new ConvertViaNoArgumentConstructor(resultConstructor, toType);
converter = noArgumentConstructorConverter.Convert;
rank = ConversionRank.Constructor;
}
}
}
}
else
{
rank = ConversionRank.Constructor;
}
}
else
{
rank = ConversionRank.Create;
}
}
else
{
rank = ConversionRank.Parse;
}
if (converter == null)
{
var tuple = FigureIEnumerableConstructorConversion(fromType, toType);
if (tuple != null)
{
converter = tuple.Item1;
rank = tuple.Item2;
}
}
if (converter == null)
{
converter = FigurePropertyConversion(fromType, toType, ref rank);
}
if (TypeConverterPossiblyExists(fromType) || TypeConverterPossiblyExists(toType)
|| (converter != null && valueDependentConversion != null))
{
ConvertCheckingForCustomConverter customConverter = new ConvertCheckingForCustomConverter();
customConverter.tryfirstConverter = valueDependentConversion;
customConverter.fallbackConverter = converter;
converter = customConverter.Convert;
if (valueDependentRank > rank)
{
rank = valueDependentRank;
}
else if (rank == ConversionRank.None)
{
rank = ConversionRank.Custom;
}
}
else if (valueDependentConversion != null)
{
converter = valueDependentConversion;
rank = valueDependentRank;
}
if (converter == null)
{
converter = ConvertNoConversion;
rank = ConversionRank.None;
}
return CacheConversion(fromType, toType, converter, rank);
}
internal class Null { };
private static ConversionData FigureConversionFromNull(Type toType)
{
ConversionData data = GetConversionData(typeof(Null), toType);
if (data != null)
{
return data;
}
if (Nullable.GetUnderlyingType(toType) != null)
{
return CacheConversion<object>(typeof(Null), toType, LanguagePrimitives.ConvertNullToNullable, ConversionRank.NullToValue);
}
else if (!toType.GetTypeInfo().IsValueType)
{
return CacheConversion<object>(typeof(Null), toType, LanguagePrimitives.ConvertNullToRef, ConversionRank.NullToRef);
}
return CacheConversion(typeof(Null), toType, ConvertNoConversion, ConversionRank.None);
}
internal static string ObjectToTypeNameString(object o)
{
if (o == null)
{
return "null";
}
PSObject pso = PSObject.AsPSObject(o);
var typeNames = pso.InternalTypeNames;
if ((typeNames != null) && (typeNames.Count > 0))
{
return typeNames[0];
}
return Microsoft.PowerShell.ToStringCodeMethods.Type(o.GetType());
}
#if !CORECLR // AppDomain Not In CoreCLR
private static Assembly AssemblyResolveHelper(object sender, ResolveEventArgs args)
{
// Dynamic assemblies don't get resolved properly by the CLR, so we
// resolve them ourselves by looking through the loaded assemblies.
foreach (Assembly assem in ClrFacade.GetAssemblies())
{
if (assem.FullName == args.Name)
{
return assem;
}
}
return null;
}
#endif
#endregion type converter
}
}
#pragma warning restore 56500
| 50.484171 | 311 | 0.538443 | [
"Apache-2.0",
"MIT"
] | JM2K69/PowerShell | src/System.Management.Automation/engine/LanguagePrimitives.cs | 271,100 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.