content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleSharp.TL; namespace TeleSharp.TL { [TLObject(-668391402)] public class TLInputUser : TLAbsInputUser { public override int Constructor { get { return -668391402; } } public int UserId { get; set; } public long AccessHash { get; set; } public void ComputeFlags() { } public override void DeserializeBody(BinaryReader br) { this.UserId = br.ReadInt32(); this.AccessHash = br.ReadInt64(); } public override void SerializeBody(BinaryWriter bw) { bw.Write(this.Constructor); bw.Write(this.UserId); bw.Write(this.AccessHash); } } }
19.913043
61
0.556769
[ "MIT" ]
slctr/Men.Telegram.ClientApi
Men.Telegram.ClientApi/TL/TL/TLInputUser.cs
916
C#
#region Namespaces using System; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; #endregion namespace PostAddinCommand { /// <summary> /// External command to programmatically launch /// a custom button command. /// </summary> [Transaction( TransactionMode.ReadOnly )] public class CmdPost2 : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; // External tool commands defined by add-ins are // identified by the string listed in the // journal file when the command is launched // manually. string name_addin_button_cmd = "CustomCtrl_%CustomCtrl_%" + "Add-Ins%Post Add-in Command%Dummy2"; // --> id 6417 RevitCommandId id_addin_button_cmd = RevitCommandId.LookupCommandId( name_addin_button_cmd ); uiapp.PostCommand( id_addin_button_cmd ); return Result.Succeeded; } } }
26.227273
65
0.663778
[ "MIT" ]
jeremytammik/PostAddinCommand
PostAddinCommand/CmdPost2.cs
1,156
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 acm-pca-2017-08-22.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Runtime; using Amazon.ACMPCA.Model; namespace Amazon.ACMPCA { /// <summary> /// Interface for accessing ACMPCA /// /// You can use the ACM PCA API to create a private certificate authority (CA). You must /// first call the <a>CreateCertificateAuthority</a> operation. If successful, the operation /// returns an Amazon Resource Name (ARN) for your private CA. Use this ARN as input to /// the <a>GetCertificateAuthorityCsr</a> operation to retrieve the certificate signing /// request (CSR) for your private CA certificate. Sign the CSR using the root or an intermediate /// CA in your on-premises PKI hierarchy, and call the <a>ImportCertificateAuthorityCertificate</a> /// to import your signed private CA certificate into ACM PCA. /// /// /// <para> /// Use your private CA to issue and revoke certificates. These are private certificates /// that identify and secure client computers, servers, applications, services, devices, /// and users over SSLS/TLS connections within your organization. Call the <a>IssueCertificate</a> /// operation to issue a certificate. Call the <a>RevokeCertificate</a> operation to revoke /// a certificate. /// </para> /// <note> /// <para> /// Certificates issued by your private CA can be trusted only within your organization, /// not publicly. /// </para> /// </note> /// <para> /// Your private CA can optionally create a certificate revocation list (CRL) to track /// the certificates you revoke. To create a CRL, you must specify a <a>RevocationConfiguration</a> /// object when you call the <a>CreateCertificateAuthority</a> operation. ACM PCA writes /// the CRL to an S3 bucket that you specify. You must specify a bucket policy that grants /// ACM PCA write permission. /// </para> /// /// <para> /// You can also call the <a>CreateCertificateAuthorityAuditReport</a> to create an optional /// audit report that lists every time the CA private key is used. The private key is /// used for signing when the <b>IssueCertificate</b> or <b>RevokeCertificate</b> operation /// is called. /// </para> /// </summary> public partial interface IAmazonACMPCA : IAmazonService, IDisposable { #region CreateCertificateAuthority /// <summary> /// Creates a private subordinate certificate authority (CA). You must specify the CA /// configuration, the revocation configuration, the CA type, and an optional idempotency /// token. The CA configuration specifies the name of the algorithm and key size to be /// used to create the CA private key, the type of signing algorithm that the CA uses /// to sign, and X.500 subject information. The CRL (certificate revocation list) configuration /// specifies the CRL expiration period in days (the validity period of the CRL), the /// Amazon S3 bucket that will contain the CRL, and a CNAME alias for the S3 bucket that /// is included in certificates issued by the CA. If successful, this operation returns /// the Amazon Resource Name (ARN) of the CA. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateCertificateAuthority service method.</param> /// /// <returns>The response from the CreateCertificateAuthority service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException"> /// One or more of the specified arguments was not valid. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidPolicyException"> /// The S3 bucket policy is not valid. The policy must give ACM PCA rights to read from /// and write to the bucket and find the bucket location. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.LimitExceededException"> /// An ACM PCA limit has been exceeded. See the exception message returned to determine /// the limit that was exceeded. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthority">REST API Reference for CreateCertificateAuthority Operation</seealso> CreateCertificateAuthorityResponse CreateCertificateAuthority(CreateCertificateAuthorityRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateCertificateAuthority operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCertificateAuthority operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthority">REST API Reference for CreateCertificateAuthority Operation</seealso> Task<CreateCertificateAuthorityResponse> CreateCertificateAuthorityAsync(CreateCertificateAuthorityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateCertificateAuthorityAuditReport /// <summary> /// Creates an audit report that lists every time that the your CA private key is used. /// The report is saved in the Amazon S3 bucket that you specify on input. The <a>IssueCertificate</a> /// and <a>RevokeCertificate</a> operations use the private key. You can generate a new /// report every 30 minutes. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateCertificateAuthorityAuditReport service method.</param> /// /// <returns>The response from the CreateCertificateAuthorityAuditReport service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException"> /// One or more of the specified arguments was not valid. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestFailedException"> /// The request has failed for an unspecified reason. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException"> /// Your request is already in progress. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityAuditReport">REST API Reference for CreateCertificateAuthorityAuditReport Operation</seealso> CreateCertificateAuthorityAuditReportResponse CreateCertificateAuthorityAuditReport(CreateCertificateAuthorityAuditReportRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateCertificateAuthorityAuditReport operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCertificateAuthorityAuditReport operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/CreateCertificateAuthorityAuditReport">REST API Reference for CreateCertificateAuthorityAuditReport Operation</seealso> Task<CreateCertificateAuthorityAuditReportResponse> CreateCertificateAuthorityAuditReportAsync(CreateCertificateAuthorityAuditReportRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteCertificateAuthority /// <summary> /// Deletes a private certificate authority (CA). You must provide the ARN (Amazon Resource /// Name) of the private CA that you want to delete. You can find the ARN by calling the /// <a>ListCertificateAuthorities</a> operation. Before you can delete a CA, you must /// disable it. Call the <a>UpdateCertificateAuthority</a> operation and set the <b>CertificateAuthorityStatus</b> /// parameter to <code>DISABLED</code>. /// /// /// <para> /// Additionally, you can delete a CA if you are waiting for it to be created (the <b>Status</b> /// field of the <a>CertificateAuthority</a> is <code>CREATING</code>). You can also delete /// it if the CA has been created but you haven't yet imported the signed certificate /// (the <b>Status</b> is <code>PENDING_CERTIFICATE</code>) into ACM PCA. /// </para> /// /// <para> /// If the CA is in one of the aforementioned states and you call <a>DeleteCertificateAuthority</a>, /// the CA's status changes to <code>DELETED</code>. However, the CA won't be permentantly /// deleted until the restoration period has passed. By default, if you do not set the /// <code>PermanentDeletionTimeInDays</code> parameter, the CA remains restorable for /// 30 days. You can set the parameter from 7 to 30 days. The <a>DescribeCertificateAuthority</a> /// operation returns the time remaining in the restoration window of a Private CA in /// the <code>DELETED</code> state. To restore an eligable CA, call the <a>RestoreCertificateAuthority</a> /// operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteCertificateAuthority service method.</param> /// /// <returns>The response from the DeleteCertificateAuthority service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException"> /// A previous update to your private CA is still ongoing. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeleteCertificateAuthority">REST API Reference for DeleteCertificateAuthority Operation</seealso> DeleteCertificateAuthorityResponse DeleteCertificateAuthority(DeleteCertificateAuthorityRequest request); /// <summary> /// Initiates the asynchronous execution of the DeleteCertificateAuthority operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCertificateAuthority operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DeleteCertificateAuthority">REST API Reference for DeleteCertificateAuthority Operation</seealso> Task<DeleteCertificateAuthorityResponse> DeleteCertificateAuthorityAsync(DeleteCertificateAuthorityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCertificateAuthority /// <summary> /// Lists information about your private certificate authority (CA). You specify the private /// CA on input by its ARN (Amazon Resource Name). The output contains the status of your /// CA. This can be any of the following: /// /// <ul> <li> /// <para> /// <code>CREATING</code> - ACM PCA is creating your private certificate authority. /// </para> /// </li> <li> /// <para> /// <code>PENDING_CERTIFICATE</code> - The certificate is pending. You must use your /// on-premises root or subordinate CA to sign your private CA CSR and then import it /// into PCA. /// </para> /// </li> <li> /// <para> /// <code>ACTIVE</code> - Your private CA is active. /// </para> /// </li> <li> /// <para> /// <code>DISABLED</code> - Your private CA has been disabled. /// </para> /// </li> <li> /// <para> /// <code>EXPIRED</code> - Your private CA certificate has expired. /// </para> /// </li> <li> /// <para> /// <code>FAILED</code> - Your private CA has failed. Your CA can fail because of problems /// such a network outage or backend AWS failure or other errors. A failed CA can never /// return to the pending state. You must create a new CA. /// </para> /// </li> <li> /// <para> /// <code>DELETED</code> - Your private CA is within the restoration period, after which /// it will be permanently deleted. The length of time remaining in the CA's restoration /// period will also be included in this operation's output. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCertificateAuthority service method.</param> /// /// <returns>The response from the DescribeCertificateAuthority service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthority">REST API Reference for DescribeCertificateAuthority Operation</seealso> DescribeCertificateAuthorityResponse DescribeCertificateAuthority(DescribeCertificateAuthorityRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeCertificateAuthority operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCertificateAuthority operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthority">REST API Reference for DescribeCertificateAuthority Operation</seealso> Task<DescribeCertificateAuthorityResponse> DescribeCertificateAuthorityAsync(DescribeCertificateAuthorityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCertificateAuthorityAuditReport /// <summary> /// Lists information about a specific audit report created by calling the <a>CreateCertificateAuthorityAuditReport</a> /// operation. Audit information is created every time the certificate authority (CA) /// private key is used. The private key is used when you call the <a>IssueCertificate</a> /// operation or the <a>RevokeCertificate</a> operation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCertificateAuthorityAuditReport service method.</param> /// /// <returns>The response from the DescribeCertificateAuthorityAuditReport service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException"> /// One or more of the specified arguments was not valid. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityAuditReport">REST API Reference for DescribeCertificateAuthorityAuditReport Operation</seealso> DescribeCertificateAuthorityAuditReportResponse DescribeCertificateAuthorityAuditReport(DescribeCertificateAuthorityAuditReportRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeCertificateAuthorityAuditReport operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCertificateAuthorityAuditReport operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/DescribeCertificateAuthorityAuditReport">REST API Reference for DescribeCertificateAuthorityAuditReport Operation</seealso> Task<DescribeCertificateAuthorityAuditReportResponse> DescribeCertificateAuthorityAuditReportAsync(DescribeCertificateAuthorityAuditReportRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetCertificate /// <summary> /// Retrieves a certificate from your private CA. The ARN of the certificate is returned /// when you call the <a>IssueCertificate</a> operation. You must specify both the ARN /// of your private CA and the ARN of the issued certificate when calling the <b>GetCertificate</b> /// operation. You can retrieve the certificate if it is in the <b>ISSUED</b> state. You /// can call the <a>CreateCertificateAuthorityAuditReport</a> operation to create a report /// that contains information about all of the certificates issued and revoked by your /// private CA. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetCertificate service method.</param> /// /// <returns>The response from the GetCertificate service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestFailedException"> /// The request has failed for an unspecified reason. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException"> /// Your request is already in progress. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificate">REST API Reference for GetCertificate Operation</seealso> GetCertificateResponse GetCertificate(GetCertificateRequest request); /// <summary> /// Initiates the asynchronous execution of the GetCertificate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetCertificate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificate">REST API Reference for GetCertificate Operation</seealso> Task<GetCertificateResponse> GetCertificateAsync(GetCertificateRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetCertificateAuthorityCertificate /// <summary> /// Retrieves the certificate and certificate chain for your private certificate authority /// (CA). Both the certificate and the chain are base64 PEM-encoded. The chain does not /// include the CA certificate. Each certificate in the chain signs the one before it. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetCertificateAuthorityCertificate service method.</param> /// /// <returns>The response from the GetCertificateAuthorityCertificate service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCertificate">REST API Reference for GetCertificateAuthorityCertificate Operation</seealso> GetCertificateAuthorityCertificateResponse GetCertificateAuthorityCertificate(GetCertificateAuthorityCertificateRequest request); /// <summary> /// Initiates the asynchronous execution of the GetCertificateAuthorityCertificate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetCertificateAuthorityCertificate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCertificate">REST API Reference for GetCertificateAuthorityCertificate Operation</seealso> Task<GetCertificateAuthorityCertificateResponse> GetCertificateAuthorityCertificateAsync(GetCertificateAuthorityCertificateRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetCertificateAuthorityCsr /// <summary> /// Retrieves the certificate signing request (CSR) for your private certificate authority /// (CA). The CSR is created when you call the <a>CreateCertificateAuthority</a> operation. /// Take the CSR to your on-premises X.509 infrastructure and sign it by using your root /// or a subordinate CA. Then import the signed certificate back into ACM PCA by calling /// the <a>ImportCertificateAuthorityCertificate</a> operation. The CSR is returned as /// a base64 PEM-encoded string. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetCertificateAuthorityCsr service method.</param> /// /// <returns>The response from the GetCertificateAuthorityCsr service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestFailedException"> /// The request has failed for an unspecified reason. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException"> /// Your request is already in progress. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCsr">REST API Reference for GetCertificateAuthorityCsr Operation</seealso> GetCertificateAuthorityCsrResponse GetCertificateAuthorityCsr(GetCertificateAuthorityCsrRequest request); /// <summary> /// Initiates the asynchronous execution of the GetCertificateAuthorityCsr operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetCertificateAuthorityCsr operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/GetCertificateAuthorityCsr">REST API Reference for GetCertificateAuthorityCsr Operation</seealso> Task<GetCertificateAuthorityCsrResponse> GetCertificateAuthorityCsrAsync(GetCertificateAuthorityCsrRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ImportCertificateAuthorityCertificate /// <summary> /// Imports your signed private CA certificate into ACM PCA. Before you can call this /// operation, you must create the private certificate authority by calling the <a>CreateCertificateAuthority</a> /// operation. You must then generate a certificate signing request (CSR) by calling the /// <a>GetCertificateAuthorityCsr</a> operation. Take the CSR to your on-premises CA and /// use the root certificate or a subordinate certificate to sign it. Create a certificate /// chain and copy the signed certificate and the certificate chain to your working directory. /// /// /// <note> /// <para> /// Your certificate chain must not include the private CA certificate that you are importing. /// </para> /// </note> <note> /// <para> /// Your on-premises CA certificate must be the last certificate in your chain. The subordinate /// certificate, if any, that your root CA signed must be next to last. The subordinate /// certificate signed by the preceding subordinate CA must come next, and so on until /// your chain is built. /// </para> /// </note> <note> /// <para> /// The chain must be PEM-encoded. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ImportCertificateAuthorityCertificate service method.</param> /// /// <returns>The response from the ImportCertificateAuthorityCertificate service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.CertificateMismatchException"> /// The certificate authority certificate you are importing does not comply with conditions /// specified in the certificate that signed it. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException"> /// A previous update to your private CA is still ongoing. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.MalformedCertificateException"> /// One or more fields in the certificate are invalid. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestFailedException"> /// The request has failed for an unspecified reason. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException"> /// Your request is already in progress. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ImportCertificateAuthorityCertificate">REST API Reference for ImportCertificateAuthorityCertificate Operation</seealso> ImportCertificateAuthorityCertificateResponse ImportCertificateAuthorityCertificate(ImportCertificateAuthorityCertificateRequest request); /// <summary> /// Initiates the asynchronous execution of the ImportCertificateAuthorityCertificate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ImportCertificateAuthorityCertificate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ImportCertificateAuthorityCertificate">REST API Reference for ImportCertificateAuthorityCertificate Operation</seealso> Task<ImportCertificateAuthorityCertificateResponse> ImportCertificateAuthorityCertificateAsync(ImportCertificateAuthorityCertificateRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region IssueCertificate /// <summary> /// Uses your private certificate authority (CA) to issue a client certificate. This operation /// returns the Amazon Resource Name (ARN) of the certificate. You can retrieve the certificate /// by calling the <a>GetCertificate</a> operation and specifying the ARN. /// /// <note> /// <para> /// You cannot use the ACM <b>ListCertificateAuthorities</b> operation to retrieve the /// ARNs of the certificates that you issue by using ACM PCA. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the IssueCertificate service method.</param> /// /// <returns>The response from the IssueCertificate service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException"> /// One or more of the specified arguments was not valid. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.LimitExceededException"> /// An ACM PCA limit has been exceeded. See the exception message returned to determine /// the limit that was exceeded. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.MalformedCSRException"> /// The certificate signing request is invalid. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/IssueCertificate">REST API Reference for IssueCertificate Operation</seealso> IssueCertificateResponse IssueCertificate(IssueCertificateRequest request); /// <summary> /// Initiates the asynchronous execution of the IssueCertificate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the IssueCertificate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/IssueCertificate">REST API Reference for IssueCertificate Operation</seealso> Task<IssueCertificateResponse> IssueCertificateAsync(IssueCertificateRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListCertificateAuthorities /// <summary> /// Lists the private certificate authorities that you created by using the <a>CreateCertificateAuthority</a> /// operation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListCertificateAuthorities service method.</param> /// /// <returns>The response from the ListCertificateAuthorities service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidNextTokenException"> /// The token specified in the <code>NextToken</code> argument is not valid. Use the token /// returned from your previous call to <a>ListCertificateAuthorities</a>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListCertificateAuthorities">REST API Reference for ListCertificateAuthorities Operation</seealso> ListCertificateAuthoritiesResponse ListCertificateAuthorities(ListCertificateAuthoritiesRequest request); /// <summary> /// Initiates the asynchronous execution of the ListCertificateAuthorities operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListCertificateAuthorities operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListCertificateAuthorities">REST API Reference for ListCertificateAuthorities Operation</seealso> Task<ListCertificateAuthoritiesResponse> ListCertificateAuthoritiesAsync(ListCertificateAuthoritiesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListTags /// <summary> /// Lists the tags, if any, that are associated with your private CA. Tags are labels /// that you can use to identify and organize your CAs. Each tag consists of a key and /// an optional value. Call the <a>TagCertificateAuthority</a> operation to add one or /// more tags to your CA. Call the <a>UntagCertificateAuthority</a> operation to remove /// tags. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTags service method.</param> /// /// <returns>The response from the ListTags service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListTags">REST API Reference for ListTags Operation</seealso> ListTagsResponse ListTags(ListTagsRequest request); /// <summary> /// Initiates the asynchronous execution of the ListTags operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTags operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/ListTags">REST API Reference for ListTags Operation</seealso> Task<ListTagsResponse> ListTagsAsync(ListTagsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RestoreCertificateAuthority /// <summary> /// Restores a certificate authority (CA) that is in the <code>DELETED</code> state. You /// can restore a CA during the period that you defined in the <b>PermanentDeletionTimeInDays</b> /// parameter of the <a>DeleteCertificateAuthority</a> operation. Currently, you can specify /// 7 to 30 days. If you did not specify a <b>PermanentDeletionTimeInDays</b> value, by /// default you can restore the CA at any time in a 30 day period. You can check the time /// remaining in the restoration period of a private CA in the <code>DELETED</code> state /// by calling the <a>DescribeCertificateAuthority</a> or <a>ListCertificateAuthorities</a> /// operations. The status of a restored CA is set to its pre-deletion status when the /// <b>RestoreCertificateAuthority</b> operation returns. To change its status to <code>ACTIVE</code>, /// call the <a>UpdateCertificateAuthority</a> operation. If the private CA was in the /// <code>PENDING_CERTIFICATE</code> state at deletion, you must use the <a>ImportCertificateAuthorityCertificate</a> /// operation to import a certificate authority into the private CA before it can be activated. /// You cannot restore a CA after the restoration period has ended. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RestoreCertificateAuthority service method.</param> /// /// <returns>The response from the RestoreCertificateAuthority service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RestoreCertificateAuthority">REST API Reference for RestoreCertificateAuthority Operation</seealso> RestoreCertificateAuthorityResponse RestoreCertificateAuthority(RestoreCertificateAuthorityRequest request); /// <summary> /// Initiates the asynchronous execution of the RestoreCertificateAuthority operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RestoreCertificateAuthority operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RestoreCertificateAuthority">REST API Reference for RestoreCertificateAuthority Operation</seealso> Task<RestoreCertificateAuthorityResponse> RestoreCertificateAuthorityAsync(RestoreCertificateAuthorityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RevokeCertificate /// <summary> /// Revokes a certificate that you issued by calling the <a>IssueCertificate</a> operation. /// If you enable a certificate revocation list (CRL) when you create or update your private /// CA, information about the revoked certificates will be included in the CRL. ACM PCA /// writes the CRL to an S3 bucket that you specify. For more information about revocation, /// see the <a>CrlConfiguration</a> structure. ACM PCA also writes revocation information /// to the audit report. For more information, see <a>CreateCertificateAuthorityAuditReport</a>. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RevokeCertificate service method.</param> /// /// <returns>The response from the RevokeCertificate service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException"> /// A previous update to your private CA is still ongoing. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestAlreadyProcessedException"> /// Your request has already been completed. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestFailedException"> /// The request has failed for an unspecified reason. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.RequestInProgressException"> /// Your request is already in progress. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RevokeCertificate">REST API Reference for RevokeCertificate Operation</seealso> RevokeCertificateResponse RevokeCertificate(RevokeCertificateRequest request); /// <summary> /// Initiates the asynchronous execution of the RevokeCertificate operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RevokeCertificate operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/RevokeCertificate">REST API Reference for RevokeCertificate Operation</seealso> Task<RevokeCertificateResponse> RevokeCertificateAsync(RevokeCertificateRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TagCertificateAuthority /// <summary> /// Adds one or more tags to your private CA. Tags are labels that you can use to identify /// and organize your AWS resources. Each tag consists of a key and an optional value. /// You specify the private CA on input by its Amazon Resource Name (ARN). You specify /// the tag by using a key-value pair. You can apply a tag to just one private CA if you /// want to identify a specific characteristic of that CA, or you can apply the same tag /// to multiple private CAs if you want to filter for a common relationship among those /// CAs. To remove one or more tags, use the <a>UntagCertificateAuthority</a> operation. /// Call the <a>ListTags</a> operation to see what tags are associated with your CA. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagCertificateAuthority service method.</param> /// /// <returns>The response from the TagCertificateAuthority service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidTagException"> /// The tag associated with the CA is not valid. The invalid argument is contained in /// the message field. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.TooManyTagsException"> /// You can associate up to 50 tags with a private CA. Exception information is contained /// in the exception message field. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/TagCertificateAuthority">REST API Reference for TagCertificateAuthority Operation</seealso> TagCertificateAuthorityResponse TagCertificateAuthority(TagCertificateAuthorityRequest request); /// <summary> /// Initiates the asynchronous execution of the TagCertificateAuthority operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TagCertificateAuthority operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/TagCertificateAuthority">REST API Reference for TagCertificateAuthority Operation</seealso> Task<TagCertificateAuthorityResponse> TagCertificateAuthorityAsync(TagCertificateAuthorityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UntagCertificateAuthority /// <summary> /// Remove one or more tags from your private CA. A tag consists of a key-value pair. /// If you do not specify the value portion of the tag when calling this operation, the /// tag will be removed regardless of value. If you specify a value, the tag is removed /// only if it is associated with the specified value. To add tags to a private CA, use /// the <a>TagCertificateAuthority</a>. Call the <a>ListTags</a> operation to see what /// tags are associated with your CA. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagCertificateAuthority service method.</param> /// /// <returns>The response from the UntagCertificateAuthority service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidTagException"> /// The tag associated with the CA is not valid. The invalid argument is contained in /// the message field. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UntagCertificateAuthority">REST API Reference for UntagCertificateAuthority Operation</seealso> UntagCertificateAuthorityResponse UntagCertificateAuthority(UntagCertificateAuthorityRequest request); /// <summary> /// Initiates the asynchronous execution of the UntagCertificateAuthority operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UntagCertificateAuthority operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UntagCertificateAuthority">REST API Reference for UntagCertificateAuthority Operation</seealso> Task<UntagCertificateAuthorityResponse> UntagCertificateAuthorityAsync(UntagCertificateAuthorityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateCertificateAuthority /// <summary> /// Updates the status or configuration of a private certificate authority (CA). Your /// private CA must be in the <code>ACTIVE</code> or <code>DISABLED</code> state before /// you can update it. You can disable a private CA that is in the <code>ACTIVE</code> /// state or make a CA that is in the <code>DISABLED</code> state active again. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateCertificateAuthority service method.</param> /// /// <returns>The response from the UpdateCertificateAuthority service method, as returned by ACMPCA.</returns> /// <exception cref="Amazon.ACMPCA.Model.ConcurrentModificationException"> /// A previous update to your private CA is still ongoing. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArgsException"> /// One or more of the specified arguments was not valid. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidArnException"> /// The requested Amazon Resource Name (ARN) does not refer to an existing resource. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidPolicyException"> /// The S3 bucket policy is not valid. The policy must give ACM PCA rights to read from /// and write to the bucket and find the bucket location. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.InvalidStateException"> /// The private CA is in a state during which a report cannot be generated. /// </exception> /// <exception cref="Amazon.ACMPCA.Model.ResourceNotFoundException"> /// A resource such as a private CA, S3 bucket, certificate, or audit report cannot be /// found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UpdateCertificateAuthority">REST API Reference for UpdateCertificateAuthority Operation</seealso> UpdateCertificateAuthorityResponse UpdateCertificateAuthority(UpdateCertificateAuthorityRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateCertificateAuthority operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateCertificateAuthority operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/acm-pca-2017-08-22/UpdateCertificateAuthority">REST API Reference for UpdateCertificateAuthority Operation</seealso> Task<UpdateCertificateAuthorityResponse> UpdateCertificateAuthorityAsync(UpdateCertificateAuthorityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
61.059893
229
0.683015
[ "Apache-2.0" ]
DalavanCloud/aws-sdk-net
sdk/src/Services/ACMPCA/Generated/_bcl45/IAmazonACMPCA.cs
57,091
C#
// SlideStopEvent.cs // Script#/Libraries/jQuery/UI // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; namespace jQueryApi.UI.Widgets { [ScriptImport] [ScriptIgnoreNamespace] [ScriptName("Object")] public sealed class SlideStopEvent { [ScriptField] public jQueryObject Handle { get { return null; } set { } } [ScriptField] public int Value { get { return 0; } set { } } } }
19.171429
90
0.52161
[ "Apache-2.0" ]
AmanArnold/dsharp
src/Libraries/jQuery/jQuery.UI/Widgets/Slider/SlideStopEvent.cs
671
C#
/* * Copyright © 2013 Ben Bader * * 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.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Rocks; using Mono.Collections.Generic; using Stiletto.Internal.Loaders.Codegen; namespace Stiletto.Fody.Generators { public class LazyBindingGenerator : Generator { private readonly string key; private readonly string lazyKey; private readonly TypeReference lazyElementType; private readonly MethodReference lazyCtor; private readonly MethodReference funcCtor; private MethodReference generatedCtor; public string Key { get { return key; } } public string LazyKey { get { return lazyKey; } } public LazyBindingGenerator(ModuleDefinition moduleDefinition, References references, string key, string lazyKey, TypeReference lazyElementType) : base(moduleDefinition, references) { this.key = Conditions.CheckNotNull(key, "key"); this.lazyKey = Conditions.CheckNotNull(lazyKey, "lazyKey"); this.lazyElementType = Conditions.CheckNotNull(lazyElementType, "lazyElementType"); funcCtor = ImportGeneric( References.FuncOfT, m => m.IsConstructor && m.Parameters.Count == 2, lazyElementType); lazyCtor = ImportGeneric( References.LazyOfT, m => m.Parameters.Count == 1 && m.Parameters[0].ParameterType.Name.StartsWith("Func", StringComparison.Ordinal), lazyElementType); } public override void Validate(IErrorReporter errorReporter) { } public override TypeDefinition Generate(IErrorReporter errorReporter) { var t = new TypeDefinition( lazyElementType.Namespace, lazyElementType.Name + CodegenLoader.LazySuffix, TypeAttributes.Public | TypeAttributes.Sealed, References.Binding); t.CustomAttributes.Add(new CustomAttribute(References.CompilerGeneratedAttribute)); var lazyKeyField = new FieldDefinition("lazyKey", FieldAttributes.Private, References.String); var delegateBindingField = new FieldDefinition("delegateBinding", FieldAttributes.Private, References.Binding); t.Fields.Add(lazyKeyField); t.Fields.Add(delegateBindingField); EmitCtor(t, lazyKeyField); EmitResolve(t, lazyKeyField, delegateBindingField); EmitGet(t, delegateBindingField); return t; } public override KeyedCtor GetKeyedCtor() { Conditions.CheckNotNull(generatedCtor); return new KeyedCtor(lazyKey, generatedCtor); } private void EmitCtor(TypeDefinition lazyBinding, FieldReference lazyKeyField) { /** * public TypeName_CompiledLazyBinding(string key, object requiredBy, string lazyKey) * : base(key, null, false, requiredBy) * { * this.lazyKey = lazyKey; * } */ var ctor = new MethodDefinition( ".ctor", MethodAttributes.Public | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.HideBySig, References.Void); ctor.Parameters.Add(new ParameterDefinition("key", ParameterAttributes.None, References.String)); ctor.Parameters.Add(new ParameterDefinition("requiredBy", ParameterAttributes.None, References.Object)); ctor.Parameters.Add(new ParameterDefinition("lazyKey", ParameterAttributes.None, References.String)); var il = ctor.Body.GetILProcessor(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldnull); il.EmitBoolean(false); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Call, References.Binding_Ctor); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_3); il.Emit(OpCodes.Stfld, lazyKeyField); il.Emit(OpCodes.Ret); lazyBinding.Methods.Add(ctor); generatedCtor = ctor; } private void EmitResolve(TypeDefinition lazyBinding, FieldReference lazyKeyField, FieldReference delegateBindingField) { /** * public override void Resolve(Resolver resolver) * { * this.delegateBinding = resolver.RequestBinding(this.lazyKey, RequiredBy, true, true); * } */ var resolve = new MethodDefinition( "Resolve", MethodAttributes.Public | MethodAttributes.Virtual, References.Void); resolve.Parameters.Add(new ParameterDefinition(References.Resolver)); var il = resolve.Body.GetILProcessor(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, lazyKeyField); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Callvirt, References.Binding_RequiredByGetter); il.EmitBoolean(true); il.EmitBoolean(true); il.Emit(OpCodes.Callvirt, References.Resolver_RequestBinding); il.Emit(OpCodes.Stfld, delegateBindingField); il.Emit(OpCodes.Ret); lazyBinding.Methods.Add(resolve); } private void EmitGet(TypeDefinition lazyBinding, FieldReference delegateBindingField) { /** * private T GetTypedValue() * { * return (T) delegateBinding.Get(); * } * * public override object Get() * { * return new Lazy<T>(new Func<T>(GetTypedValue)); * } */ var get = new MethodDefinition( "Get", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, References.Object); var getTypedValue = new MethodDefinition( "GetTypedValue", MethodAttributes.Private | MethodAttributes.HideBySig, lazyElementType); // First we emit a helper method to serve as the body of a Func<T>, // because lambdas don't exist in IL var il = getTypedValue.Body.GetILProcessor(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, delegateBindingField); il.Emit(OpCodes.Callvirt, References.Binding_Get); il.Cast(lazyElementType); il.Emit(OpCodes.Ret); lazyBinding.Methods.Add(getTypedValue); il = get.Body.GetILProcessor(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldftn, getTypedValue); il.Emit(OpCodes.Newobj, funcCtor); il.Emit(OpCodes.Newobj, lazyCtor); il.Emit(OpCodes.Ret); lazyBinding.Methods.Add(get); } } }
37.735294
152
0.60873
[ "Apache-2.0" ]
OlexaLe/stiletto
Stiletto.Fody/Generators/LazyBindingGenerator.cs
7,701
C#
namespace CodeVeinOutfitInjector { public enum StandardColor_Blue1 { palette_stg_bluegreen00, palette_stg_bluegreen10, palette_stg_bluegreen20, palette_stg_bluegreen30, palette_stg_bluegreen40, palette_stg_bluegreen50, palette_stg_bluegreen60, palette_stg_bluegreen70, palette_stg_bluegreen01, palette_stg_bluegreen11, palette_stg_bluegreen21, palette_stg_bluegreen31, palette_stg_bluegreen41, palette_stg_bluegreen51, palette_stg_bluegreen61, palette_stg_bluegreen71, palette_stg_bluegreen02, palette_stg_bluegreen12, palette_stg_bluegreen22, palette_stg_bluegreen32, palette_stg_bluegreen42, palette_stg_bluegreen52, palette_stg_bluegreen62, palette_stg_bluegreen72, } }
23.354839
32
0.845304
[ "MIT" ]
Code-Vein-Tool-Hub/CodeVeinOutfitInjector
CodeVeinOutfitInjector/enums/StandardColor_Blue1.cs
724
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ScoreboardManager.Common.ViewModels; using ScoreboardManager.ServiceFacade; using ScoreboardManager.WebFormLib; using ScoreboardManager.Common.Messages; using ScoreboardManager.Common.Extension; using ScoreboardManager.Common.Models; namespace ScoreboardManager.WebForms { public partial class _Default : SecureBasePage { #region Page Events protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string errorMessage; List<PointViewModel> lstPoints = this.GetPoints(out errorMessage); List<PointViewModel> lstSortedScoreboardData = this.GetSortedScoreboardData(out errorMessage, "TotalPoints", "DESC", lstPoints); LoadScoreboardData(lstSortedScoreboardData); List<PlayerViewModel> lstPlayers = this.GetPlayers(out errorMessage); this.LoadPlayers(lstPlayers); List<MatchViewModel> lstMatchs = this.GetMatchs(out errorMessage); this.LoadMatchs(lstMatchs); } } #endregion #region Control's Events protected void gvScoreboard_Sorting(object sender, GridViewSortEventArgs e) { string errorMessage; string currentSortDirection = gvScoreboard.Attributes["CurrentSortDirection"]; List<PointViewModel> lstPoints = this.GetPoints(out errorMessage); List<PointViewModel> lstSortedScoreboardData = this.GetSortedScoreboardData(out errorMessage, e.SortExpression, currentSortDirection, lstPoints); LoadScoreboardData(lstSortedScoreboardData); this.ChangeCurrentSortDirection(currentSortDirection); } protected void gvScoreboard_RowDataBound(object sender, GridViewRowEventArgs e) { e.Row.Cells[3].Visible = false; e.Row.Cells[4].Visible = false; e.Row.Cells[5].Visible = false; } protected void lbtnAddPoint_Click(object sender, EventArgs e) { string message; bool result = this.SaveData(out message); if (result) { base.ShowSuccessNotification(message); this.ResetInputFields(); List<PointViewModel> lstPoints = this.GetPoints(out message); List<PointViewModel> lstSortedScoreboardData = this.GetSortedScoreboardData(out message, "TotalPoints", "DESC", lstPoints); LoadScoreboardData(lstSortedScoreboardData); } else { base.ShowErrorNotification(message); } } #endregion #region Private Methods /// <summary> /// Method to reset the values of input fields. /// </summary> private void ResetInputFields() { ddlPlayers.SelectedIndex = 0; ddlMatchs.SelectedIndex = 0; txtNewPoint.Text = string.Empty; } /// <summary> /// Method to insert new point for a player in database. /// </summary> /// <param name="message"></param> /// <returns></returns> private bool SaveData(out string message) { bool result = false; message = string.Empty; Facade facade = new Facade(); if (this.ValidateData(out message)) { if (!this.IsPointExist(out message, ddlPlayers.SelectedValue.ToInt(), ddlMatchs.SelectedValue.ToInt())) { PointModel pointModel = this.GetPointData(); result = facade.PointsInsert(out message, pointModel); if (result) { message = OperationMessages.OPERATION_SUCCESSFUL; } } else { message = ErrorMessages.POINT_IS_EXISTING; } } return result; } /// <summary> /// Method to get point data from UI. /// </summary> /// <returns></returns> private PointModel GetPointData() { PointModel pointModel = new PointModel(); pointModel.PlayerID = ddlPlayers.SelectedValue.ToInt(); pointModel.MatchID = ddlMatchs.SelectedValue.ToInt(); pointModel.Point = txtNewPoint.Text.ToInt(); return pointModel; } /// <summary> /// Method to check whether Point of a particular match of a player is exist in the table. /// </summary> /// <param name="message"></param> /// <param name="playerId"></param> /// <param name="matchId"></param> /// <returns></returns> private bool IsPointExist(out string message, int playerId, int matchId) { Facade facade = new Facade(); return facade.IsPointExist(out message, playerId, matchId); } /// <summary> /// Method to validate required input data. /// </summary> /// <param name="errorMessage"></param> /// <returns></returns> private bool ValidateData(out string errorMessage) { errorMessage = string.Empty; if (this.ddlPlayers.SelectedIndex <= 0) { this.ddlPlayers.Focus(); this.ddlPlayers.BorderColor = System.Drawing.Color.Red; errorMessage = ErrorMessages.REQUIRED_FILD_IS_MISSING; return false; } if (this.ddlMatchs.SelectedIndex <= 0) { this.ddlMatchs.Focus(); this.ddlMatchs.BorderColor = System.Drawing.Color.Red; errorMessage = ErrorMessages.REQUIRED_FILD_IS_MISSING; return false; } if (this.txtNewPoint.Text.IsNullOrWhiteSpace()) { this.txtNewPoint.Focus(); this.txtNewPoint.BorderColor = System.Drawing.Color.Red; errorMessage = ErrorMessages.REQUIRED_FILD_IS_MISSING; return false; } return true; } /// <summary> /// Method to load matchs in dropdown. /// </summary> /// <param name="lstMatchs"></param> private void LoadMatchs(List<MatchViewModel> lstMatchs) { ddlMatchs.DataSource = lstMatchs; ddlMatchs.DataValueField = "MatchID"; ddlMatchs.DataTextField = "MatchName"; ddlMatchs.DataBind(); ddlMatchs.Items.Insert(0, new ListItem("---- Select Match -----", "-1")); } /// <summary> /// Method to get all matchs from database. /// </summary> /// <param name="errorMessage"></param> /// <returns></returns> private List<MatchViewModel> GetMatchs(out string errorMessage) { Facade facade = new Facade(); return facade.MatchsGetAll(out errorMessage); } /// <summary> /// Method to load players in dropdown. /// </summary> /// <param name="lstPlayers"></param> private void LoadPlayers(List<PlayerViewModel> lstPlayers) { ddlPlayers.DataSource = lstPlayers; ddlPlayers.DataTextField = "LastName"; ddlPlayers.DataValueField = "PlayerID"; ddlPlayers.DataBind(); ddlPlayers.Items.Insert(0, new ListItem("---- Select Player -----", "-1")); } /// <summary> /// Method to get all the players from database. /// </summary> /// <param name="errorMessage"></param> /// <returns></returns> private List<PlayerViewModel> GetPlayers(out string errorMessage) { Facade facade = new Facade(); return facade.PlayersGetAll(out errorMessage); } /// <summary> /// Method to change current sort direction. /// </summary> /// <param name="currentSortDirection"></param> private void ChangeCurrentSortDirection(string currentSortDirection) { if (currentSortDirection == "DESC") { gvScoreboard.Attributes["CurrentSortDirection"] = "ASC"; } else { gvScoreboard.Attributes["CurrentSortDirection"] = "DESC"; } } /// <summary> /// Method to get sorted scoreboard data. /// </summary> /// <param name="errorMessage"></param> /// <param name="sortDirection"></param> /// <param name="lstPoints"></param> /// <returns></returns> private List<PointViewModel> GetSortedScoreboardData(out string errorMessage, string sortExpression, string currentSortDirection, List<PointViewModel> lstPoints) { errorMessage = string.Empty; List<PointViewModel> lstSortedPoints = new List<PointViewModel>(); switch (sortExpression) { case "FirstName": lstSortedPoints = this.SortScoreboardByFirstName(currentSortDirection, lstPoints); break; case "LastName": lstSortedPoints = this.SortScoreboardByLastName(currentSortDirection, lstPoints); break; case "TotalPoints": lstSortedPoints = this.SortScoreboardByTotalPoints(currentSortDirection, lstPoints); break; default: break; } return lstSortedPoints; } /// <summary> /// Method to sort scoreboard data by total points of players. /// </summary> /// <param name="currentSortDirection"></param> /// <param name="lstPoints"></param> /// <returns></returns> private List<PointViewModel> SortScoreboardByTotalPoints(string currentSortDirection, List<PointViewModel> lstPoints) { List<PointViewModel> lstSortedPoints = new List<PointViewModel>(); switch (currentSortDirection) { case "ASC": lstSortedPoints = lstPoints.OrderBy(p => p.TotalPoints).ToList<PointViewModel>(); break; case "DESC": lstSortedPoints = lstPoints.OrderByDescending(p => p.TotalPoints).ToList<PointViewModel>(); break; default: lstSortedPoints = lstPoints.OrderByDescending(p => p.TotalPoints).ToList<PointViewModel>(); break; } return lstSortedPoints; } /// <summary> /// Method to sort scoreboard data by last name. /// </summary> /// <param name="currentSortDirection"></param> /// <param name="lstPoints"></param> /// <returns></returns> private List<PointViewModel> SortScoreboardByLastName(string currentSortDirection, List<PointViewModel> lstPoints) { List<PointViewModel> lstSortedPoints = new List<PointViewModel>(); switch (currentSortDirection) { case "ASC": lstSortedPoints = lstPoints.OrderBy(p => p.LastName).ToList<PointViewModel>(); break; case "DESC": lstSortedPoints = lstPoints.OrderByDescending(p => p.LastName).ToList<PointViewModel>(); break; default: lstSortedPoints = lstPoints.OrderBy(p => p.LastName).ToList<PointViewModel>(); break; } return lstSortedPoints; } /// <summary> /// Method to sort scoreboard data by first name. /// </summary> /// <param name="currentSortDirection"></param> /// <param name="lstPoints"></param> /// <returns></returns> private List<PointViewModel> SortScoreboardByFirstName(string currentSortDirection, List<PointViewModel> lstPoints) { List<PointViewModel> lstSortedPoints = new List<PointViewModel>(); switch (currentSortDirection) { case "ASC": lstSortedPoints = lstPoints.OrderBy(p => p.FirstName).ToList<PointViewModel>(); break; case "DESC": lstSortedPoints = lstPoints.OrderByDescending(p => p.FirstName).ToList<PointViewModel>(); break; default: lstSortedPoints = lstPoints.OrderBy(p => p.FirstName).ToList<PointViewModel>(); break; } return lstSortedPoints; } /// <summary> /// Method to load scoreboard data. /// </summary> /// <param name="lstPoints"></param> private void LoadScoreboardData(List<PointViewModel> lstPoints) { gvScoreboard.DataSource = lstPoints; gvScoreboard.DataBind(); } /// <summary> /// Method to get points of all players. /// </summary> /// <param name="errorMessage"></param> /// <returns></returns> private List<PointViewModel> GetPoints(out string errorMessage) { Facade facade = new Facade(); return facade.PointsGetAll(out errorMessage); } #endregion } }
33.903941
169
0.555394
[ "Apache-2.0" ]
attiqislam/ScoreboardManager
ScoreboardManager.WebForms/Default.aspx.cs
13,767
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 16.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.NotEqual.Complete.NullableByte.Double{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Byte>; using T_DATA2 =System.Double; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__01__VV public static class TestSet_504__param__01__VV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001__less() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ vv2); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001__less //----------------------------------------------------------------------- [Test] public static void Test_002__equal() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002__equal //----------------------------------------------------------------------- [Test] public static void Test_003__greater() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=3; var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ vv2); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_003__greater //----------------------------------------------------------------------- [Test] public static void Test_101__less() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_101__less //----------------------------------------------------------------------- [Test] public static void Test_102__equal() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ vv2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_102__equal //----------------------------------------------------------------------- [Test] public static void Test_103__greater() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=3; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_103__greater //----------------------------------------------------------------------- [Test] public static void Test_ZA01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ != /*}OP*/ vv2); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA01NV //----------------------------------------------------------------------- [Test] public static void Test_ZA02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => vv1 /*OP{*/ != /*}OP*/ ((T_DATA2)vv2__null_obj)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA02VN //----------------------------------------------------------------------- [Test] public static void Test_ZA03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ != /*}OP*/ ((T_DATA2)vv2__null_obj)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA03NN //----------------------------------------------------------------------- [Test] public static void Test_ZB01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ != /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB01NV //----------------------------------------------------------------------- [Test] public static void Test_ZB02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ != /*}OP*/ ((T_DATA2)vv2__null_obj))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB02VN //----------------------------------------------------------------------- [Test] public static void Test_ZB03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ != /*}OP*/ ((T_DATA2)vv2__null_obj))); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB03NN };//class TestSet_504__param__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.NotEqual.Complete.NullableByte.Double
22.772727
135
0.521188
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/NotEqual/Complete/NullableByte/Double/TestSet_504__param__01__VV.cs
13,028
C#
namespace PiCar { internal interface IDeviceInfo { string GetName(); } }
11.75
34
0.585106
[ "MIT" ]
julieisdead/PiCar
PiCar/PiCar/PiCar/Dependancies/IDeviceINfo.cs
96
C#
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; namespace SharpMath.Plotting.Functions { public interface IRangedPlotFunction : IPlotFunction { double XMin { get; } double XMax { get; } } }
14.863636
54
0.651376
[ "MIT" ]
mortenbakkedal/SharpMath
SharpMath/Plotting/Functions/IRangedPlotFunction.cs
327
C#
// // SpinButtonTests.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace Xwt { public class SpinButtonTests: WidgetTests { public override Widget CreateWidget () { return new SpinButton (); } } }
34.74359
80
0.746125
[ "MIT" ]
Bert1974/xwt
Test/SpinButtonTests.cs
1,355
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using CDR.Logging; namespace DiscogsXML2MySQL { public class XMLRelease { // ----------------------------------------------------------------------------------------------------------- private static int SERIAL_FORMAT_ID = 0; private static int SERIAL_TRACK_ID = 0; // must self generate! private static StreamWriter swRELEASE = null; private static StreamWriter swIMAGE = null; private static StreamWriter swRELEASE_ARTIST = null; private static StreamWriter swRELEASE_GENRE = null; private static StreamWriter swRELEASE_STYLE = null; private static StreamWriter swFORMAT = null; private static StreamWriter swFORMAT_DESCRIPTION = null; private static StreamWriter swRELEASE_LABEL = null; private static StreamWriter swTRACK = null; private static StreamWriter swTRACK_ARTIST = null; private static StreamWriter swIDENTIFIER = null; private static StreamWriter swRELEASE_VIDEO = null; private static StreamWriter swCOMPANY = null; // ----------------------------------------------------------------------------------------------------------- #region Data definition public int RELEASE_ID = -1; public int? MASTER_ID = null; public bool IS_MAIN_RELEASE = false; public string STATUS = ""; public string TITLE = ""; public string COUNTRY = ""; public DateTime RELEASED = DateTime.MinValue; public string NOTES = ""; public string DATA_QUALITY = ""; public List<Image> IMAGES = new List<Image>(); public List<Artist> ARTISTS = new List<Artist>(); public List<string> GENRES = new List<string>(); public List<string> STYLES = new List<string>(); public List<Format> FORMATS = new List<Format>(); public List<ReleaseLabel> RELEASELABELS = new List<ReleaseLabel>(); public List<Track> TRACKS = new List<Track>(); public List<Identifier> IDENTIFIERS = new List<Identifier>(); public List<Video> VIDEOS = new List<Video>(); public List<Company> COMPANIES = new List<Company>(); public class Image { public int HEIGHT = -1; public int WIDTH = -1; public string TYPE = ""; public string URI = ""; public string URI150 = ""; } public class Format { public int FORMAT_ID = -1; // must self generate! public string FORMAT_NAME = ""; public string FORMAT_TEXT = ""; public int QUANTITY = 1; public List<FormatDescription> FORMAT_DESCRIPTIONS = new List<FormatDescription>(); public class FormatDescription { public string DESCRIPTION = ""; public int DESCRIPTION_ORDER = 1; } } public class ReleaseLabel { public int LABEL_ID = -1; public string NAME = ""; public string CATNO = ""; } public class Track { public int TRACK_ID = -1; // must self generate! public int? MAIN_TRACK_ID = null; // if not null points to track where this is a subtrack of otherwise null public bool HAS_SUBTRACKS = false; public bool IS_SUBTRACK = false; public int TRACKNUMBER = 1; public string TITLE = ""; public string SUBTRACK_TITLE = ""; public string POSITION = ""; public int DURATION_IN_SEC = 0; public List<Artist> ARTISTS = new List<Artist>(); } public class Identifier { public string DESCRIPTION = ""; public string TYPE = ""; public string VALUE = ""; } public class Video { public bool EMBED = false; public int DURATION_IN_SEC = 0; public string SRC = ""; public string TITLE = ""; public string DESCRIPTION = ""; } public class Company { public int COMPANY_ID = -1; public string NAME = ""; public string CATNO = ""; public int ENTITY_TYPE = 0; public string ENTITY_TYPE_NAME = ""; public string RESOURCE_URL = ""; } #endregion #region Parse XML public static XMLRelease ParseXML(XmlElement xRelease) { // ------------------------------------------------------------------------- System.Globalization.NumberFormatInfo nfi = null; System.Globalization.CultureInfo culture = null; nfi = new System.Globalization.CultureInfo("en-US", false).NumberFormat; nfi.CurrencySymbol = "€"; nfi.CurrencyDecimalDigits = 2; nfi.CurrencyDecimalSeparator = "."; nfi.NumberGroupSeparator = ""; nfi.NumberDecimalSeparator = "."; culture = new System.Globalization.CultureInfo("en-US"); // ------------------------------------------------------------------------- XMLRelease release = new XMLRelease(); release.RELEASE_ID = Convert.ToInt32(xRelease.Attributes["id"].Value); release.STATUS = xRelease.Attributes["status"].Value; release.TITLE = xRelease["title"].InnerText; if (xRelease["country"] != null) { release.COUNTRY = xRelease["country"].InnerText; } if (xRelease["released"] != null) { string[] tmp = xRelease["released"].InnerText.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < tmp.Length; i++) { int v; if (int.TryParse(tmp[i], out v)) { if (v == 0) { tmp[i] = "01"; if (i == 0) { tmp[i] = "0001"; } } } else { tmp[i] = "01"; if (i == 0) { tmp[i] = "0001"; } } } switch (tmp.Length) { case 0: release.RELEASED = DateTime.Parse("0001-01-01"); break; case 1: DateTime.TryParse($"{tmp[0]}-01-01", out release.RELEASED); break; case 2: DateTime.TryParse($"{tmp[0]}-{tmp[1]}-01", out release.RELEASED); break; case 3: default: DateTime.TryParse($"{tmp[0]}-{tmp[1]}-{tmp[2]}", out release.RELEASED); break; } //switch } if (xRelease["notes"] != null) { release.NOTES = xRelease["notes"].InnerText; } release.MASTER_ID = null; release.IS_MAIN_RELEASE = false; if (xRelease["master_id"] != null) { release.MASTER_ID = Convert.ToInt32(xRelease["master_id"].InnerText); if (release.MASTER_ID == 0) { release.MASTER_ID = null; } release.IS_MAIN_RELEASE = (xRelease["master_id"].Attributes["is_main_release"].Value == "true"); } if (xRelease["data_quality"] != null) { release.DATA_QUALITY = xRelease["data_quality"].InnerText; } if (xRelease.GetElementsByTagName("images")[0] != null) { foreach (XmlNode xn in xRelease.GetElementsByTagName("images")[0].ChildNodes) { XmlElement xImage = (XmlElement)xn; Image image = new Image(); image.HEIGHT = Convert.ToInt32(xImage.Attributes["height"].Value); image.WIDTH = Convert.ToInt32(xImage.Attributes["width"].Value); image.TYPE = xImage.Attributes["type"].Value; image.URI = xImage.Attributes["uri"].Value; image.URI150 = xImage.Attributes["uri150"].Value; release.IMAGES.Add(image); } //foreach } release.ARTISTS = Artist.ParseArtists(xRelease); if (xRelease.GetElementsByTagName("genres")[0] != null) { foreach (XmlNode xn in xRelease.GetElementsByTagName("genres")[0].ChildNodes) { XmlElement xGenre = (XmlElement)xn; release.GENRES.Add(xGenre.InnerText); } //foreach } if (xRelease.GetElementsByTagName("styles")[0] != null) { foreach (XmlNode xn in xRelease.GetElementsByTagName("styles")[0].ChildNodes) { XmlElement xStyle = (XmlElement)xn; release.STYLES.Add(xStyle.InnerText); } //foreach } if (xRelease.GetElementsByTagName("formats")[0] != null) { foreach (XmlNode xn1 in xRelease.GetElementsByTagName("formats")[0].ChildNodes) { XmlElement xformat = (XmlElement)xn1; Format format = new Format(); XMLRelease.SERIAL_FORMAT_ID++; format.FORMAT_ID = XMLRelease.SERIAL_FORMAT_ID; format.FORMAT_NAME = xformat.Attributes["name"].Value; format.FORMAT_TEXT = xformat.Attributes["text"].Value; if (xformat.Attributes["qty"] != null) { int.TryParse(xformat.Attributes["qty"].Value, out format.QUANTITY); } if (xformat.GetElementsByTagName("descriptions")[0] != null) { int cnt = 1; foreach (XmlNode xn2 in xRelease.GetElementsByTagName("descriptions")[0].ChildNodes) { XmlElement xDescription = (XmlElement)xn2; Format.FormatDescription formatDescription = new Format.FormatDescription(); formatDescription.DESCRIPTION = xDescription.InnerText; formatDescription.DESCRIPTION_ORDER = cnt; format.FORMAT_DESCRIPTIONS.Add(formatDescription); cnt++; } //foreach } release.FORMATS.Add(format); } //foreach } if (xRelease.GetElementsByTagName("labels")[0] != null) { foreach (XmlNode xn in xRelease.GetElementsByTagName("labels")[0].ChildNodes) { XmlElement xLabel = (XmlElement)xn; ReleaseLabel releaseLabel = new ReleaseLabel(); releaseLabel.LABEL_ID = Convert.ToInt32(xLabel.Attributes["id"].Value); releaseLabel.NAME = xLabel.Attributes["name"].Value; releaseLabel.CATNO = xLabel.Attributes["catno"].Value; release.RELEASELABELS.Add(releaseLabel); } //foreach } if (xRelease.GetElementsByTagName("tracklist")[0] != null) { int cnt = 1; foreach (XmlNode xn in xRelease.GetElementsByTagName("tracklist")[0].ChildNodes) { XmlElement xTrack = (XmlElement)xn; if (xTrack["title"] != null) { Track track = new Track(); track.TRACKNUMBER = cnt; SERIAL_TRACK_ID++; track.TRACK_ID = SERIAL_TRACK_ID; track.POSITION = track.TRACKNUMBER.ToString(); if (xTrack["position"] != null) { track.POSITION = xTrack["position"].InnerText; } track.TITLE = xTrack["title"].InnerText; if (xTrack["duration"] != null) { track.DURATION_IN_SEC = ParseDuration(xTrack["duration"].InnerText); } track.ARTISTS = Artist.ParseArtists(xTrack); if (track.ARTISTS.Count == 0) { // Copy Artists from release album track.ARTISTS = Artist.Clone(release.ARTISTS); } // Only when there are no subtracks do we use the "main" track info release.TRACKS.Add(track); cnt++; // Are there sub tracks? (then we ignore the main track!) if (xTrack.GetElementsByTagName("sub_tracks")[0] != null) { track.HAS_SUBTRACKS = true; foreach (XmlNode xn2 in xTrack.GetElementsByTagName("sub_tracks")[0].ChildNodes) { XmlElement xSubTrack = (XmlElement)xn2; Track subTrack = new Track(); SERIAL_TRACK_ID++; subTrack.TRACK_ID = SERIAL_TRACK_ID; subTrack.MAIN_TRACK_ID = track.TRACK_ID; subTrack.TRACKNUMBER = cnt; subTrack.IS_SUBTRACK = true; subTrack.POSITION = subTrack.TRACKNUMBER.ToString(); if (xSubTrack["position"] != null) { subTrack.POSITION = xSubTrack["position"].InnerText; } subTrack.TITLE = track.TITLE + " / " + xSubTrack["title"].InnerText; subTrack.SUBTRACK_TITLE = xSubTrack["title"].InnerText; if (xSubTrack["duration"] != null) { subTrack.DURATION_IN_SEC = ParseDuration(xSubTrack["duration"].InnerText); } // I don't believe this exists for sub_tracks but it doesn't hurt subTrack.ARTISTS = Artist.ParseArtists(xSubTrack); if (subTrack.ARTISTS.Count == 0) { // Copy Artists from "Main" track album subTrack.ARTISTS = Artist.Clone(track.ARTISTS); } release.TRACKS.Add(subTrack); cnt++; } //foreach subtrack } } } //foreach } if (xRelease.GetElementsByTagName("identifiers")[0] != null) { foreach (XmlNode xn in xRelease.GetElementsByTagName("identifiers")[0].ChildNodes) { XmlElement xIdentifier = (XmlElement)xn; Identifier identifier = new Identifier(); if (xIdentifier.Attributes["value"] != null) { if (xIdentifier.Attributes["description"] != null) { identifier.DESCRIPTION = xIdentifier.Attributes["description"].Value; } if (xIdentifier.Attributes["type"] != null) { identifier.TYPE = xIdentifier.Attributes["type"].Value; } identifier.VALUE = xIdentifier.Attributes["value"].Value; release.IDENTIFIERS.Add(identifier); } } //foreach } if (xRelease.GetElementsByTagName("videos")[0] != null) { foreach (XmlNode xn in xRelease.GetElementsByTagName("videos")[0].ChildNodes) { XmlElement xVideo = (XmlElement)xn; Video video = new Video(); video.EMBED = (xVideo.Attributes["embed"].Value == "true"); video.DURATION_IN_SEC = Convert.ToInt32(xVideo.Attributes["duration"].Value); video.SRC = xVideo.Attributes["src"].Value; video.TITLE = xVideo["title"].InnerText; video.DESCRIPTION = xVideo["description"].InnerText; release.VIDEOS.Add(video); } //foreach } if (xRelease.GetElementsByTagName("companies")[0] != null) { foreach (XmlNode xn in xRelease.GetElementsByTagName("companies")[0].ChildNodes) { XmlElement xCompany = (XmlElement)xn; Company company = new Company(); company.COMPANY_ID = Convert.ToInt32(xCompany["id"].InnerText); company.NAME = xCompany["name"].InnerText; company.CATNO = xCompany["catno"].InnerText; company.ENTITY_TYPE = Convert.ToInt32(xCompany["entity_type"].InnerText); company.ENTITY_TYPE_NAME = xCompany["entity_type_name"].InnerText; company.RESOURCE_URL = xCompany["resource_url"].InnerText; release.COMPANIES.Add(company); } //foreach } return release; } /// <summary> /// returns duration in seconds /// </summary> private static int ParseDuration(string d) { if (d.Contains(":")) { string[] duration = d.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries); int min = 0; if (duration.Length >= 1) { int.TryParse(duration[0], out min); } int sec = 0; if (duration.Length >= 2) { int.TryParse(duration[1], out sec); } return min * 60 + sec; } return 0; } #endregion #region Export to file /// <summary> /// Write data to diffenrent tab seperated files, which kan be imported using local MySQL functions (this is way faster!) /// </summary> public void StoreInTAB() { if (swRELEASE == null) { CreateTABSeperatedFiles(); } string MASTER_ID = "\\N"; if (this.MASTER_ID != null) { MASTER_ID = this.MASTER_ID.ToString(); } string IS_MAIN_RELEASE = "0"; if (this.IS_MAIN_RELEASE) { IS_MAIN_RELEASE = "1"; } string notes = "\\N"; if (!string.IsNullOrEmpty(this.NOTES)) { notes = CDR.DB_Helper.EscapeMySQL(this.NOTES); } swRELEASE.WriteLine($"{this.RELEASE_ID}\t{MASTER_ID}\t{CDR.DB_Helper.EscapeMySQL(this.STATUS)}\t{CDR.DB_Helper.EscapeMySQL(this.TITLE)}\t" + $"{CDR.DB_Helper.EscapeMySQL(this.COUNTRY)}\t{this.RELEASED:yyyy-MM-dd}\t{notes}\t{CDR.DB_Helper.EscapeMySQL(this.DATA_QUALITY)}\t{IS_MAIN_RELEASE}"); foreach (Image image in this.IMAGES) { string uri = "\\N"; if (!string.IsNullOrEmpty(image.URI)) { uri = CDR.DB_Helper.EscapeMySQL(image.URI); } string uri150 = "\\N"; if (!string.IsNullOrEmpty(image.URI150)) { uri150 = CDR.DB_Helper.EscapeMySQL(image.URI150); } swIMAGE.WriteLine($"{this.RELEASE_ID}\t{image.HEIGHT}\t{image.WIDTH}\t{CDR.DB_Helper.EscapeMySQL(image.TYPE)}\t{uri}\t{uri150}"); } //foreach foreach (Artist artist in this.ARTISTS) { string EXTRA_ARTIST = "0"; if (artist.EXTRA_ARTIST) { EXTRA_ARTIST = "1"; } swRELEASE_ARTIST.WriteLine($"{this.RELEASE_ID}\t{artist.ARTIST_ID}\t{CDR.DB_Helper.EscapeMySQL(artist.ANV)}\t{CDR.DB_Helper.EscapeMySQL(artist.JOIN)}\t{CDR.DB_Helper.EscapeMySQL(artist.ROLE)}\t{CDR.DB_Helper.EscapeMySQL(artist.NAME)}\t{EXTRA_ARTIST}"); } //foreach foreach (Track track in this.TRACKS) { string MAIN_TRACK_ID = "\\N"; if (track.MAIN_TRACK_ID != null) { MAIN_TRACK_ID = track.MAIN_TRACK_ID.ToString(); } int HAS_SUBTRACKS = Convert.ToInt32(track.HAS_SUBTRACKS); int IS_SUBTRACK = Convert.ToInt32(track.IS_SUBTRACK); swTRACK.WriteLine($"{track.TRACK_ID}\t{this.RELEASE_ID}\t{MAIN_TRACK_ID}\t{HAS_SUBTRACKS}\t{IS_SUBTRACK}\t{track.TRACKNUMBER}\t{CDR.DB_Helper.EscapeMySQL(track.TITLE)}\t{CDR.DB_Helper.EscapeMySQL(track.SUBTRACK_TITLE)}\t{CDR.DB_Helper.EscapeMySQL(track.POSITION)}\t{track.DURATION_IN_SEC}"); foreach (Artist artist in track.ARTISTS) { string EXTRA_ARTIST = "0"; if (artist.EXTRA_ARTIST) { EXTRA_ARTIST = "1"; } swTRACK_ARTIST.WriteLine($"{track.TRACK_ID}\t{artist.ARTIST_ID}\t{CDR.DB_Helper.EscapeMySQL(artist.ANV)}\t{CDR.DB_Helper.EscapeMySQL(artist.JOIN)}\t{CDR.DB_Helper.EscapeMySQL(artist.ROLE)}\t{CDR.DB_Helper.EscapeMySQL(artist.NAME)}\t{EXTRA_ARTIST}"); } //foreach } //foreach foreach (string genre in this.GENRES) { swRELEASE_GENRE.WriteLine($"{this.RELEASE_ID}\t{CDR.DB_Helper.EscapeMySQL(genre)}"); } //foreach foreach (string style in this.STYLES) { swRELEASE_STYLE.WriteLine($"{this.RELEASE_ID}\t{CDR.DB_Helper.EscapeMySQL(style)}"); } //foreach foreach (Format format in this.FORMATS) { swFORMAT.WriteLine($"{format.FORMAT_ID}\t{this.RELEASE_ID}\t{CDR.DB_Helper.EscapeMySQL(format.FORMAT_NAME)}\t{CDR.DB_Helper.EscapeMySQL(format.FORMAT_TEXT)}\t{format.QUANTITY}"); foreach (Format.FormatDescription formatDescription in format.FORMAT_DESCRIPTIONS) { swFORMAT_DESCRIPTION.WriteLine($"{format.FORMAT_ID}\t{CDR.DB_Helper.EscapeMySQL(formatDescription.DESCRIPTION)}\t{CDR.DB_Helper.EscapeMySQL(formatDescription.DESCRIPTION_ORDER)}"); } //foreach } //foreach foreach (ReleaseLabel releaseLabel in this.RELEASELABELS) { swRELEASE_LABEL.WriteLine($"{this.RELEASE_ID}\t{releaseLabel.LABEL_ID}\t{CDR.DB_Helper.EscapeMySQL(releaseLabel.CATNO)}"); } //foreach foreach (Identifier identifier in this.IDENTIFIERS) { swIDENTIFIER.WriteLine($"{this.RELEASE_ID}\t{CDR.DB_Helper.EscapeMySQL(identifier.DESCRIPTION)}\t{CDR.DB_Helper.EscapeMySQL(identifier.TYPE)}\t{CDR.DB_Helper.EscapeMySQL(identifier.VALUE)}"); } //foreach foreach (Video video in this.VIDEOS) { swRELEASE_VIDEO.WriteLine($"{this.RELEASE_ID}\t{Convert.ToInt16(video.EMBED)}\t{video.DURATION_IN_SEC}\t{CDR.DB_Helper.EscapeMySQL(video.SRC)}\t{CDR.DB_Helper.EscapeMySQL(video.TITLE)}\t{CDR.DB_Helper.EscapeMySQL(video.DESCRIPTION)}"); } //foreach foreach (Company company in this.COMPANIES) { swCOMPANY.WriteLine($"{company.COMPANY_ID}\t{this.RELEASE_ID}\t{CDR.DB_Helper.EscapeMySQL(company.NAME)}\t{CDR.DB_Helper.EscapeMySQL(company.CATNO)}\t{company.ENTITY_TYPE}\t{CDR.DB_Helper.EscapeMySQL(company.ENTITY_TYPE_NAME)}\t{CDR.DB_Helper.EscapeMySQL(company.RESOURCE_URL)}"); } //foreach } public void CreateTABSeperatedFiles() { if (swRELEASE == null) { CloseTABSeperatedFiles(); Encoding utf8WithoutBom = new UTF8Encoding(false); swRELEASE = new System.IO.StreamWriter(@"RELEASE.TAB", false, utf8WithoutBom); swIMAGE = new System.IO.StreamWriter(@"RELEASE-IMAGE.TAB", false, utf8WithoutBom); swRELEASE_ARTIST = new System.IO.StreamWriter(@"RELEASE-ARTIST.TAB", false, utf8WithoutBom); swRELEASE_GENRE = new System.IO.StreamWriter(@"RELEASE-GENRE.TAB", false, utf8WithoutBom); swRELEASE_STYLE = new System.IO.StreamWriter(@"RELEASE-STYLE.TAB", false, utf8WithoutBom); swTRACK_ARTIST = new System.IO.StreamWriter(@"TRACK-ARTIST.TAB", false, utf8WithoutBom); swFORMAT = new System.IO.StreamWriter(@"FORMAT.TAB", false, utf8WithoutBom); swFORMAT_DESCRIPTION = new System.IO.StreamWriter(@"FORMAT-DESCRIPTION.TAB", false, utf8WithoutBom); swRELEASE_LABEL = new System.IO.StreamWriter(@"RELEASE-LABEL.TAB", false, utf8WithoutBom); swTRACK = new System.IO.StreamWriter(@"TRACK.TAB", false, utf8WithoutBom); swIDENTIFIER = new System.IO.StreamWriter(@"IDENTIFIER.TAB", false, utf8WithoutBom); swRELEASE_VIDEO = new System.IO.StreamWriter(@"RELEASE-VIDEO.TAB", false, utf8WithoutBom); swCOMPANY = new System.IO.StreamWriter(@"COMPANY.TAB", false, utf8WithoutBom); GC.WaitForPendingFinalizers(); } } public static void CloseTABSeperatedFiles() { CloseStreamWriter(ref swRELEASE); CloseStreamWriter(ref swIMAGE); CloseStreamWriter(ref swRELEASE_ARTIST); CloseStreamWriter(ref swRELEASE_GENRE); CloseStreamWriter(ref swRELEASE_STYLE); CloseStreamWriter(ref swTRACK_ARTIST); CloseStreamWriter(ref swFORMAT); CloseStreamWriter(ref swFORMAT_DESCRIPTION); CloseStreamWriter(ref swRELEASE_LABEL); CloseStreamWriter(ref swTRACK); CloseStreamWriter(ref swIDENTIFIER); CloseStreamWriter(ref swRELEASE_VIDEO); CloseStreamWriter(ref swCOMPANY); } private static void CloseStreamWriter(ref StreamWriter sw) { if (sw != null) { sw.Close(); sw = null; } } /// <summary> /// Remove tab files, to save space /// </summary> public static void CleanUpConvertedReleasesFiles(string tabFolder) { DeleteFile(Path.Combine(tabFolder, "RELEASE.TAB")); DeleteFile(Path.Combine(tabFolder, "RELEASE-IMAGE.TAB")); DeleteFile(Path.Combine(tabFolder, "RELEASE-ARTIST.TAB")); DeleteFile(Path.Combine(tabFolder, "RELEASE-GENRE.TAB")); DeleteFile(Path.Combine(tabFolder, "RELEASE-STYLE.TAB")); DeleteFile(Path.Combine(tabFolder, "FORMAT.TAB")); DeleteFile(Path.Combine(tabFolder, "FORMAT-DESCRIPTION.TAB")); DeleteFile(Path.Combine(tabFolder, "RELEASE-LABEL.TAB")); DeleteFile(Path.Combine(tabFolder, "TRACK.TAB")); DeleteFile(Path.Combine(tabFolder, "TRACK-ARTIST.TAB")); DeleteFile(Path.Combine(tabFolder, "IDENTIFIER.TAB")); DeleteFile(Path.Combine(tabFolder, "RELEASE-VIDEO.TAB")); DeleteFile(Path.Combine(tabFolder, "COMPANY.TAB")); } private static void DeleteFile(string filename) { if (File.Exists(filename)) { try { File.Delete(filename); } catch { } } } #endregion #region Import into MySQL public static void ImportReleasesData(string tabFolder) { using (MySql.Data.MySqlClient.MySqlConnection conn = CDR.DB_Helper.NewMySQLConnection()) { CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "RELEASE.TAB"), "RELEASE", "RELEASE_ID, MASTER_ID, STATUS, TITLE, COUNTRY, RELEASED, NOTES, DATA_QUALITY, IS_MAIN_RELEASE", ""); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "RELEASE-IMAGE.TAB"), "IMAGE", "RELEASE_ID, HEIGHT, WIDTH, `TYPE`, URI, URI150", "IMAGE_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "RELEASE-ARTIST.TAB"), "RELEASE_ARTIST", "RELEASE_ID, ARTIST_ID, ANV, `JOIN`, ROLE, `NAME`, EXTRA_ARTIST", "RELEASE_ARTIST_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "RELEASE-GENRE.TAB"), "GENRE", "RELEASE_ID, GENRE_NAME", "GENRE_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "RELEASE-STYLE.TAB"), "STYLE", "RELEASE_ID, STYLE_NAME", "STYLE_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "FORMAT.TAB"), "FORMAT", "FORMAT_ID, RELEASE_ID, FORMAT_NAME, FORMAT_TEXT, QUANTITY", ""); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "FORMAT-DESCRIPTION.TAB"), "FORMAT_DESCRIPTION", "FORMAT_ID, `DESCRIPTION`, DESCRIPTION_ORDER", "FORMAT_DESCRIPTION_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "RELEASE-LABEL.TAB"), "RELEASE_LABEL", "RELEASE_ID, LABEL_ID, CATNO", "RELEASE_LABEL_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "TRACK.TAB"), "TRACK", "TRACK_ID, RELEASE_ID, MAIN_TRACK_ID, HAS_SUBTRACKS, IS_SUBTRACK, TRACKNUMBER, TITLE, SUBTRACK_TITLE, POSITION, DURATION_IN_SEC", ""); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "TRACK-ARTIST.TAB"), "TRACK_ARTIST", "TRACK_ID, ARTIST_ID, ANV, `JOIN`, ROLE, `NAME`, EXTRA_ARTIST", "TRACK_ARTIST_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "IDENTIFIER.TAB"), "IDENTIFIER", "RELEASE_ID, `DESCRIPTION`, TYPE, VALUE", "IDENTIFIER_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "RELEASE-VIDEO.TAB"), "VIDEO", "RELEASE_ID, EMBED, DURATION_IN_SEC, SRC, TITLE, `DESCRIPTION`", "VIDEO_ID"); CDR.DB_Helper.LOAD_DATA_LOCAL_INFILE(conn, Path.Combine(tabFolder, "COMPANY.TAB"), "COMPANY", "COMPANY_ID, RELEASE_ID, `NAME`, CATNO, ENTITY_TYPE, ENTITY_TYPE_NAME, RESOURCE_URL", ""); } //using } #endregion public static void Clear() { SERIAL_FORMAT_ID = 0; SERIAL_TRACK_ID = 0; CloseTABSeperatedFiles(); } } }
45.458924
307
0.520346
[ "MIT" ]
nelemans1971/Discogs
DiscogsXML2MySQL/XMLEntities/XMLRelease.cs
32,098
C#
using Met.Core.Proto; using System.Collections.Generic; namespace Met.Core.Extensions { public static class TlvDictionaryExtensions { public static Tlv TryGetTlv(this Dictionary<TlvType, List<Tlv>> dict, TlvType type) { var list = default(List<Tlv>); if (dict.TryGetValue(type, out list) && list.Count > 0) { return list[0]; } return null; } public static byte[] TryGetTlvValueAsRaw(this Dictionary<TlvType, List<Tlv>> dict, TlvType type, byte[] def = null) { var list = default(List<Tlv>); if (dict.TryGetValue(type, out list) && list.Count > 0) { return list[0].ValueAsRaw(); } return def; } public static uint TryGetTlvValueAsDword(this Dictionary<TlvType, List<Tlv>> dict, TlvType type, uint def = 0) { var list = default(List<Tlv>); if (dict.TryGetValue(type, out list) && list.Count > 0) { return list[0].ValueAsDword(); } return def; } public static bool TryGetTlvValueAsBool(this Dictionary<TlvType, List<Tlv>> dict, TlvType type, bool def = false) { var list = default(List<Tlv>); if (dict.TryGetValue(type, out list) && list.Count > 0) { return list[0].ValueAsBool(); } return def; } public static ulong TryGetTlvValueAsQword(this Dictionary<TlvType, List<Tlv>> dict, TlvType type, ulong def = 0) { var list = default(List<Tlv>); if (dict.TryGetValue(type, out list) && list.Count > 0) { return list[0].ValueAsQword(); } return def; } public static string TryGetTlvValueAsString(this Dictionary<TlvType, List<Tlv>> dict, TlvType type, string def = "") { var list = default(List<Tlv>); if (dict.TryGetValue(type, out list) && list.Count > 0) { return list[0].ValueAsString(); } return def; } } }
30.72
125
0.50434
[ "Apache-2.0" ]
IMULMUL/clr-meterpreter
src/metsrv.net35/Extensions/TlvDictionaryExtensions.cs
2,306
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 mediaconnect-2018-11-14.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.MediaConnect.Model { /// <summary> /// The settings for attaching a VPC interface to an output. /// </summary> public partial class VpcInterfaceAttachment { private string _vpcInterfaceName; /// <summary> /// Gets and sets the property VpcInterfaceName. The name of the VPC interface to use /// for this output. /// </summary> public string VpcInterfaceName { get { return this._vpcInterfaceName; } set { this._vpcInterfaceName = value; } } // Check to see if VpcInterfaceName property is set internal bool IsSetVpcInterfaceName() { return this._vpcInterfaceName != null; } } }
30.203704
110
0.676272
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/MediaConnect/Generated/Model/VpcInterfaceAttachment.cs
1,631
C#
namespace MCal.CalendarUI { public interface IDateKeeper { void AddDays(int days); void AddMonths(short monthIncr); short DayOfWeek{ get; } int Day { get; } int Month { get; } int Year{ get; } void ResetToFirstDay(); } }
22.230769
40
0.553633
[ "MIT" ]
kbrock84/MCal
MCal/CalendarUI/IDateKeeper.cs
291
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; namespace Maestro.Common.Model { public abstract class ModelBase : INotifyPropertyChanged, INotifyDataErrorInfo { public event PropertyChangedEventHandler PropertyChanged; protected bool Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; OnChanging?.Invoke(new PropertyChange(this, propertyName, typeof(T), field, value)); field = value; NotifyChange(); return true; } public static void Add<T>(ObservableCollection<T> list, T value) { list.Add(value); OnChanging?.Invoke(new ListAddition(list, typeof(T), value)); } public static void Remove<T>(ObservableCollection<T> list, T value) { list.Remove(value); OnChanging?.Invoke(new ListSuppression(list, typeof(T), value)); } public IEnumerable GetErrors(string propertyName) { foreach (var e in Errors()) if (e.Item1 == propertyName) yield return e.Item2; } public static Dictionary<object, string> ListNames { get; } = new Dictionary<object, string>(); public bool HasErrors => Errors().Any(); public struct PropertyChange { public PropertyChange(ModelBase origin, string propertyName, Type type, object previousValue, object newValue) { Origin = origin; PropertyName = propertyName; Type = type; PreviousValue = previousValue; NewValue = newValue; } public ModelBase Origin { get; } public string PropertyName { get; } public Type Type { get; } public object PreviousValue { get; } public object NewValue { get; } public void Undo() { Origin.GetType().GetProperty(PropertyName, Type).SetValue(Origin, PreviousValue); } public void Redo() { Origin.GetType().GetProperty(PropertyName, Type).SetValue(Origin, NewValue); } } public struct ListAddition { public object List; public Type Type; public object Added; public ListAddition(object list, Type type, object added) { List = list; Type = type; Added = added; } public ListSuppression Invert() => new ListSuppression(List, Type, Added); public void Undo() { List.GetType().GetMethod("Remove", new[] { Type }).Invoke(List, new[] { Added }); ; OnChanging?.Invoke(new ListSuppression(List, Type, Added)); } public string ListName() => ListNames.ContainsKey(List) ? ListNames[List] : $"{List.GetType().Name}<{Type.Name}>"; } public struct ListSuppression { public object List; public Type Type; public object Suppressed; public ListSuppression(object list, Type type, object suppressed) { List = list; Type = type; Suppressed = suppressed; } public ListAddition Invert() => new ListAddition(List, Type, Suppressed); public void Undo() { List.GetType().GetMethod("Add", new[] { Type }).Invoke(List, new[] { Suppressed }); ; OnChanging?.Invoke(new ListAddition(List, Type, Suppressed)); } public string ListName() => ListNames.ContainsKey(List) ? ListNames[List] : $"{List.GetType().Name}<{Type.Name}>"; } public delegate void OnChangingEventHandler(object change); public static event OnChangingEventHandler OnChanging; public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; protected abstract IEnumerable<(string, object)> Errors(); protected void NotifyChange(string propertyName = null) { if (string.IsNullOrEmpty(propertyName)) foreach (var p in GetType().GetProperties()) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(p.Name)); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p.Name)); } else { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public abstract IEnumerable<string> TranslatableResources(); } }
33.893333
126
0.56786
[ "MIT" ]
Otatiaro/Maestro
Maestro.Common/Model/ModelBase.cs
5,086
C#
#region License /* * 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. */ #endregion using System.IO; using System.Threading.Tasks; namespace Gremlin.Net.Structure.IO.GraphBinary.Types { /// <summary> /// Base class for serialization of types that don't contain type specific information only {type_code}, /// {value_flag} and {value}. /// </summary> /// <typeparam name="T">The supported type.</typeparam> public abstract class SimpleTypeSerializer<T> : ITypeSerializer { /// <summary> /// Initializes a new instance of the <see cref="SimpleTypeSerializer{T}" /> class. /// </summary> protected SimpleTypeSerializer(DataType dataType) { DataType = dataType; } /// <inheritdoc /> public DataType DataType { get; } /// <inheritdoc /> public async Task WriteAsync(object value, Stream stream, GraphBinaryWriter writer) { await WriteValueAsync((T) value, stream, writer, true).ConfigureAwait(false); } /// <inheritdoc /> public async Task WriteValueAsync(object value, Stream stream, GraphBinaryWriter writer, bool nullable) { if (value == null) { if (!nullable) { throw new IOException("Unexpected null value when nullable is false"); } await writer.WriteValueFlagNullAsync(stream).ConfigureAwait(false); return; } if (nullable) { await writer.WriteValueFlagNoneAsync(stream).ConfigureAwait(false); } await WriteValueAsync((T) value, stream, writer).ConfigureAwait(false); } /// <summary> /// Writes a non-nullable value into a stream. /// </summary> /// <param name="value">The value to write.</param> /// <param name="stream">The stream to write to.</param> /// <param name="writer">A <see cref="GraphBinaryWriter"/>.</param> /// <returns>A task that represents the asynchronous write operation.</returns> protected abstract Task WriteValueAsync(T value, Stream stream, GraphBinaryWriter writer); /// <inheritdoc /> public async Task<object> ReadAsync(Stream stream, GraphBinaryReader reader) { return await ReadValueAsync(stream, reader, true).ConfigureAwait(false); } /// <inheritdoc /> public async Task<object> ReadValueAsync(Stream stream, GraphBinaryReader reader, bool nullable) { if (nullable) { var valueFlag = await stream.ReadByteAsync().ConfigureAwait(false); if ((valueFlag & 1) == 1) { return null; } } return await ReadValueAsync(stream, reader).ConfigureAwait(false); } /// <summary> /// Reads a non-nullable value according to the type format. /// </summary> /// <param name="stream">The GraphBinary data to parse.</param> /// <param name="reader">A <see cref="GraphBinaryReader"/>.</param> /// <returns>The read value.</returns> protected abstract Task<T> ReadValueAsync(Stream stream, GraphBinaryReader reader); } }
36.442478
111
0.612919
[ "Apache-2.0" ]
CarlSample/tinkerpop
gremlin-dotnet/src/Gremlin.Net/Structure/IO/GraphBinary/Types/SimpleTypeSerializer.cs
4,120
C#
using System; using CompanyName.MyMeetings.Modules.Payments.Domain.SeedWork; namespace CompanyName.MyMeetings.Modules.Payments.Domain.Subscriptions { public class SubscriptionId : AggregateId<Subscription> { public SubscriptionId(Guid value) : base(value) { } } }
25.083333
70
0.717608
[ "MIT" ]
AndreiGanichev/modular-monolith-with-ddd
src/Modules/Payments/Domain/Subscriptions/SubscriptionId.cs
303
C#
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.AIPlatform.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedPipelineServiceClientSnippets { /// <summary>Snippet for CreateTrainingPipeline</summary> public void CreateTrainingPipelineRequestObject() { // Snippet: CreateTrainingPipeline(CreateTrainingPipelineRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), TrainingPipeline = new TrainingPipeline(), }; // Make the request TrainingPipeline response = pipelineServiceClient.CreateTrainingPipeline(request); // End snippet } /// <summary>Snippet for CreateTrainingPipelineAsync</summary> public async Task CreateTrainingPipelineRequestObjectAsync() { // Snippet: CreateTrainingPipelineAsync(CreateTrainingPipelineRequest, CallSettings) // Additional: CreateTrainingPipelineAsync(CreateTrainingPipelineRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) CreateTrainingPipelineRequest request = new CreateTrainingPipelineRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), TrainingPipeline = new TrainingPipeline(), }; // Make the request TrainingPipeline response = await pipelineServiceClient.CreateTrainingPipelineAsync(request); // End snippet } /// <summary>Snippet for CreateTrainingPipeline</summary> public void CreateTrainingPipeline() { // Snippet: CreateTrainingPipeline(string, TrainingPipeline, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; TrainingPipeline trainingPipeline = new TrainingPipeline(); // Make the request TrainingPipeline response = pipelineServiceClient.CreateTrainingPipeline(parent, trainingPipeline); // End snippet } /// <summary>Snippet for CreateTrainingPipelineAsync</summary> public async Task CreateTrainingPipelineAsync() { // Snippet: CreateTrainingPipelineAsync(string, TrainingPipeline, CallSettings) // Additional: CreateTrainingPipelineAsync(string, TrainingPipeline, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; TrainingPipeline trainingPipeline = new TrainingPipeline(); // Make the request TrainingPipeline response = await pipelineServiceClient.CreateTrainingPipelineAsync(parent, trainingPipeline); // End snippet } /// <summary>Snippet for CreateTrainingPipeline</summary> public void CreateTrainingPipelineResourceNames() { // Snippet: CreateTrainingPipeline(LocationName, TrainingPipeline, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); TrainingPipeline trainingPipeline = new TrainingPipeline(); // Make the request TrainingPipeline response = pipelineServiceClient.CreateTrainingPipeline(parent, trainingPipeline); // End snippet } /// <summary>Snippet for CreateTrainingPipelineAsync</summary> public async Task CreateTrainingPipelineResourceNamesAsync() { // Snippet: CreateTrainingPipelineAsync(LocationName, TrainingPipeline, CallSettings) // Additional: CreateTrainingPipelineAsync(LocationName, TrainingPipeline, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); TrainingPipeline trainingPipeline = new TrainingPipeline(); // Make the request TrainingPipeline response = await pipelineServiceClient.CreateTrainingPipelineAsync(parent, trainingPipeline); // End snippet } /// <summary>Snippet for GetTrainingPipeline</summary> public void GetTrainingPipelineRequestObject() { // Snippet: GetTrainingPipeline(GetTrainingPipelineRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) GetTrainingPipelineRequest request = new GetTrainingPipelineRequest { TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"), }; // Make the request TrainingPipeline response = pipelineServiceClient.GetTrainingPipeline(request); // End snippet } /// <summary>Snippet for GetTrainingPipelineAsync</summary> public async Task GetTrainingPipelineRequestObjectAsync() { // Snippet: GetTrainingPipelineAsync(GetTrainingPipelineRequest, CallSettings) // Additional: GetTrainingPipelineAsync(GetTrainingPipelineRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) GetTrainingPipelineRequest request = new GetTrainingPipelineRequest { TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"), }; // Make the request TrainingPipeline response = await pipelineServiceClient.GetTrainingPipelineAsync(request); // End snippet } /// <summary>Snippet for GetTrainingPipeline</summary> public void GetTrainingPipeline() { // Snippet: GetTrainingPipeline(string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/trainingPipelines/[TRAINING_PIPELINE]"; // Make the request TrainingPipeline response = pipelineServiceClient.GetTrainingPipeline(name); // End snippet } /// <summary>Snippet for GetTrainingPipelineAsync</summary> public async Task GetTrainingPipelineAsync() { // Snippet: GetTrainingPipelineAsync(string, CallSettings) // Additional: GetTrainingPipelineAsync(string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/trainingPipelines/[TRAINING_PIPELINE]"; // Make the request TrainingPipeline response = await pipelineServiceClient.GetTrainingPipelineAsync(name); // End snippet } /// <summary>Snippet for GetTrainingPipeline</summary> public void GetTrainingPipelineResourceNames() { // Snippet: GetTrainingPipeline(TrainingPipelineName, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) TrainingPipelineName name = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"); // Make the request TrainingPipeline response = pipelineServiceClient.GetTrainingPipeline(name); // End snippet } /// <summary>Snippet for GetTrainingPipelineAsync</summary> public async Task GetTrainingPipelineResourceNamesAsync() { // Snippet: GetTrainingPipelineAsync(TrainingPipelineName, CallSettings) // Additional: GetTrainingPipelineAsync(TrainingPipelineName, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) TrainingPipelineName name = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"); // Make the request TrainingPipeline response = await pipelineServiceClient.GetTrainingPipelineAsync(name); // End snippet } /// <summary>Snippet for ListTrainingPipelines</summary> public void ListTrainingPipelinesRequestObject() { // Snippet: ListTrainingPipelines(ListTrainingPipelinesRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) ListTrainingPipelinesRequest request = new ListTrainingPipelinesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", ReadMask = new FieldMask(), }; // Make the request PagedEnumerable<ListTrainingPipelinesResponse, TrainingPipeline> response = pipelineServiceClient.ListTrainingPipelines(request); // Iterate over all response items, lazily performing RPCs as required foreach (TrainingPipeline item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTrainingPipelinesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TrainingPipeline item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TrainingPipeline> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TrainingPipeline item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTrainingPipelinesAsync</summary> public async Task ListTrainingPipelinesRequestObjectAsync() { // Snippet: ListTrainingPipelinesAsync(ListTrainingPipelinesRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) ListTrainingPipelinesRequest request = new ListTrainingPipelinesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", ReadMask = new FieldMask(), }; // Make the request PagedAsyncEnumerable<ListTrainingPipelinesResponse, TrainingPipeline> response = pipelineServiceClient.ListTrainingPipelinesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TrainingPipeline item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTrainingPipelinesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TrainingPipeline item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TrainingPipeline> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TrainingPipeline item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTrainingPipelines</summary> public void ListTrainingPipelines() { // Snippet: ListTrainingPipelines(string, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListTrainingPipelinesResponse, TrainingPipeline> response = pipelineServiceClient.ListTrainingPipelines(parent); // Iterate over all response items, lazily performing RPCs as required foreach (TrainingPipeline item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTrainingPipelinesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TrainingPipeline item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TrainingPipeline> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TrainingPipeline item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTrainingPipelinesAsync</summary> public async Task ListTrainingPipelinesAsync() { // Snippet: ListTrainingPipelinesAsync(string, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListTrainingPipelinesResponse, TrainingPipeline> response = pipelineServiceClient.ListTrainingPipelinesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TrainingPipeline item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTrainingPipelinesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TrainingPipeline item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TrainingPipeline> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TrainingPipeline item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTrainingPipelines</summary> public void ListTrainingPipelinesResourceNames() { // Snippet: ListTrainingPipelines(LocationName, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListTrainingPipelinesResponse, TrainingPipeline> response = pipelineServiceClient.ListTrainingPipelines(parent); // Iterate over all response items, lazily performing RPCs as required foreach (TrainingPipeline item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTrainingPipelinesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TrainingPipeline item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TrainingPipeline> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TrainingPipeline item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTrainingPipelinesAsync</summary> public async Task ListTrainingPipelinesResourceNamesAsync() { // Snippet: ListTrainingPipelinesAsync(LocationName, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListTrainingPipelinesResponse, TrainingPipeline> response = pipelineServiceClient.ListTrainingPipelinesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TrainingPipeline item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTrainingPipelinesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TrainingPipeline item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TrainingPipeline> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TrainingPipeline item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteTrainingPipeline</summary> public void DeleteTrainingPipelineRequestObject() { // Snippet: DeleteTrainingPipeline(DeleteTrainingPipelineRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) DeleteTrainingPipelineRequest request = new DeleteTrainingPipelineRequest { TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"), }; // Make the request Operation<Empty, DeleteOperationMetadata> response = pipelineServiceClient.DeleteTrainingPipeline(request); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = pipelineServiceClient.PollOnceDeleteTrainingPipeline(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTrainingPipelineAsync</summary> public async Task DeleteTrainingPipelineRequestObjectAsync() { // Snippet: DeleteTrainingPipelineAsync(DeleteTrainingPipelineRequest, CallSettings) // Additional: DeleteTrainingPipelineAsync(DeleteTrainingPipelineRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) DeleteTrainingPipelineRequest request = new DeleteTrainingPipelineRequest { TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"), }; // Make the request Operation<Empty, DeleteOperationMetadata> response = await pipelineServiceClient.DeleteTrainingPipelineAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = await pipelineServiceClient.PollOnceDeleteTrainingPipelineAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTrainingPipeline</summary> public void DeleteTrainingPipeline() { // Snippet: DeleteTrainingPipeline(string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/trainingPipelines/[TRAINING_PIPELINE]"; // Make the request Operation<Empty, DeleteOperationMetadata> response = pipelineServiceClient.DeleteTrainingPipeline(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = pipelineServiceClient.PollOnceDeleteTrainingPipeline(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTrainingPipelineAsync</summary> public async Task DeleteTrainingPipelineAsync() { // Snippet: DeleteTrainingPipelineAsync(string, CallSettings) // Additional: DeleteTrainingPipelineAsync(string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/trainingPipelines/[TRAINING_PIPELINE]"; // Make the request Operation<Empty, DeleteOperationMetadata> response = await pipelineServiceClient.DeleteTrainingPipelineAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = await pipelineServiceClient.PollOnceDeleteTrainingPipelineAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTrainingPipeline</summary> public void DeleteTrainingPipelineResourceNames() { // Snippet: DeleteTrainingPipeline(TrainingPipelineName, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) TrainingPipelineName name = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"); // Make the request Operation<Empty, DeleteOperationMetadata> response = pipelineServiceClient.DeleteTrainingPipeline(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = pipelineServiceClient.PollOnceDeleteTrainingPipeline(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTrainingPipelineAsync</summary> public async Task DeleteTrainingPipelineResourceNamesAsync() { // Snippet: DeleteTrainingPipelineAsync(TrainingPipelineName, CallSettings) // Additional: DeleteTrainingPipelineAsync(TrainingPipelineName, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) TrainingPipelineName name = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"); // Make the request Operation<Empty, DeleteOperationMetadata> response = await pipelineServiceClient.DeleteTrainingPipelineAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = await pipelineServiceClient.PollOnceDeleteTrainingPipelineAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CancelTrainingPipeline</summary> public void CancelTrainingPipelineRequestObject() { // Snippet: CancelTrainingPipeline(CancelTrainingPipelineRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest { TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"), }; // Make the request pipelineServiceClient.CancelTrainingPipeline(request); // End snippet } /// <summary>Snippet for CancelTrainingPipelineAsync</summary> public async Task CancelTrainingPipelineRequestObjectAsync() { // Snippet: CancelTrainingPipelineAsync(CancelTrainingPipelineRequest, CallSettings) // Additional: CancelTrainingPipelineAsync(CancelTrainingPipelineRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) CancelTrainingPipelineRequest request = new CancelTrainingPipelineRequest { TrainingPipelineName = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"), }; // Make the request await pipelineServiceClient.CancelTrainingPipelineAsync(request); // End snippet } /// <summary>Snippet for CancelTrainingPipeline</summary> public void CancelTrainingPipeline() { // Snippet: CancelTrainingPipeline(string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/trainingPipelines/[TRAINING_PIPELINE]"; // Make the request pipelineServiceClient.CancelTrainingPipeline(name); // End snippet } /// <summary>Snippet for CancelTrainingPipelineAsync</summary> public async Task CancelTrainingPipelineAsync() { // Snippet: CancelTrainingPipelineAsync(string, CallSettings) // Additional: CancelTrainingPipelineAsync(string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/trainingPipelines/[TRAINING_PIPELINE]"; // Make the request await pipelineServiceClient.CancelTrainingPipelineAsync(name); // End snippet } /// <summary>Snippet for CancelTrainingPipeline</summary> public void CancelTrainingPipelineResourceNames() { // Snippet: CancelTrainingPipeline(TrainingPipelineName, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) TrainingPipelineName name = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"); // Make the request pipelineServiceClient.CancelTrainingPipeline(name); // End snippet } /// <summary>Snippet for CancelTrainingPipelineAsync</summary> public async Task CancelTrainingPipelineResourceNamesAsync() { // Snippet: CancelTrainingPipelineAsync(TrainingPipelineName, CallSettings) // Additional: CancelTrainingPipelineAsync(TrainingPipelineName, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) TrainingPipelineName name = TrainingPipelineName.FromProjectLocationTrainingPipeline("[PROJECT]", "[LOCATION]", "[TRAINING_PIPELINE]"); // Make the request await pipelineServiceClient.CancelTrainingPipelineAsync(name); // End snippet } /// <summary>Snippet for CreatePipelineJob</summary> public void CreatePipelineJobRequestObject() { // Snippet: CreatePipelineJob(CreatePipelineJobRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) CreatePipelineJobRequest request = new CreatePipelineJobRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), PipelineJob = new PipelineJob(), PipelineJobId = "", }; // Make the request PipelineJob response = pipelineServiceClient.CreatePipelineJob(request); // End snippet } /// <summary>Snippet for CreatePipelineJobAsync</summary> public async Task CreatePipelineJobRequestObjectAsync() { // Snippet: CreatePipelineJobAsync(CreatePipelineJobRequest, CallSettings) // Additional: CreatePipelineJobAsync(CreatePipelineJobRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) CreatePipelineJobRequest request = new CreatePipelineJobRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), PipelineJob = new PipelineJob(), PipelineJobId = "", }; // Make the request PipelineJob response = await pipelineServiceClient.CreatePipelineJobAsync(request); // End snippet } /// <summary>Snippet for CreatePipelineJob</summary> public void CreatePipelineJob() { // Snippet: CreatePipelineJob(string, PipelineJob, string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; PipelineJob pipelineJob = new PipelineJob(); string pipelineJobId = ""; // Make the request PipelineJob response = pipelineServiceClient.CreatePipelineJob(parent, pipelineJob, pipelineJobId); // End snippet } /// <summary>Snippet for CreatePipelineJobAsync</summary> public async Task CreatePipelineJobAsync() { // Snippet: CreatePipelineJobAsync(string, PipelineJob, string, CallSettings) // Additional: CreatePipelineJobAsync(string, PipelineJob, string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; PipelineJob pipelineJob = new PipelineJob(); string pipelineJobId = ""; // Make the request PipelineJob response = await pipelineServiceClient.CreatePipelineJobAsync(parent, pipelineJob, pipelineJobId); // End snippet } /// <summary>Snippet for CreatePipelineJob</summary> public void CreatePipelineJobResourceNames() { // Snippet: CreatePipelineJob(LocationName, PipelineJob, string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); PipelineJob pipelineJob = new PipelineJob(); string pipelineJobId = ""; // Make the request PipelineJob response = pipelineServiceClient.CreatePipelineJob(parent, pipelineJob, pipelineJobId); // End snippet } /// <summary>Snippet for CreatePipelineJobAsync</summary> public async Task CreatePipelineJobResourceNamesAsync() { // Snippet: CreatePipelineJobAsync(LocationName, PipelineJob, string, CallSettings) // Additional: CreatePipelineJobAsync(LocationName, PipelineJob, string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); PipelineJob pipelineJob = new PipelineJob(); string pipelineJobId = ""; // Make the request PipelineJob response = await pipelineServiceClient.CreatePipelineJobAsync(parent, pipelineJob, pipelineJobId); // End snippet } /// <summary>Snippet for GetPipelineJob</summary> public void GetPipelineJobRequestObject() { // Snippet: GetPipelineJob(GetPipelineJobRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) GetPipelineJobRequest request = new GetPipelineJobRequest { PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"), }; // Make the request PipelineJob response = pipelineServiceClient.GetPipelineJob(request); // End snippet } /// <summary>Snippet for GetPipelineJobAsync</summary> public async Task GetPipelineJobRequestObjectAsync() { // Snippet: GetPipelineJobAsync(GetPipelineJobRequest, CallSettings) // Additional: GetPipelineJobAsync(GetPipelineJobRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) GetPipelineJobRequest request = new GetPipelineJobRequest { PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"), }; // Make the request PipelineJob response = await pipelineServiceClient.GetPipelineJobAsync(request); // End snippet } /// <summary>Snippet for GetPipelineJob</summary> public void GetPipelineJob() { // Snippet: GetPipelineJob(string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/pipelineJobs/[PIPELINE_JOB]"; // Make the request PipelineJob response = pipelineServiceClient.GetPipelineJob(name); // End snippet } /// <summary>Snippet for GetPipelineJobAsync</summary> public async Task GetPipelineJobAsync() { // Snippet: GetPipelineJobAsync(string, CallSettings) // Additional: GetPipelineJobAsync(string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/pipelineJobs/[PIPELINE_JOB]"; // Make the request PipelineJob response = await pipelineServiceClient.GetPipelineJobAsync(name); // End snippet } /// <summary>Snippet for GetPipelineJob</summary> public void GetPipelineJobResourceNames() { // Snippet: GetPipelineJob(PipelineJobName, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) PipelineJobName name = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"); // Make the request PipelineJob response = pipelineServiceClient.GetPipelineJob(name); // End snippet } /// <summary>Snippet for GetPipelineJobAsync</summary> public async Task GetPipelineJobResourceNamesAsync() { // Snippet: GetPipelineJobAsync(PipelineJobName, CallSettings) // Additional: GetPipelineJobAsync(PipelineJobName, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) PipelineJobName name = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"); // Make the request PipelineJob response = await pipelineServiceClient.GetPipelineJobAsync(name); // End snippet } /// <summary>Snippet for ListPipelineJobs</summary> public void ListPipelineJobsRequestObject() { // Snippet: ListPipelineJobs(ListPipelineJobsRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) ListPipelineJobsRequest request = new ListPipelineJobsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedEnumerable<ListPipelineJobsResponse, PipelineJob> response = pipelineServiceClient.ListPipelineJobs(request); // Iterate over all response items, lazily performing RPCs as required foreach (PipelineJob item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPipelineJobsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PipelineJob item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PipelineJob> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PipelineJob item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPipelineJobsAsync</summary> public async Task ListPipelineJobsRequestObjectAsync() { // Snippet: ListPipelineJobsAsync(ListPipelineJobsRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) ListPipelineJobsRequest request = new ListPipelineJobsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedAsyncEnumerable<ListPipelineJobsResponse, PipelineJob> response = pipelineServiceClient.ListPipelineJobsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PipelineJob item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPipelineJobsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PipelineJob item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PipelineJob> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PipelineJob item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPipelineJobs</summary> public void ListPipelineJobs() { // Snippet: ListPipelineJobs(string, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListPipelineJobsResponse, PipelineJob> response = pipelineServiceClient.ListPipelineJobs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (PipelineJob item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPipelineJobsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PipelineJob item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PipelineJob> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PipelineJob item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPipelineJobsAsync</summary> public async Task ListPipelineJobsAsync() { // Snippet: ListPipelineJobsAsync(string, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListPipelineJobsResponse, PipelineJob> response = pipelineServiceClient.ListPipelineJobsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PipelineJob item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPipelineJobsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PipelineJob item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PipelineJob> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PipelineJob item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPipelineJobs</summary> public void ListPipelineJobsResourceNames() { // Snippet: ListPipelineJobs(LocationName, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListPipelineJobsResponse, PipelineJob> response = pipelineServiceClient.ListPipelineJobs(parent); // Iterate over all response items, lazily performing RPCs as required foreach (PipelineJob item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPipelineJobsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PipelineJob item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PipelineJob> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PipelineJob item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPipelineJobsAsync</summary> public async Task ListPipelineJobsResourceNamesAsync() { // Snippet: ListPipelineJobsAsync(LocationName, string, int?, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListPipelineJobsResponse, PipelineJob> response = pipelineServiceClient.ListPipelineJobsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PipelineJob item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPipelineJobsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PipelineJob item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<PipelineJob> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (PipelineJob item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeletePipelineJob</summary> public void DeletePipelineJobRequestObject() { // Snippet: DeletePipelineJob(DeletePipelineJobRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) DeletePipelineJobRequest request = new DeletePipelineJobRequest { PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"), }; // Make the request Operation<Empty, DeleteOperationMetadata> response = pipelineServiceClient.DeletePipelineJob(request); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = pipelineServiceClient.PollOnceDeletePipelineJob(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeletePipelineJobAsync</summary> public async Task DeletePipelineJobRequestObjectAsync() { // Snippet: DeletePipelineJobAsync(DeletePipelineJobRequest, CallSettings) // Additional: DeletePipelineJobAsync(DeletePipelineJobRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) DeletePipelineJobRequest request = new DeletePipelineJobRequest { PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"), }; // Make the request Operation<Empty, DeleteOperationMetadata> response = await pipelineServiceClient.DeletePipelineJobAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = await pipelineServiceClient.PollOnceDeletePipelineJobAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeletePipelineJob</summary> public void DeletePipelineJob() { // Snippet: DeletePipelineJob(string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/pipelineJobs/[PIPELINE_JOB]"; // Make the request Operation<Empty, DeleteOperationMetadata> response = pipelineServiceClient.DeletePipelineJob(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = pipelineServiceClient.PollOnceDeletePipelineJob(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeletePipelineJobAsync</summary> public async Task DeletePipelineJobAsync() { // Snippet: DeletePipelineJobAsync(string, CallSettings) // Additional: DeletePipelineJobAsync(string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/pipelineJobs/[PIPELINE_JOB]"; // Make the request Operation<Empty, DeleteOperationMetadata> response = await pipelineServiceClient.DeletePipelineJobAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = await pipelineServiceClient.PollOnceDeletePipelineJobAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeletePipelineJob</summary> public void DeletePipelineJobResourceNames() { // Snippet: DeletePipelineJob(PipelineJobName, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) PipelineJobName name = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"); // Make the request Operation<Empty, DeleteOperationMetadata> response = pipelineServiceClient.DeletePipelineJob(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = pipelineServiceClient.PollOnceDeletePipelineJob(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeletePipelineJobAsync</summary> public async Task DeletePipelineJobResourceNamesAsync() { // Snippet: DeletePipelineJobAsync(PipelineJobName, CallSettings) // Additional: DeletePipelineJobAsync(PipelineJobName, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) PipelineJobName name = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"); // Make the request Operation<Empty, DeleteOperationMetadata> response = await pipelineServiceClient.DeletePipelineJobAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteOperationMetadata> retrievedResponse = await pipelineServiceClient.PollOnceDeletePipelineJobAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CancelPipelineJob</summary> public void CancelPipelineJobRequestObject() { // Snippet: CancelPipelineJob(CancelPipelineJobRequest, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) CancelPipelineJobRequest request = new CancelPipelineJobRequest { PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"), }; // Make the request pipelineServiceClient.CancelPipelineJob(request); // End snippet } /// <summary>Snippet for CancelPipelineJobAsync</summary> public async Task CancelPipelineJobRequestObjectAsync() { // Snippet: CancelPipelineJobAsync(CancelPipelineJobRequest, CallSettings) // Additional: CancelPipelineJobAsync(CancelPipelineJobRequest, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) CancelPipelineJobRequest request = new CancelPipelineJobRequest { PipelineJobName = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"), }; // Make the request await pipelineServiceClient.CancelPipelineJobAsync(request); // End snippet } /// <summary>Snippet for CancelPipelineJob</summary> public void CancelPipelineJob() { // Snippet: CancelPipelineJob(string, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/pipelineJobs/[PIPELINE_JOB]"; // Make the request pipelineServiceClient.CancelPipelineJob(name); // End snippet } /// <summary>Snippet for CancelPipelineJobAsync</summary> public async Task CancelPipelineJobAsync() { // Snippet: CancelPipelineJobAsync(string, CallSettings) // Additional: CancelPipelineJobAsync(string, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/pipelineJobs/[PIPELINE_JOB]"; // Make the request await pipelineServiceClient.CancelPipelineJobAsync(name); // End snippet } /// <summary>Snippet for CancelPipelineJob</summary> public void CancelPipelineJobResourceNames() { // Snippet: CancelPipelineJob(PipelineJobName, CallSettings) // Create client PipelineServiceClient pipelineServiceClient = PipelineServiceClient.Create(); // Initialize request argument(s) PipelineJobName name = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"); // Make the request pipelineServiceClient.CancelPipelineJob(name); // End snippet } /// <summary>Snippet for CancelPipelineJobAsync</summary> public async Task CancelPipelineJobResourceNamesAsync() { // Snippet: CancelPipelineJobAsync(PipelineJobName, CallSettings) // Additional: CancelPipelineJobAsync(PipelineJobName, CancellationToken) // Create client PipelineServiceClient pipelineServiceClient = await PipelineServiceClient.CreateAsync(); // Initialize request argument(s) PipelineJobName name = PipelineJobName.FromProjectLocationPipelineJob("[PROJECT]", "[LOCATION]", "[PIPELINE_JOB]"); // Make the request await pipelineServiceClient.CancelPipelineJobAsync(name); // End snippet } } }
50.158985
153
0.635028
[ "Apache-2.0" ]
amanda-tarafa/google-cloud-dotnet
apis/Google.Cloud.AIPlatform.V1/Google.Cloud.AIPlatform.V1.Snippets/PipelineServiceClientSnippets.g.cs
75,088
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Linq; using Bicep.Core.Parsing; namespace Bicep.Core.Syntax { public class DecoratorSyntax : SyntaxBase { public DecoratorSyntax(Token at, SyntaxBase expression) { AssertTokenType(at, nameof(at), TokenType.At); AssertSyntaxType( expression, nameof(expression), typeof(SkippedTriviaSyntax), typeof(VariableAccessSyntax), typeof(PropertyAccessSyntax), typeof(FunctionCallSyntax), typeof(InstanceFunctionCallSyntax)); this.At = at; this.Expression = expression; } public Token At { get; } public SyntaxBase Expression { get; } public IEnumerable<FunctionArgumentSyntax> Arguments => this.Expression is FunctionCallSyntaxBase functionCall ? functionCall.Arguments : Enumerable.Empty<FunctionArgumentSyntax>(); public override TextSpan Span => TextSpan.Between(this.At, this.Expression); public override void Accept(ISyntaxVisitor visitor) => visitor.VisitDecoratorSyntax(this); } }
31.675
118
0.639305
[ "MIT" ]
AlanFlorance/bicep
src/Bicep.Core/Syntax/DecoratorSyntax.cs
1,267
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.txt file in the project root for more information. namespace Microsoft.DiaSymReader.PortablePdb { internal static class FileNameUtilities { private const string DirectorySeparatorStr = "\\"; private const char DirectorySeparatorChar = '\\'; private const char AltDirectorySeparatorChar = '/'; private const char VolumeSeparatorChar = ':'; /// <summary> /// Returns the position in given path where the file name starts. /// </summary> /// <returns>-1 if path is null.</returns> internal static int IndexOfFileName(string? path) { if (path == null) { return -1; } for (int i = path.Length - 1; i >= 0; i--) { char ch = path[i]; if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar) { return i + 1; } } return 0; } internal static bool IsDirectorySeparator(char separator) { return separator == DirectorySeparatorChar || separator == AltDirectorySeparatorChar; } /// <summary> /// Get file name from path. /// </summary> /// <remarks>Unlike <see cref="System.IO.Path.GetFileName"/> doesn't check for invalid path characters.</remarks> internal static string GetFileName(string path) { int fileNameStart = IndexOfFileName(path); return (fileNameStart <= 0) ? path : path.Substring(fileNameStart); } } }
34.09434
121
0.568345
[ "MIT" ]
alexsasheka/SymReaderPortable
src/Microsoft.DiaSymReader.PortablePdb/Utilities/FileNameUtilities.cs
1,809
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Policy { using Newtonsoft.Json; /// <summary> /// The policy rule object. /// </summary> public class PolicyRule { /// <summary> /// The policy rule /// </summary> [JsonProperty(Required = Required.Always)] public string Rule { get; set; } } }
37.677419
87
0.571918
[ "MIT" ]
3quanfeng/azure-powershell
src/Resources/ResourceManager/Entities/Policy/PolicyRule.cs
1,140
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 01.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableInt16.NullableDouble{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Int16>; using T_DATA2 =System.Nullable<System.Double>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__01__VV public static class TestSet_504__param__01__VV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001__less() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ >= /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001__less //----------------------------------------------------------------------- [Test] public static void Test_002__equal() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ >= /*}OP*/ vv2); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002__equal //----------------------------------------------------------------------- [Test] public static void Test_003__greater() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=3; var recs=db.testTable.Where(r => vv1 /*OP{*/ >= /*}OP*/ vv2); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_003__greater //----------------------------------------------------------------------- [Test] public static void Test_ZA01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ >= /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA01NV //----------------------------------------------------------------------- [Test] public static void Test_ZA02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => vv1 /*OP{*/ >= /*}OP*/ ((T_DATA2)vv2__null_obj)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA02VN //----------------------------------------------------------------------- [Test] public static void Test_ZA03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ >= /*}OP*/ ((T_DATA2)vv2__null_obj)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA03NN //----------------------------------------------------------------------- [Test] public static void Test_ZB01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ >= /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB01NV //----------------------------------------------------------------------- [Test] public static void Test_ZB02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ >= /*}OP*/ ((T_DATA2)vv2__null_obj))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB02VN //----------------------------------------------------------------------- [Test] public static void Test_ZB03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ >= /*}OP*/ ((T_DATA2)vv2__null_obj))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB03NN };//class TestSet_504__param__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableInt16.NullableDouble
24.313283
154
0.530873
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/GreaterThanOrEqual/Complete/NullableInt16/NullableDouble/TestSet_504__param__01__VV.cs
9,703
C#
using System; using System.Drawing; namespace Aris.Moe.OverlayTranslate.Gui { public interface ITargetAreaResizeOverlay { void AskForResize(Rectangle current, Action<Rectangle?> resultCallback); } }
22
80
0.745455
[ "MIT" ]
Amiron49/Aris.Moe.Ocr.Translation.Overlay
Aris.Moe.OverlayTranslate.Gui/ITargetAreaResizeOverlay.cs
222
C#
using Acme.BookStore.Localization; using Volo.Abp.Authorization.Permissions; using Volo.Abp.Localization; namespace Acme.BookStore.Permissions; public class BookStorePermissionDefinitionProvider : PermissionDefinitionProvider { public override void Define(IPermissionDefinitionContext context) { var myGroup = context.AddGroup(BookStorePermissions.GroupName); //Define your own permissions here. Example: //myGroup.AddPermission(BookStorePermissions.MyPermission1, L("Permission:MyPermission1")); } private static LocalizableString L(string name) { return LocalizableString.Create<BookStoreResource>(name); } }
31.904762
99
0.768657
[ "MIT" ]
kfrancis/abp-wpf
src/Acme.BookStore.Application.Contracts/Permissions/BookStorePermissionDefinitionProvider.cs
670
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace SBAdmin2 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type. // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries. // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712. //config.EnableQuerySupport(); } } }
36.416667
147
0.645309
[ "Apache-2.0" ]
Warrenpk1997/SB-Admin-2-MVC
App_Start/WebApiConfig.cs
876
C#
#pragma warning disable 0472 using System; using System.Text; using System.IO; using System.Collections; using System.ComponentModel; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Xml.Serialization; using BLToolkit.Aspects; using BLToolkit.DataAccess; using BLToolkit.EditableObjects; using BLToolkit.Data; using BLToolkit.Data.DataProvider; using BLToolkit.Mapping; using BLToolkit.Reflection; using bv.common.Configuration; using bv.common.Enums; using bv.common.Core; using bv.model.BLToolkit; using bv.model.Model; using bv.model.Helpers; using bv.model.Model.Extenders; using bv.model.Model.Core; using bv.model.Model.Handlers; using bv.model.Model.Validators; using eidss.model.Core; using eidss.model.Enums; namespace eidss.model.Schema { [XmlType(AnonymousType = true)] public abstract partial class RegionLookup : EditableObject<RegionLookup> , IObject , IDisposable , ILookupUsage { [MapField(_str_idfsRegion), NonUpdatable, PrimaryKey] public abstract Int64 idfsRegion { get; set; } [LocalizedDisplayName(_str_strRegionName)] [MapField(_str_strRegionName)] public abstract String strRegionName { get; set; } protected String strRegionName_Original { get { return ((EditableValue<String>)((dynamic)this)._strRegionName).OriginalValue; } } protected String strRegionName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strRegionName).PreviousValue; } } [LocalizedDisplayName(_str_strExtendedRegionName)] [MapField(_str_strExtendedRegionName)] public abstract String strExtendedRegionName { get; set; } protected String strExtendedRegionName_Original { get { return ((EditableValue<String>)((dynamic)this)._strExtendedRegionName).OriginalValue; } } protected String strExtendedRegionName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strExtendedRegionName).PreviousValue; } } [LocalizedDisplayName(_str_strRegionCode)] [MapField(_str_strRegionCode)] public abstract String strRegionCode { get; set; } protected String strRegionCode_Original { get { return ((EditableValue<String>)((dynamic)this)._strRegionCode).OriginalValue; } } protected String strRegionCode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strRegionCode).PreviousValue; } } [LocalizedDisplayName(_str_idfsCountry)] [MapField(_str_idfsCountry)] public abstract Int64 idfsCountry { get; set; } protected Int64 idfsCountry_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsCountry).OriginalValue; } } protected Int64 idfsCountry_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsCountry).PreviousValue; } } [LocalizedDisplayName(_str_intRowStatus)] [MapField(_str_intRowStatus)] public abstract Int32 intRowStatus { get; set; } protected Int32 intRowStatus_Original { get { return ((EditableValue<Int32>)((dynamic)this)._intRowStatus).OriginalValue; } } protected Int32 intRowStatus_Previous { get { return ((EditableValue<Int32>)((dynamic)this)._intRowStatus).PreviousValue; } } [LocalizedDisplayName(_str_strCountryName)] [MapField(_str_strCountryName)] public abstract String strCountryName { get; set; } protected String strCountryName_Original { get { return ((EditableValue<String>)((dynamic)this)._strCountryName).OriginalValue; } } protected String strCountryName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strCountryName).PreviousValue; } } #region Set/Get values #region filed_info definifion protected class field_info { internal string _name; internal string _formname; internal string _type; internal Func<RegionLookup, object> _get_func; internal Action<RegionLookup, string> _set_func; internal Action<RegionLookup, RegionLookup, CompareModel> _compare_func; } internal const string _str_Parent = "Parent"; internal const string _str_IsNew = "IsNew"; internal const string _str_idfsRegion = "idfsRegion"; internal const string _str_strRegionName = "strRegionName"; internal const string _str_strExtendedRegionName = "strExtendedRegionName"; internal const string _str_strRegionCode = "strRegionCode"; internal const string _str_idfsCountry = "idfsCountry"; internal const string _str_intRowStatus = "intRowStatus"; internal const string _str_strCountryName = "strCountryName"; private static readonly field_info[] _field_infos = { new field_info { _name = _str_idfsRegion, _formname = _str_idfsRegion, _type = "Int64", _get_func = o => o.idfsRegion, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsRegion != newval) o.idfsRegion = newval; }, _compare_func = (o, c, m) => { if (o.idfsRegion != c.idfsRegion || o.IsRIRPropChanged(_str_idfsRegion, c)) m.Add(_str_idfsRegion, o.ObjectIdent + _str_idfsRegion, o.ObjectIdent2 + _str_idfsRegion, o.ObjectIdent3 + _str_idfsRegion, "Int64", o.idfsRegion == null ? "" : o.idfsRegion.ToString(), o.IsReadOnly(_str_idfsRegion), o.IsInvisible(_str_idfsRegion), o.IsRequired(_str_idfsRegion)); } }, new field_info { _name = _str_strRegionName, _formname = _str_strRegionName, _type = "String", _get_func = o => o.strRegionName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strRegionName != newval) o.strRegionName = newval; }, _compare_func = (o, c, m) => { if (o.strRegionName != c.strRegionName || o.IsRIRPropChanged(_str_strRegionName, c)) m.Add(_str_strRegionName, o.ObjectIdent + _str_strRegionName, o.ObjectIdent2 + _str_strRegionName, o.ObjectIdent3 + _str_strRegionName, "String", o.strRegionName == null ? "" : o.strRegionName.ToString(), o.IsReadOnly(_str_strRegionName), o.IsInvisible(_str_strRegionName), o.IsRequired(_str_strRegionName)); } }, new field_info { _name = _str_strExtendedRegionName, _formname = _str_strExtendedRegionName, _type = "String", _get_func = o => o.strExtendedRegionName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strExtendedRegionName != newval) o.strExtendedRegionName = newval; }, _compare_func = (o, c, m) => { if (o.strExtendedRegionName != c.strExtendedRegionName || o.IsRIRPropChanged(_str_strExtendedRegionName, c)) m.Add(_str_strExtendedRegionName, o.ObjectIdent + _str_strExtendedRegionName, o.ObjectIdent2 + _str_strExtendedRegionName, o.ObjectIdent3 + _str_strExtendedRegionName, "String", o.strExtendedRegionName == null ? "" : o.strExtendedRegionName.ToString(), o.IsReadOnly(_str_strExtendedRegionName), o.IsInvisible(_str_strExtendedRegionName), o.IsRequired(_str_strExtendedRegionName)); } }, new field_info { _name = _str_strRegionCode, _formname = _str_strRegionCode, _type = "String", _get_func = o => o.strRegionCode, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strRegionCode != newval) o.strRegionCode = newval; }, _compare_func = (o, c, m) => { if (o.strRegionCode != c.strRegionCode || o.IsRIRPropChanged(_str_strRegionCode, c)) m.Add(_str_strRegionCode, o.ObjectIdent + _str_strRegionCode, o.ObjectIdent2 + _str_strRegionCode, o.ObjectIdent3 + _str_strRegionCode, "String", o.strRegionCode == null ? "" : o.strRegionCode.ToString(), o.IsReadOnly(_str_strRegionCode), o.IsInvisible(_str_strRegionCode), o.IsRequired(_str_strRegionCode)); } }, new field_info { _name = _str_idfsCountry, _formname = _str_idfsCountry, _type = "Int64", _get_func = o => o.idfsCountry, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsCountry != newval) o.idfsCountry = newval; }, _compare_func = (o, c, m) => { if (o.idfsCountry != c.idfsCountry || o.IsRIRPropChanged(_str_idfsCountry, c)) m.Add(_str_idfsCountry, o.ObjectIdent + _str_idfsCountry, o.ObjectIdent2 + _str_idfsCountry, o.ObjectIdent3 + _str_idfsCountry, "Int64", o.idfsCountry == null ? "" : o.idfsCountry.ToString(), o.IsReadOnly(_str_idfsCountry), o.IsInvisible(_str_idfsCountry), o.IsRequired(_str_idfsCountry)); } }, new field_info { _name = _str_intRowStatus, _formname = _str_intRowStatus, _type = "Int32", _get_func = o => o.intRowStatus, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt32(val); if (o.intRowStatus != newval) o.intRowStatus = newval; }, _compare_func = (o, c, m) => { if (o.intRowStatus != c.intRowStatus || o.IsRIRPropChanged(_str_intRowStatus, c)) m.Add(_str_intRowStatus, o.ObjectIdent + _str_intRowStatus, o.ObjectIdent2 + _str_intRowStatus, o.ObjectIdent3 + _str_intRowStatus, "Int32", o.intRowStatus == null ? "" : o.intRowStatus.ToString(), o.IsReadOnly(_str_intRowStatus), o.IsInvisible(_str_intRowStatus), o.IsRequired(_str_intRowStatus)); } }, new field_info { _name = _str_strCountryName, _formname = _str_strCountryName, _type = "String", _get_func = o => o.strCountryName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strCountryName != newval) o.strCountryName = newval; }, _compare_func = (o, c, m) => { if (o.strCountryName != c.strCountryName || o.IsRIRPropChanged(_str_strCountryName, c)) m.Add(_str_strCountryName, o.ObjectIdent + _str_strCountryName, o.ObjectIdent2 + _str_strCountryName, o.ObjectIdent3 + _str_strCountryName, "String", o.strCountryName == null ? "" : o.strCountryName.ToString(), o.IsReadOnly(_str_strCountryName), o.IsInvisible(_str_strCountryName), o.IsRequired(_str_strCountryName)); } }, new field_info() }; #endregion private string _getType(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? "" : i._type; } private object _getValue(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? null : i._get_func(this); } private void _setValue(string name, string val) { var i = _field_infos.FirstOrDefault(n => n._name == name); if (i != null) i._set_func(this, val); } internal CompareModel _compare(IObject o, CompareModel ret) { if (ret == null) ret = new CompareModel(); if (o == null) return ret; RegionLookup obj = (RegionLookup)o; foreach (var i in _field_infos) if (i != null && i._compare_func != null) i._compare_func(this, obj, ret); return ret; } #endregion private BvSelectList _getList(string name) { return null; } protected CacheScope m_CS; protected Accessor _getAccessor() { return Accessor.Instance(m_CS); } private IObjectPermissions m_permissions = null; internal IObjectPermissions _permissions { get { return m_permissions; } set { m_permissions = value; } } internal string m_ObjectName = "RegionLookup"; #region Parent and Clone supporting [XmlIgnore] public IObject Parent { get { return m_Parent; } set { m_Parent = value; /*OnPropertyChanged(_str_Parent);*/ } } private IObject m_Parent; internal void _setParent() { } partial void Cloned(); partial void ClonedWithSetup(); public override object Clone() { var ret = base.Clone() as RegionLookup; ret.Cloned(); ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret._setParent(); if (this.IsDirty && !ret.IsDirty) ret.SetChange(); else if (!this.IsDirty && ret.IsDirty) ret.RejectChanges(); return ret; } public IObject CloneWithSetup(DbManagerProxy manager, bool bRestricted = false) { var ret = base.Clone() as RegionLookup; ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret.m_IsNew = this.IsNew; ret.m_ObjectName = this.m_ObjectName; Accessor.Instance(null)._SetupLoad(manager, ret, true); ret.ClonedWithSetup(); ret.DeepAcceptChanges(); ret._setParent(); ret._permissions = _permissions; return ret; } public RegionLookup CloneWithSetup() { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return CloneWithSetup(manager) as RegionLookup; } } #endregion #region IObject implementation public object Key { get { return idfsRegion; } } public string KeyName { get { return "idfsRegion"; } } public string ToStringProp { get { return ToString(); } } private bool m_IsNew; public bool IsNew { get { return m_IsNew; } } [XmlIgnore] [LocalizedDisplayName("HasChanges")] public bool HasChanges { get { return IsDirty ; } } public new void RejectChanges() { base.RejectChanges(); } public void DeepRejectChanges() { RejectChanges(); } public void DeepAcceptChanges() { AcceptChanges(); } private bool m_bForceDirty; public override void AcceptChanges() { m_bForceDirty = false; base.AcceptChanges(); } [XmlIgnore] [LocalizedDisplayName("IsDirty")] public override bool IsDirty { get { return m_bForceDirty || base.IsDirty; } } public void SetChange() { m_bForceDirty = true; } public void DeepSetChange() { SetChange(); } public bool MarkToDelete() { return _Delete(false); } public string ObjectName { get { return m_ObjectName; } } public string ObjectIdent { get { return ObjectName + "_" + Key.ToString() + "_"; } } public string ObjectIdent2 { get { return ObjectIdent; } } public string ObjectIdent3 { get { return ObjectIdent; } } public IObjectAccessor GetAccessor() { return _getAccessor(); } public IObjectPermissions GetPermissions() { return _permissions; } private IObjectEnvironment _environment; public IObjectEnvironment Environment { get { return _environment; } set { _environment = value; } } public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } } public bool IsReadOnly(string name) { return _isReadOnly(name); } public bool IsInvisible(string name) { return _isInvisible(name); } public bool IsRequired(string name) { return _isRequired(m_isRequired, name); } public bool IsHiddenPersonalData(string name) { return _isHiddenPersonalData(name); } public string GetType(string name) { return _getType(name); } public object GetValue(string name) { return _getValue(name); } public void SetValue(string name, string val) { _setValue(name, val); } public CompareModel Compare(IObject o) { return _compare(o, null); } public BvSelectList GetList(string name) { return _getList(name); } public event ValidationEvent Validation; public event ValidationEvent ValidationEnd; public event AfterPostEvent AfterPost; public Dictionary<string, string> GetFieldTags(string name) { return null; } #endregion private bool IsRIRPropChanged(string fld, RegionLookup c) { return IsReadOnly(fld) != c.IsReadOnly(fld) || IsInvisible(fld) != c.IsInvisible(fld) || IsRequired(fld) != c._isRequired(m_isRequired, fld); } public override string ToString() { return new Func<RegionLookup, string>(c => c.strRegionName)(this); } public RegionLookup() { } partial void Changed(string fieldName); partial void Created(DbManagerProxy manager); partial void Loaded(DbManagerProxy manager); partial void Deleted(); partial void ParsedFormCollection(NameValueCollection form); private bool m_IsForcedToDelete; [LocalizedDisplayName("IsForcedToDelete")] public bool IsForcedToDelete { get { return m_IsForcedToDelete; } } private bool m_IsMarkedToDelete; [LocalizedDisplayName("IsMarkedToDelete")] public bool IsMarkedToDelete { get { return m_IsMarkedToDelete; } } public void _SetupMainHandler() { PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(RegionLookup_PropertyChanged); } public void _RevokeMainHandler() { PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(RegionLookup_PropertyChanged); } private void RegionLookup_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { (sender as RegionLookup).Changed(e.PropertyName); } public bool ForceToDelete() { return _Delete(true); } internal bool _Delete(bool isForceDelete) { if (!_ValidateOnDelete()) return false; _DeletingExtenders(); m_IsMarkedToDelete = true; m_IsForcedToDelete = m_IsForcedToDelete ? m_IsForcedToDelete : isForceDelete; OnPropertyChanged("IsMarkedToDelete"); _DeletedExtenders(); Deleted(); return true; } private bool _ValidateOnDelete(bool bReport = true) { return true; } private void _DeletingExtenders() { RegionLookup obj = this; } private void _DeletedExtenders() { RegionLookup obj = this; } public bool OnValidation(ValidationModelException ex) { if (Validation != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); Validation(this, args); return args.Continue; } return false; } public bool OnValidationEnd(ValidationModelException ex) { if (ValidationEnd != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); ValidationEnd(this, args); return args.Continue; } return false; } public void OnAfterPost() { if (AfterPost != null) { AfterPost(this, EventArgs.Empty); } } public FormSize FormSize { get { return FormSize.Undefined; } } private bool _isInvisible(string name) { return false; } private bool _isReadOnly(string name) { return ReadOnly; } private bool m_readOnly; private bool _readOnly { get { return m_readOnly; } set { m_readOnly = value; } } internal Dictionary<string, Func<RegionLookup, bool>> m_isRequired; private bool _isRequired(Dictionary<string, Func<RegionLookup, bool>> isRequiredDict, string name) { if (isRequiredDict != null && isRequiredDict.ContainsKey(name)) return isRequiredDict[name](this); return false; } public void AddRequired(string name, Func<RegionLookup, bool> func) { if (m_isRequired == null) m_isRequired = new Dictionary<string, Func<RegionLookup, bool>>(); if (!m_isRequired.ContainsKey(name)) m_isRequired.Add(name, func); } internal Dictionary<string, Func<RegionLookup, bool>> m_isHiddenPersonalData; private bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData != null && m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name](this); return false; } public void AddHiddenPersonalData(string name, Func<RegionLookup, bool> func) { if (m_isHiddenPersonalData == null) m_isHiddenPersonalData = new Dictionary<string, Func<RegionLookup, bool>>(); if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, func); } #region IDisposable Members private bool bIsDisposed; ~RegionLookup() { Dispose(); } public void Dispose() { if (!bIsDisposed) { bIsDisposed = true; } } #endregion #region ILookupUsage Members public void ReloadLookupItem(DbManagerProxy manager, string lookup_object) { } #endregion public void ParseFormCollection(NameValueCollection form, bool bParseLookups = true, bool bParseRelations = true) { if (bParseLookups) { _field_infos.Where(i => i._type == "Lookup").ToList().ForEach(a => { if (form[ObjectIdent + a._formname] != null) a._set_func(this, form[ObjectIdent + a._formname]);} ); } _field_infos.Where(i => i._type != "Lookup" && i._type != "Child" && i._type != "Relation" && i._type != null) .ToList().ForEach(a => { if (form.AllKeys.Contains(ObjectIdent + a._formname)) a._set_func(this, form[ObjectIdent + a._formname]);} ); if (bParseRelations) { } ParsedFormCollection(form); } #region Accessor public abstract partial class Accessor : DataAccessor<RegionLookup> , IObjectAccessor , IObjectMeta , IObjectValidator , IObjectCreator , IObjectCreator<RegionLookup> { #region IObjectAccessor public string KeyName { get { return "idfsRegion"; } } #endregion private delegate void on_action(RegionLookup obj); private static Accessor g_Instance = CreateInstance<Accessor>(); private CacheScope m_CS; public static Accessor Instance(CacheScope cs) { if (cs == null) return g_Instance; lock(cs) { object acc = cs.Get(typeof (Accessor)); if (acc != null) { return acc as Accessor; } Accessor ret = CreateInstance<Accessor>(); ret.m_CS = cs; cs.Add(typeof(Accessor), ret); return ret; } } [InstanceCache(typeof(BvCacheAspect))] public virtual List<RegionLookup> SelectLookupList(DbManagerProxy manager , Int64? CountryID , Int64? ID ) { return _SelectList(manager , CountryID , ID , null, null ); } public static string GetLookupTableName(string method) { return "Region"; } public virtual List<RegionLookup> SelectList(DbManagerProxy manager , Int64? CountryID , Int64? ID ) { return _SelectList(manager , CountryID , ID , delegate(RegionLookup obj) { } , delegate(RegionLookup obj) { } ); } private List<RegionLookup> _SelectList(DbManagerProxy manager , Int64? CountryID , Int64? ID , on_action loading, on_action loaded ) { try { MapResultSet[] sets = new MapResultSet[1]; List<RegionLookup> objs = new List<RegionLookup>(); sets[0] = new MapResultSet(typeof(RegionLookup), objs); manager .SetSpCommand("spRegion_SelectLookup" , manager.Parameter("@CountryID", CountryID) , manager.Parameter("@ID", ID) , manager.Parameter("@LangID", ModelUserContext.CurrentLanguage) ) .ExecuteResultSet(sets); foreach(var obj in objs) { obj.m_CS = m_CS; if (loading != null) loading(obj); _SetupLoad(manager, obj); if (loaded != null) loaded(obj); } return objs; } catch(DataException e) { throw DbModelException.Create(e); } } internal void _SetupLoad(DbManagerProxy manager, RegionLookup obj, bool bCloning = false) { if (obj == null) return; // loading extenters - begin // loading extenters - end if (!bCloning) { } _LoadLookups(manager, obj); obj._setParent(); // loaded extenters - begin // loaded extenters - end _SetupHandlers(obj); _SetupChildHandlers(obj, null); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); obj._SetupMainHandler(); obj.AcceptChanges(); } internal void _SetPermitions(IObjectPermissions permissions, RegionLookup obj) { if (obj != null) { obj._permissions = permissions; if (obj._permissions != null) { } } } private RegionLookup _CreateNew(DbManagerProxy manager, IObject Parent, int? HACode, on_action creating, on_action created, bool isFake = false) { try { RegionLookup obj = RegionLookup.CreateInstance(); obj.m_CS = m_CS; obj.m_IsNew = true; obj.Parent = Parent; if (creating != null) creating(obj); // creating extenters - begin // creating extenters - end _LoadLookups(manager, obj); _SetupHandlers(obj); _SetupChildHandlers(obj, null); obj._SetupMainHandler(); obj._setParent(); // created extenters - begin // created extenters - end if (created != null) created(obj); obj.Created(manager); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); return obj; } catch(DataException e) { throw DbModelException.Create(e); } } public RegionLookup CreateNewT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public IObject CreateNew(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public RegionLookup CreateFakeT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public IObject CreateFake(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public RegionLookup CreateWithParamsT(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } public IObject CreateWithParams(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } private void _SetupChildHandlers(RegionLookup obj, object newobj) { } private void _SetupHandlers(RegionLookup obj) { } private void _LoadLookups(DbManagerProxy manager, RegionLookup obj) { } public bool Post(DbManagerProxy manager, IObject obj, bool bChildObject = false) { throw new NotImplementedException(); } protected ValidationModelException ChainsValidate(RegionLookup obj) { return null; } protected bool ChainsValidate(RegionLookup obj, bool bRethrowException) { ValidationModelException ex = ChainsValidate(obj); if (ex != null) { if (bRethrowException) throw ex; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } public bool Validate(DbManagerProxy manager, IObject obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { return Validate(manager, obj as RegionLookup, bPostValidation, bChangeValidation, bDeepValidation, bRethrowException); } public bool Validate(DbManagerProxy manager, RegionLookup obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { if (!ChainsValidate(obj, bRethrowException)) return false; return true; } private void _SetupRequired(RegionLookup obj) { } private void _SetupPersonalDataRestrictions(RegionLookup obj) { } #region IObjectMeta public int? MaxSize(string name) { return Meta.Sizes.ContainsKey(name) ? (int?)Meta.Sizes[name] : null; } public bool RequiredByField(string name, IObject obj) { return Meta.RequiredByField.ContainsKey(name) ? Meta.RequiredByField[name](obj as RegionLookup) : false; } public bool RequiredByProperty(string name, IObject obj) { return Meta.RequiredByProperty.ContainsKey(name) ? Meta.RequiredByProperty[name](obj as RegionLookup) : false; } public List<SearchPanelMetaItem> SearchPanelMeta { get { return Meta.SearchPanelMeta; } } public List<GridMetaItem> GridMeta { get { return Meta.GridMeta; } } public List<ActionMetaItem> Actions { get { return Meta.Actions; } } public string DetailPanel { get { return "RegionLookupDetail"; } } public string HelpIdWin { get { return ""; } } public string HelpIdWeb { get { return ""; } } public string HelpIdHh { get { return ""; } } #endregion } #region Meta public static class Meta { public static string spSelect = "spRegion_SelectLookup"; public static string spCount = ""; public static string spPost = ""; public static string spInsert = ""; public static string spUpdate = ""; public static string spDelete = ""; public static string spCanDelete = ""; public static Dictionary<string, int> Sizes = new Dictionary<string, int>(); public static Dictionary<string, Func<RegionLookup, bool>> RequiredByField = new Dictionary<string, Func<RegionLookup, bool>>(); public static Dictionary<string, Func<RegionLookup, bool>> RequiredByProperty = new Dictionary<string, Func<RegionLookup, bool>>(); public static List<SearchPanelMetaItem> SearchPanelMeta = new List<SearchPanelMetaItem>(); public static List<GridMetaItem> GridMeta = new List<GridMetaItem>(); public static List<ActionMetaItem> Actions = new List<ActionMetaItem>(); private static Dictionary<string, List<Func<bool>>> m_isHiddenPersonalData = new Dictionary<string, List<Func<bool>>>(); internal static bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name].Aggregate(false, (s,c) => s | c()); return false; } private static void AddHiddenPersonalData(string name, Func<bool> func) { if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, new List<Func<bool>>()); m_isHiddenPersonalData[name].Add(func); } static Meta() { Sizes.Add(_str_strRegionName, 300); Sizes.Add(_str_strExtendedRegionName, 365); Sizes.Add(_str_strRegionCode, 200); Sizes.Add(_str_strCountryName, 300); Actions.Add(new ActionMetaItem( "Create", ActionTypes.Create, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, Accessor.Instance(null).CreateWithParams(manager, c, pars)), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCreate_Id", "add", /*from BvMessages*/"tooltipCreate_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipCreate_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Save", ActionTypes.Save, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<RegionLookup>().Post(manager, (RegionLookup)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strSave_Id", "Save", /*from BvMessages*/"tooltipSave_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipSave_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Ok", ActionTypes.Ok, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<RegionLookup>().Post(manager, (RegionLookup)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipOK_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipOK_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Cancel", ActionTypes.Cancel, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCancel_Id", "", /*from BvMessages*/"tooltipCancel_Id", /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipCancel_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Delete", ActionTypes.Delete, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(((RegionLookup)c).MarkToDelete() && ObjectAccessor.PostInterface<RegionLookup>().Post(manager, (RegionLookup)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strDelete_Id", "Delete_Remove", /*from BvMessages*/"tooltipDelete_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipDelete_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, (o, p, r) => r && !o.IsNew && !o.HasChanges, null, null, false )); _SetupPersonalDataRestrictions(); } private static void _SetupPersonalDataRestrictions() { } } #endregion #endregion } }
40.968692
197
0.510429
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6/eidss.model/Schema/RegionLookup.model.cs
44,494
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.Security.V20190801 { /// <summary> /// The device security group resource /// </summary> public partial class DeviceSecurityGroup : Pulumi.CustomResource { /// <summary> /// The allow-list custom alert rules. /// </summary> [Output("allowlistRules")] public Output<ImmutableArray<Outputs.AllowlistCustomAlertRuleResponse>> AllowlistRules { get; private set; } = null!; /// <summary> /// The deny-list custom alert rules. /// </summary> [Output("denylistRules")] public Output<ImmutableArray<Outputs.DenylistCustomAlertRuleResponse>> DenylistRules { get; private set; } = null!; /// <summary> /// Resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The list of custom alert threshold rules. /// </summary> [Output("thresholdRules")] public Output<ImmutableArray<Outputs.ThresholdCustomAlertRuleResponse>> ThresholdRules { get; private set; } = null!; /// <summary> /// The list of custom alert time-window rules. /// </summary> [Output("timeWindowRules")] public Output<ImmutableArray<Outputs.TimeWindowCustomAlertRuleResponse>> TimeWindowRules { get; private set; } = null!; /// <summary> /// Resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a DeviceSecurityGroup 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 DeviceSecurityGroup(string name, DeviceSecurityGroupArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:security/v20190801:DeviceSecurityGroup", name, args ?? new DeviceSecurityGroupArgs(), MakeResourceOptions(options, "")) { } private DeviceSecurityGroup(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:security/v20190801:DeviceSecurityGroup", 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:security/latest:DeviceSecurityGroup"}, new Pulumi.Alias { Type = "azure-nextgen:security/v20170801preview:DeviceSecurityGroup"}, }, }; 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 DeviceSecurityGroup 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 DeviceSecurityGroup Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new DeviceSecurityGroup(name, id, options); } } public sealed class DeviceSecurityGroupArgs : Pulumi.ResourceArgs { [Input("allowlistRules")] private InputList<Inputs.AllowlistCustomAlertRuleArgs>? _allowlistRules; /// <summary> /// The allow-list custom alert rules. /// </summary> public InputList<Inputs.AllowlistCustomAlertRuleArgs> AllowlistRules { get => _allowlistRules ?? (_allowlistRules = new InputList<Inputs.AllowlistCustomAlertRuleArgs>()); set => _allowlistRules = value; } [Input("denylistRules")] private InputList<Inputs.DenylistCustomAlertRuleArgs>? _denylistRules; /// <summary> /// The deny-list custom alert rules. /// </summary> public InputList<Inputs.DenylistCustomAlertRuleArgs> DenylistRules { get => _denylistRules ?? (_denylistRules = new InputList<Inputs.DenylistCustomAlertRuleArgs>()); set => _denylistRules = value; } /// <summary> /// The name of the device security group. Note that the name of the device security group is case insensitive. /// </summary> [Input("deviceSecurityGroupName", required: true)] public Input<string> DeviceSecurityGroupName { get; set; } = null!; /// <summary> /// The identifier of the resource. /// </summary> [Input("resourceId", required: true)] public Input<string> ResourceId { get; set; } = null!; [Input("thresholdRules")] private InputList<Inputs.ThresholdCustomAlertRuleArgs>? _thresholdRules; /// <summary> /// The list of custom alert threshold rules. /// </summary> public InputList<Inputs.ThresholdCustomAlertRuleArgs> ThresholdRules { get => _thresholdRules ?? (_thresholdRules = new InputList<Inputs.ThresholdCustomAlertRuleArgs>()); set => _thresholdRules = value; } [Input("timeWindowRules")] private InputList<Inputs.TimeWindowCustomAlertRuleArgs>? _timeWindowRules; /// <summary> /// The list of custom alert time-window rules. /// </summary> public InputList<Inputs.TimeWindowCustomAlertRuleArgs> TimeWindowRules { get => _timeWindowRules ?? (_timeWindowRules = new InputList<Inputs.TimeWindowCustomAlertRuleArgs>()); set => _timeWindowRules = value; } public DeviceSecurityGroupArgs() { } } }
40.517857
153
0.62377
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Security/V20190801/DeviceSecurityGroup.cs
6,807
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mynt.Core.Enums; using Mynt.Core.Indicators; using Mynt.Core.Interfaces; using Mynt.Core.Models; namespace Mynt.Core.Strategies { public class RsiBbands : BaseStrategy { public override string Name => "RSI Bbands"; public override int MinimumAmountOfCandles => 200; public override Period IdealPeriod => Period.Hour; public override List<TradeAdvice> Prepare(List<Candle> candles) { var result = new List<TradeAdvice>(); var rsi = candles.Rsi(6); var bbands = candles.Bbands(200); var closes = candles.Select(x => x.Close).ToList(); for (int i = 0; i < candles.Count; i++) { if (i < 1) result.Add(TradeAdvice.Hold); else if (rsi[i - 1] > 50 && rsi[i] <= 50 && closes[i - 1] < bbands.UpperBand[i - 1] && closes[i] > bbands.UpperBand[i]) result.Add(TradeAdvice.Sell); else if (rsi[i - 1] < 50 && rsi[i] >= 50 && closes[i - 1] < bbands.LowerBand[i - 1] && closes[i] > bbands.LowerBand[i]) result.Add(TradeAdvice.Buy); else result.Add(TradeAdvice.Hold); } return result; } public override Candle GetSignalCandle(List<Candle> candles) { return candles.Last(); } public override TradeAdvice Forecast(List<Candle> candles) { return Prepare(candles).LastOrDefault(); } } }
30.888889
135
0.559353
[ "BSD-3-Clause" ]
Nick777-Pixel/Mynt
src/Mynt.Core/Strategies/RsiBbands.cs
1,670
C#
using Newtonsoft.Json; namespace PactNet.Generators; public class ProviderStateGenerator : IGenerator { public string Type => "type"; public dynamic Value { get; } public string GeneratorType => "ProviderState"; /// <summary> /// Expression to lookup in provider state context /// </summary> [JsonProperty("expression")] public string Expression { get; } public ProviderStateGenerator(dynamic example, string expression) { this.Value = example; this.Expression = expression; } }
21.8
69
0.67156
[ "MIT" ]
chad-tw/pact-net
src/PactNet.Abstractions/Generators/ProviderStateGenerator.cs
545
C#
using System; using System.Collections.Generic; using System.Text; namespace ManiaPlanetSharp.GameBox.Classes.Map { public class GbxThumbnailClass : Node { public uint Version { get; set; } public byte[] ThumbnailData { get; set; } public string Comment { get; set; } } public class GbxThumbnailClassParser : ClassParser<GbxThumbnailClass> { protected override int ChunkId => 0x3043007; protected override GbxThumbnailClass ParseChunkInternal(GameBoxReader reader) { GbxThumbnailClass thumbnail = new GbxThumbnailClass(); thumbnail.Version = reader.ReadUInt32(); if (thumbnail.Version != 0) { uint thumbnailSize = reader.ReadUInt32(); reader.ReadString("<Thumbnail.jpg>".Length); thumbnail.ThumbnailData = reader.ReadRaw((int)thumbnailSize); reader.ReadString("</Thumbnail.jpg>".Length); reader.ReadString("<Comments>".Length); thumbnail.Comment = reader.ReadString(); reader.ReadString("</Comments>".Length); } return thumbnail; } } }
31.307692
85
0.59869
[ "MIT" ]
stefan-baumann/ManiaPlanetSharp
old/ManiaPlanetSharp/ManiaPlanetSharp/GameBox/Classes/Map/GbxThumbnailClass.cs
1,223
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.CostManagement.V20190901.Inputs { /// <summary> /// The definition of a query. /// </summary> public sealed class QueryDefinitionArgs : Pulumi.ResourceArgs { /// <summary> /// Has definition for data in this query. /// </summary> [Input("dataset")] public Input<Inputs.QueryDatasetArgs>? Dataset { get; set; } /// <summary> /// Has time period for pulling data for the query. /// </summary> [Input("timePeriod")] public Input<Inputs.QueryTimePeriodArgs>? TimePeriod { get; set; } /// <summary> /// The time frame for pulling data for the query. If custom, then a specific time period must be provided. /// </summary> [Input("timeframe", required: true)] public Input<string> Timeframe { get; set; } = null!; /// <summary> /// The type of the query. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public QueryDefinitionArgs() { } } }
30.297872
115
0.602528
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/CostManagement/V20190901/Inputs/QueryDefinitionArgs.cs
1,424
C#
#region License // ScriptElement.cs // Author: Daniel Sklenitzka // // Copyright 2013 The CWC Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; namespace CkMp.Data.Scripts { public class ScriptElement { public int Id { get; set; } public String Name { get; set; } public List<Parameter> Parameters { get; private set; } public ScriptElement() { Parameters = new List<Parameter>(); } public int GetSize(bool includingHeader) { return 4 //id + 1 //3 + 2 //name index + 1 //null + 4 //parameters + Parameters.Sum(p => p.GetSize()) + (includingHeader ? 10 : 0); } } }
26.960784
75
0.610182
[ "Apache-2.0" ]
Skleni/genesis
CkMp.Data/Scripts/ScriptElement.cs
1,377
C#
using System; using System.Linq; using Fluid; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using OrchardCore.Autoroute.Drivers; using OrchardCore.Autoroute.Handlers; using OrchardCore.Autoroute.Indexing; using OrchardCore.Autoroute.Liquid; using OrchardCore.Autoroute.Model; using OrchardCore.Autoroute.Routing; using OrchardCore.Autoroute.Services; using OrchardCore.Autoroute.Settings; using OrchardCore.Autoroute.ViewModels; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.ContentManagement.GraphQL.Options; using OrchardCore.ContentManagement.Handlers; using OrchardCore.ContentManagement.Records; using OrchardCore.ContentManagement.Routing; using OrchardCore.ContentTypes.Editors; using OrchardCore.Data.Migration; using OrchardCore.Indexing; using OrchardCore.Liquid; using OrchardCore.Modules; using OrchardCore.Security.Permissions; using YesSql; using YesSql.Indexes; namespace OrchardCore.Autoroute { public class Startup : StartupBase { static Startup() { TemplateContext.GlobalMemberAccessStrategy.Register<AutoroutePartViewModel>(); } public override void ConfigureServices(IServiceCollection services) { // Autoroute Part services.AddScoped<IContentPartDisplayDriver, AutoroutePartDisplay>(); services.AddScoped<IPermissionProvider, Permissions>(); services.AddSingleton<ContentPart, AutoroutePart>(); services.AddScoped<IContentPartHandler, AutoroutePartHandler>(); services.AddScoped<IContentTypePartDefinitionDisplayDriver, AutoroutePartSettingsDisplayDriver>(); services.AddScoped<IContentPartIndexHandler, AutoroutePartIndexHandler>(); services.AddSingleton<IIndexProvider, AutoroutePartIndexProvider>(); services.AddScoped<IDataMigration, Migrations>(); services.AddSingleton<IAutorouteEntries, AutorouteEntries>(); services.AddScoped<IContentAliasProvider, AutorouteAliasProvider>(); services.AddScoped<ILiquidTemplateEventHandler, ContentAutorouteLiquidTemplateEventHandler>(); services.Configure<GraphQLContentOptions>(options => { options.ConfigurePart<AutoroutePart>(partOptions => { partOptions.Collapse = true; }); }); } public override void Configure(IApplicationBuilder app, IRouteBuilder routes, IServiceProvider serviceProvider) { var entries = serviceProvider.GetRequiredService<IAutorouteEntries>(); var session = serviceProvider.GetRequiredService<ISession>(); var autoroutes = session.QueryIndex<AutoroutePartIndex>(o => o.Published).ListAsync().GetAwaiter().GetResult(); entries.AddEntries(autoroutes.Select(o => new AutorouteEntry { ContentItemId = o.ContentItemId, Path = o.Path })); var options = serviceProvider.GetRequiredService<IOptions<AutorouteOptions>>().Value; var autorouteRoute = new AutorouteRoute(routes.DefaultHandler, entries, options); routes.Routes.Insert(0, autorouteRoute); } } }
40.409639
126
0.735242
[ "BSD-3-Clause" ]
TheCheng/OrchardCore
src/OrchardCore.Modules/OrchardCore.Autoroute/Startup.cs
3,354
C#
using Testura.Android.PageObjectCreator.ViewModels; using NUnit.Framework; using Testura.Android.PageObjectCreator.Services; using Moq; namespace Testura.Android.PageObjectCreator.Tests.ViewModels { [TestFixture] public class ScreenViewModelTests { private Mock<IScreenService> _screenServiceMock; private Mock<IDialogService> _dialogServiceMock; private Mock<IUniqueWithFinderService> _optimalWithServiceMock; private ScreenViewModel _screenViewModel; [SetUp] public void SetUp() { _screenServiceMock = new Mock<IScreenService>(); _dialogServiceMock = new Mock<IDialogService>(); _optimalWithServiceMock = new Mock<IUniqueWithFinderService>(); _screenViewModel = new ScreenViewModel(_screenServiceMock.Object, _dialogServiceMock.Object, _optimalWithServiceMock.Object); } } }
36.28
137
0.726571
[ "MIT" ]
Testura/Testura.Android.PageObjectCreator
src/Testura.Android.PageObjectCreator.Tests/ViewModels/ScreenViewModelTests.cs
907
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.ML.Probabilistic.Collections; namespace Microsoft.ML.Probabilistic.Compiler.Graphs { /// <summary> /// Create a graph from a collection of nodes and corresponding adjacency data. /// </summary> /// <typeparam name="Node">The type of a node handle.</typeparam> /// <typeparam name="NodeInfo">The type of a node data structure.</typeparam> /// <remarks><para> /// This class creates a directed graph object from a collection of node handles and data objects. /// The data object is assumed to hold the adjacency information for the handles, in the form /// of a delegate sourcesOfNode(data) which returns a collection of node handles. /// Each node is given an integer index. /// Using these integers you can attach additional data to the graph via CreateNodeData which returns an array. /// </para><para> /// In the simplest case, NodeInfo can be the same as Node in which case this class just stores /// a mapping from nodes to integers and vice versa. /// (The delegate infoOfNode would simply return its argument.) /// More generally, NodeInfo can store cached information about the node. /// </para></remarks> internal class IndexedGraphWrapper<Node, NodeInfo> : IDirectedGraph<int>, CanCreateNodeData<int> { public NodeInfo[] info; /// <summary>Provides an index (into info[]) for each node.</summary> public IndexedProperty<Node, int> indexOfNode; protected Converter<NodeInfo, ICollection<Node>> sourcesOfNode; public ICollection<int>[] targetsOfNode; public IndexedGraphWrapper(ICollection<Node> nodes, Converter<Node, NodeInfo> infoOfNode, Converter<NodeInfo, ICollection<Node>> sourcesOfNode) : this(nodes, infoOfNode, sourcesOfNode, new IndexedProperty<Node, int>(new Dictionary<Node, int>())) { } public IndexedGraphWrapper(ICollection<Node> nodes, Converter<Node, NodeInfo> infoOfNode, Converter<NodeInfo, ICollection<Node>> sourcesOfNode, IndexedProperty<Node, int> indexOfNode) { info = new NodeInfo[nodes.Count]; this.indexOfNode = indexOfNode; this.sourcesOfNode = sourcesOfNode; //new IndexedProperty<Node,int>(new Dictionary<Node,int>()); int i = 0; foreach (Node node in nodes) { info[i] = infoOfNode(node); indexOfNode[node] = i; i++; } targetsOfNode = new ICollection<int>[info.Length]; } public int TargetCount(int source) { ICollection<int> targets = targetsOfNode[source]; return (targets != null) ? targets.Count : 0; } public int SourceCount(int target) { return sourcesOfNode(info[target]).Count; } public IEnumerable<int> TargetsOf(int source) { ICollection<int> targets = targetsOfNode[source]; if (targets != null) { foreach (int target in targets) { yield return target; } } } public IEnumerable<int> SourcesOf(int target) { foreach (Node sourceNode in sourcesOfNode(info[target])) { int source = indexOfNode[sourceNode]; ICollection<int> targets = targetsOfNode[source]; if (targets == null) targets = new Set<int>(); targets.Add(target); targetsOfNode[source] = targets; yield return source; } } public ICollection<int> Nodes { get { return new Range(0, info.Length); } } public int EdgeCount() { throw new Exception("The method or operation is not implemented."); } public int NeighborCount(int node) { return SourceCount(node) + TargetCount(node); } public IEnumerable<int> NeighborsOf(int node) { return SourcesOf(node).Concat(TargetsOf(node)); } public bool ContainsEdge(int source, int target) { foreach (Node targetNode in sourcesOfNode(info[target])) { if (indexOfNode[targetNode] == target) return true; } return false; //return info[target].Sources.Contains(nodeOf(info[source])); } public IndexedProperty<int, T> CreateNodeData<T>(T defaultValue) { T[] data = new T[info.Length]; IndexedProperty<int, T> prop = MakeIndexedProperty.FromArray<T>(data, defaultValue); prop.Clear(); return prop; } } }
37.681159
126
0.588269
[ "MIT" ]
0xflotus/infer
src/Compiler/Graphs/IndexedGraphWrapper.cs
5,200
C#
using System; using System.Linq; using System.Reflection; using Inject; using Util; namespace Live_Performance.Persistence { public static class PersistenceInjector { /// <summary> /// Register all repositories found using the given provider. /// </summary> /// <param name="provider">The provider that supplies the types.</param> public static void Inject(IRepositoryProvider provider) { // Connection params if (provider.ConnectionParamsContract != null && provider.ConnectionParamsImpl != null) { Injector.Register(provider.ConnectionParamsContract, provider.ConnectionParamsImpl); } // Setup if (provider.Setup != null) { Injector.Register(typeof(IRepositorySetup), provider.Setup); } AppDomain.CurrentDomain.GetAssemblies() // Get all entities with Entity and Identity attribute .SelectMany(x => x.GetTypes() .Where(t => t.IsDefined(typeof(EntityAttribute), true)) .Where(t => t.GetProperties() .Any(info => info.IsDefined(typeof(IdentityAttribute), true))) ).ToList().ForEach(t => { Log.I("DISCOVERY", $"Found entity '{t.Name}'"); try { // Get database Type from IRepositoryProvider Type repository = (Type) typeof(IRepositoryProvider).GetMethod("GetDatabaseType") .MakeGenericMethod(t) .Invoke(provider, new object[] {}); // Register repository typeof(PersistenceInjector).GetMethod("RegisterRepository", BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(new Type[] {t, repository}) .Invoke(null, new object[] {}); } catch (System.Exception e) { Log.E("INJECT", e.ToString()); } }); } /// <summary> /// Register a repository and its armour. /// </summary> /// <typeparam name="T">The entity for which to register the repository.</typeparam> /// <typeparam name="TRepo">The repository to register.</typeparam> private static void RegisterRepository<T, TRepo>() where T : new() { // Global persistence layer Injector.Register<IRepository<T>, RepositoryArmour<T>>(); // Database specific Injector.Register<IStrictRepository<T>, TRepo>(); } } }
39.680556
105
0.515576
[ "MIT" ]
SvenDub/s2-live-performance
Live Performance.Persistence/PersistenceInjector.cs
2,859
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Profile; using System.Web.Security; using DXInfo.Models; using DXInfo.Data.Contracts; using Ninject; using System.Web.Mvc; namespace DXInfo.Profile { public class CustomProfile : ProfileBase { [SettingsAllowAnonymous(false)] [CustomProviderData("DeptId;uniqueidentifier")] public Guid DeptId { get { return (Guid)this.GetPropertyValue("DeptId"); } set { this.SetPropertyValue("DeptId", value); } } [SettingsAllowAnonymous(false)] public string DeptCode { get { return (string)this.GetPropertyValue("DeptCode"); } set { this.SetPropertyValue("DeptCode", value); } } [SettingsAllowAnonymous(false)] public string DeptName { get { return (string)this.GetPropertyValue("DeptName"); } set { this.SetPropertyValue("DeptName", value); } } [SettingsAllowAnonymous(false)] [CustomProviderData("FullName;nvarchar")] public string FullName { get { return (string)this.GetPropertyValue("FullName"); } set { this.SetPropertyValue("FullName", value); } } //[SettingsAllowAnonymous(false)] //[CustomProviderData("Limit;int")] //public int Limit //{ // get { return (int)this.GetPropertyValue("Limit"); } // set { this.SetPropertyValue("Limit", value); } //} public static CustomProfile GetUserProfile(string username) { CustomProfile customProfile = Create(username) as CustomProfile; if (customProfile.DeptId != Guid.Empty) { var Uow = DependencyResolver.Current.GetService<IFairiesMemberManageUow>(); Depts dept = Uow.Depts.GetById(g => g.DeptId == customProfile.DeptId); if (dept != null) { customProfile.DeptCode = dept.DeptCode; customProfile.DeptName = dept.DeptName; } } return customProfile; } public static CustomProfile GetUserProfile() { MembershipUser u = Membership.GetUser(); string username = ""; if (u != null) { username = u.UserName; } CustomProfile customProfile = Create(username) as CustomProfile; if (customProfile.DeptId != Guid.Empty) { var Uow = DependencyResolver.Current.GetService<IFairiesMemberManageUow>(); Depts dept = Uow.Depts.GetById(g => g.DeptId == customProfile.DeptId); if (dept != null) { customProfile.DeptCode = dept.DeptCode; customProfile.DeptName = dept.DeptName; } } return customProfile; } } }
32.967391
91
0.559512
[ "Apache-2.0" ]
zhenghua75/DXInfo
DXInfo.Profile/CustomProfile.cs
3,035
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Text; using SharpAvi.Codecs; namespace SharpAvi.Output { /// <summary> /// Used to write an AVI file. /// </summary> /// <remarks> /// After writing begin to any of the streams, no property changes or stream addition are allowed. /// </remarks> public class AviWriter : IDisposable, IAviStreamWriteHandler { private const int MAX_INDEX_ENTRIES = 15000; private const int INDEX1_ENTRY_SIZE = 4 * sizeof(uint); private const int RIFF_AVI_SIZE_TRESHOLD = 512 * 1024 * 1024; private const int RIFF_AVIX_SIZE_TRESHOLD = int.MaxValue - 1024 * 1024; private readonly BinaryWriter fileWriter; #if !FX45 private readonly bool closeWriter = true; #endif private bool isClosed = false; private bool startedWriting = false; private readonly object syncWrite = new object(); private bool isFirstRiff = true; private RiffItem currentRiff; private RiffItem currentMovie; private RiffItem header; private int riffSizeTreshold; private int riffAviFrameCount = -1; private int index1Count = 0; #if FX45 private readonly List<IAviStreamInternal> streams = new List<IAviStreamInternal>(); #else private readonly List<IAviStream> streamsList = new List<IAviStream>(); private IEnumerable<IAviStreamInternal> streams { get { return streamsList.Cast<IAviStreamInternal>(); } } private readonly ReadOnlyCollection<IAviStream> streamsRO; #endif private StreamInfo[] streamsInfo; /// <summary> /// Creates a new instance of <see cref="AviWriter"/> for writing to a file. /// </summary> /// <param name="fileName">Path to an AVI file being written.</param> public AviWriter(string fileName) { Contract.Requires(!string.IsNullOrEmpty(fileName)); #if !FX45 streamsRO = new ReadOnlyCollection<IAviStream>(streamsList); #endif var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024); fileWriter = new BinaryWriter(fileStream); } /// <summary> /// Creates a new instance of <see cref="AviWriter"/> for writing to a stream. /// </summary> /// <param name="stream">Stream being written to.</param> /// <param name="leaveOpen">Whether to leave the stream open when closing <see cref="AviWriter"/>.</param> public AviWriter(Stream stream, bool leaveOpen = false) { Contract.Requires(stream.CanWrite); Contract.Requires(stream.CanSeek); #if FX45 fileWriter = new BinaryWriter(stream, Encoding.Default, leaveOpen); #else fileWriter = new BinaryWriter(stream); closeWriter = !leaveOpen; streamsRO = new ReadOnlyCollection<IAviStream>(streamsList); #endif } /// <summary>Frame rate.</summary> /// <remarks> /// The value of the property is rounded to 3 fractional digits. /// Default value is <c>1</c>. /// </remarks> /// <exception cref="InvalidOperationException"> /// Already started to write frames hence this information cannot be changed. /// </exception> public decimal FramesPerSecond { get { return framesPerSecond; } set { Contract.Requires(value > 0); lock (syncWrite) { CheckNotStartedWriting(); framesPerSecond = Decimal.Round(value, 3); } } } private decimal framesPerSecond = 1; private uint frameRateNumerator; private uint frameRateDenominator; /// <summary> /// Whether to emit index used in AVI v1 format. /// </summary> /// <remarks> /// By default, only index conformant to OpenDML AVI extensions (AVI v2) is emitted. /// Presence of v1 index may improve the compatibility of generated AVI files with certain software, /// especially when there are multiple streams. /// </remarks> /// <exception cref="InvalidOperationException"> /// Already started to write frames hence this information cannot be changed. /// </exception> public bool EmitIndex1 { get { return emitIndex1; } set { lock (syncWrite) { CheckNotStartedWriting(); emitIndex1 = value; } } } private bool emitIndex1; /// <summary> /// The maximum number of super index entries. /// </summary> /// <remarks> /// <para> /// This number should be known before writing starts because the space for /// super-index entries is reserved in the file header. /// It effectively limits the number of frames which can be written to an individual stream. /// Each super-index entry points to a single index block which can reference up to <c>15,000</c> frames. /// </para> /// <para> /// The default value is <c>256</c>. For a 60 frames/s video stream this is equivalent to a duration /// of more than 17 hours. /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// Already started to write frames hence this information cannot be changed. /// </exception> public int MaxSuperIndexEntries { get { return maxSuperIndexEntries; } set { Contract.Requires(value > 0); lock (syncWrite) { CheckNotStartedWriting(); maxSuperIndexEntries = value; } } } private int maxSuperIndexEntries = 256; /// <summary>AVI streams that have been added so far.</summary> #if FX45 public IReadOnlyList<IAviStream> Streams { get { return streams; } } #else public ReadOnlyCollection<IAviStream> Streams { get { return streamsRO; } } #endif /// <summary>Adds new video stream.</summary> /// <param name="width">Frame's width.</param> /// <param name="height">Frame's height.</param> /// <param name="bitsPerPixel">Bits per pixel.</param> /// <returns>Newly added video stream.</returns> /// <remarks> /// Stream is initialized to be ready for uncompressed video (bottom-up BGR) with specified parameters. /// However, properties (such as <see cref="IAviVideoStream.Codec"/>) can be changed later if the stream is /// to be fed with pre-compressed data. /// </remarks> public IAviVideoStream AddVideoStream(int width = 1, int height = 1, BitsPerPixel bitsPerPixel = BitsPerPixel.Bpp32) { Contract.Requires(width > 0); Contract.Requires(height > 0); Contract.Requires(Enum.IsDefined(typeof(BitsPerPixel), bitsPerPixel)); Contract.Requires(Streams.Count < 100); Contract.Ensures(Contract.Result<IAviVideoStream>() != null); return AddStream<IAviVideoStreamInternal>(index => { var stream = new AviVideoStream(index, this, width, height, bitsPerPixel); var asyncStream = new AsyncVideoStreamWrapper(stream); return asyncStream; }); } /// <summary>Adds new encoding video stream.</summary> /// <param name="encoder">Encoder to be used.</param> /// <param name="ownsEncoder">Whether encoder should be disposed with the writer.</param> /// <param name="width">Frame's width.</param> /// <param name="height">Frame's height.</param> /// <returns>Newly added video stream.</returns> /// <remarks> /// <para> /// Stream is initialized to be to be encoded with the specified encoder. /// Method <see cref="IAviVideoStream.WriteFrame"/> expects data in the same format as encoders, /// that is top-down BGR32 bitmap. It is passed to the encoder and the encoded result is written /// to the stream. /// Parameters <c>isKeyFrame</c> and <c>length</c> are ignored by encoding streams, /// as encoders determine on their own which frames are keys, and the size of input bitmaps is fixed. /// </para> /// <para> /// Properties <see cref="IAviVideoStream.Codec"/> and <see cref="IAviVideoStream.BitsPerPixel"/> /// are defined by the encoder, and cannot be modified. /// </para> /// </remarks> public IAviVideoStream AddEncodingVideoStream(IVideoEncoder encoder, bool ownsEncoder = true, int width = 1, int height = 1) { Contract.Requires(encoder != null); Contract.Requires(Streams.Count < 100); Contract.Ensures(Contract.Result<IAviVideoStream>() != null); return AddStream<IAviVideoStreamInternal>(index => { var stream = new AviVideoStream(index, this, width, height, BitsPerPixel.Bpp32); var encodingStream = new EncodingVideoStreamWrapper(stream, encoder, ownsEncoder); var asyncStream = new AsyncVideoStreamWrapper(encodingStream); return asyncStream; }); } /// <summary>Adds new audio stream.</summary> /// <param name="channelCount">Number of channels.</param> /// <param name="samplesPerSecond">Sample rate.</param> /// <param name="bitsPerSample">Bits per sample (per single channel).</param> /// <returns>Newly added audio stream.</returns> /// <remarks> /// Stream is initialized to be ready for uncompressed audio (PCM) with specified parameters. /// However, properties (such as <see cref="IAviAudioStream.Format"/>) can be changed later if the stream is /// to be fed with pre-compressed data. /// </remarks> public IAviAudioStream AddAudioStream(int channelCount = 1, int samplesPerSecond = 44100, int bitsPerSample = 16) { Contract.Requires(channelCount > 0); Contract.Requires(samplesPerSecond > 0); Contract.Requires(bitsPerSample > 0 && (bitsPerSample % 8) == 0); Contract.Requires(Streams.Count < 100); Contract.Ensures(Contract.Result<IAviAudioStream>() != null); return AddStream<IAviAudioStreamInternal>(index => { var stream = new AviAudioStream(index, this, channelCount, samplesPerSecond, bitsPerSample); var asyncStream = new AsyncAudioStreamWrapper(stream); return asyncStream; }); } /// <summary>Adds new encoding audio stream.</summary> /// <param name="encoder">Encoder to be used.</param> /// <param name="ownsEncoder">Whether encoder should be disposed with the writer.</param> /// <returns>Newly added audio stream.</returns> /// <remarks> /// <para> /// Stream is initialized to be to be encoded with the specified encoder. /// Method <see cref="IAviAudioStream.WriteBlock"/> expects data in the same format as encoder (see encoder's docs). /// The data is passed to the encoder and the encoded result is written to the stream. /// </para> /// <para> /// The encoder defines the following properties of the stream: /// <see cref="IAviAudioStream.ChannelCount"/>, <see cref="IAviAudioStream.SamplesPerSecond"/>, /// <see cref="IAviAudioStream.BitsPerSample"/>, <see cref="IAviAudioStream.BytesPerSecond"/>, /// <see cref="IAviAudioStream.Granularity"/>, <see cref="IAviAudioStream.Format"/>, /// <see cref="IAviAudioStream.FormatSpecificData"/>. /// These properties cannot be modified. /// </para> /// </remarks> public IAviAudioStream AddEncodingAudioStream(IAudioEncoder encoder, bool ownsEncoder = true) { Contract.Requires(encoder != null); Contract.Requires(Streams.Count < 100); Contract.Ensures(Contract.Result<IAviAudioStream>() != null); return AddStream<IAviAudioStreamInternal>(index => { var stream = new AviAudioStream(index, this, 1, 44100, 16); var encodingStream = new EncodingAudioStreamWrapper(stream, encoder, ownsEncoder); var asyncStream = new AsyncAudioStreamWrapper(encodingStream); return asyncStream; }); } private TStream AddStream<TStream>(Func<int, TStream> streamFactory) where TStream : IAviStreamInternal { Contract.Requires(streamFactory != null); Contract.Requires(Streams.Count < 100); lock (syncWrite) { CheckNotClosed(); CheckNotStartedWriting(); var stream = streamFactory.Invoke(Streams.Count); #if FX45 streams.Add(stream); #else streamsList.Add(stream); #endif return stream; } } /// <summary> /// Closes the writer and AVI file itself. /// </summary> public void Close() { if (!isClosed) { bool finishWriting; lock (syncWrite) { finishWriting = startedWriting; } // Call FinishWriting without holding the lock // because additional writes may be performed inside if (finishWriting) { foreach (var stream in streams) { stream.FinishWriting(); } } lock (syncWrite) { if (startedWriting) { foreach (var stream in streams) { FlushStreamIndex(stream); } CloseCurrentRiff(); // Rewrite header with actual data like frames count, super index, etc. fileWriter.BaseStream.Position = header.ItemStart; WriteHeader(); } #if FX45 fileWriter.Close(); #else if (closeWriter) { fileWriter.Close(); } else { fileWriter.Flush(); } #endif isClosed = true; } foreach (var disposableStream in streams.OfType<IDisposable>()) { disposableStream.Dispose(); } } } void IDisposable.Dispose() { Close(); } private void CheckNotStartedWriting() { if (startedWriting) { throw new InvalidOperationException("No stream information can be changed after starting to write frames."); } } private void CheckNotClosed() { if (isClosed) { throw new ObjectDisposedException(typeof(AviWriter).Name); } } private void PrepareForWriting() { startedWriting = true; foreach (var stream in streams) { stream.PrepareForWriting(); } AviUtils.SplitFrameRate(FramesPerSecond, out frameRateNumerator, out frameRateDenominator); streamsInfo = streams.Select(s => new StreamInfo(KnownFourCCs.Chunks.IndexData(s.Index))).ToArray(); riffSizeTreshold = RIFF_AVI_SIZE_TRESHOLD; currentRiff = fileWriter.OpenList(KnownFourCCs.Lists.Avi, KnownFourCCs.ListTypes.Riff); WriteHeader(); currentMovie = fileWriter.OpenList(KnownFourCCs.Lists.Movie); } private void CreateNewRiffIfNeeded(int approximateSizeOfNextChunk) { var estimatedSize = fileWriter.BaseStream.Position + approximateSizeOfNextChunk - currentRiff.ItemStart; if (isFirstRiff && emitIndex1) { estimatedSize += RiffItem.ITEM_HEADER_SIZE + index1Count * INDEX1_ENTRY_SIZE; } if (estimatedSize > riffSizeTreshold) { CloseCurrentRiff(); currentRiff = fileWriter.OpenList(KnownFourCCs.Lists.AviExtended, KnownFourCCs.ListTypes.Riff); currentMovie = fileWriter.OpenList(KnownFourCCs.Lists.Movie); } } private void CloseCurrentRiff() { fileWriter.CloseItem(currentMovie); // Several special actions for the first RIFF (AVI) if (isFirstRiff) { riffAviFrameCount = streams.OfType<IAviVideoStream>().Max(s => streamsInfo[s.Index].FrameCount); if (emitIndex1) { WriteIndex1(); } riffSizeTreshold = RIFF_AVIX_SIZE_TRESHOLD; } fileWriter.CloseItem(currentRiff); isFirstRiff = false; } #region IAviStreamDataHandler implementation void IAviStreamWriteHandler.WriteVideoFrame(AviVideoStream stream, bool isKeyFrame, byte[] frameData, int startIndex, int count) { WriteStreamFrame(stream, isKeyFrame, frameData, startIndex, count); } void IAviStreamWriteHandler.WriteAudioBlock(AviAudioStream stream, byte[] blockData, int startIndex, int count) { WriteStreamFrame(stream, true, blockData, startIndex, count); } private void WriteStreamFrame(AviStreamBase stream, bool isKeyFrame, byte[] frameData, int startIndex, int count) { lock (syncWrite) { CheckNotClosed(); if (!startedWriting) { PrepareForWriting(); } var si = streamsInfo[stream.Index]; if (ShouldFlushStreamIndex(si.StandardIndex)) { FlushStreamIndex(stream); } if (si.SuperIndex.Count == maxSuperIndexEntries) { throw new InvalidOperationException("Cannot write more frames to this stream."); } var shouldCreateIndex1Entry = emitIndex1 && isFirstRiff; CreateNewRiffIfNeeded(count + (shouldCreateIndex1Entry ? INDEX1_ENTRY_SIZE : 0)); var chunk = fileWriter.OpenChunk(stream.ChunkId, count); fileWriter.Write(frameData, startIndex, count); fileWriter.CloseItem(chunk); si.OnFrameWritten(chunk.DataSize); var dataSize = (uint)chunk.DataSize; // Set highest bit for non-key frames according to the OpenDML spec if (!isKeyFrame) { dataSize |= 0x80000000U; } var newEntry = new StandardIndexEntry { DataOffset = chunk.DataStart, DataSize = dataSize }; si.StandardIndex.Add(newEntry); if (shouldCreateIndex1Entry) { var index1Entry = new Index1Entry { IsKeyFrame = isKeyFrame, DataOffset = (uint)(chunk.ItemStart - currentMovie.DataStart), DataSize = dataSize }; si.Index1.Add(index1Entry); index1Count++; } } } void IAviStreamWriteHandler.WriteStreamHeader(AviVideoStream videoStream) { // See AVISTREAMHEADER structure fileWriter.Write((uint)videoStream.StreamType); fileWriter.Write((uint)videoStream.Codec); fileWriter.Write(0U); // StreamHeaderFlags fileWriter.Write((ushort)0); // priority fileWriter.Write((ushort)0); // language fileWriter.Write(0U); // initial frames fileWriter.Write(frameRateDenominator); // scale (frame rate denominator) fileWriter.Write(frameRateNumerator); // rate (frame rate numerator) fileWriter.Write(0U); // start fileWriter.Write((uint)streamsInfo[videoStream.Index].FrameCount); // length fileWriter.Write((uint)streamsInfo[videoStream.Index].MaxChunkDataSize); // suggested buffer size fileWriter.Write(0U); // quality fileWriter.Write(0U); // sample size fileWriter.Write((short)0); // rectangle left fileWriter.Write((short)0); // rectangle top short right = (short)(videoStream != null ? videoStream.Width : 0); short bottom = (short)(videoStream != null ? videoStream.Height : 0); fileWriter.Write(right); // rectangle right fileWriter.Write(bottom); // rectangle bottom } void IAviStreamWriteHandler.WriteStreamHeader(AviAudioStream audioStream) { // See AVISTREAMHEADER structure fileWriter.Write((uint)audioStream.StreamType); fileWriter.Write(0U); // no codec fileWriter.Write(0U); // StreamHeaderFlags fileWriter.Write((ushort)0); // priority fileWriter.Write((ushort)0); // language fileWriter.Write(0U); // initial frames fileWriter.Write((uint)audioStream.Granularity); // scale (sample rate denominator) fileWriter.Write((uint)audioStream.BytesPerSecond); // rate (sample rate numerator) fileWriter.Write(0U); // start fileWriter.Write((uint)streamsInfo[audioStream.Index].TotalDataSize); // length fileWriter.Write((uint)(audioStream.BytesPerSecond / 2)); // suggested buffer size (half-second) fileWriter.Write(-1); // quality fileWriter.Write(audioStream.Granularity); // sample size fileWriter.SkipBytes(sizeof(short) * 4); } void IAviStreamWriteHandler.WriteStreamFormat(AviVideoStream videoStream) { // See BITMAPINFOHEADER structure fileWriter.Write(40U); // size of structure fileWriter.Write(videoStream.Width); fileWriter.Write(videoStream.Height); fileWriter.Write((short)1); // planes fileWriter.Write((ushort)videoStream.BitsPerPixel); // bits per pixel fileWriter.Write((uint)videoStream.Codec); // compression (codec FOURCC) // 0 size is safer for uncompressed formats not to bother with stride calculation var sizeInBytes = videoStream.Codec == KnownFourCCs.Codecs.Uncompressed ? 0 : videoStream.Width * videoStream.Height * (((int)videoStream.BitsPerPixel) / 8); fileWriter.Write((uint)sizeInBytes); // image size in bytes fileWriter.Write(0); // X pixels per meter fileWriter.Write(0); // Y pixels per meter // Writing grayscale palette for 8-bit uncompressed stream // Otherwise, no palette if (videoStream.BitsPerPixel == BitsPerPixel.Bpp8 && videoStream.Codec == KnownFourCCs.Codecs.Uncompressed) { fileWriter.Write(256U); // palette colors used fileWriter.Write(0U); // palette colors important for (int i = 0; i < 256; i++) { fileWriter.Write((byte)i); fileWriter.Write((byte)i); fileWriter.Write((byte)i); fileWriter.Write((byte)0); } } else { fileWriter.Write(0U); // palette colors used fileWriter.Write(0U); // palette colors important } } void IAviStreamWriteHandler.WriteStreamFormat(AviAudioStream audioStream) { // See WAVEFORMATEX structure fileWriter.Write(audioStream.Format); fileWriter.Write((ushort)audioStream.ChannelCount); fileWriter.Write((uint)audioStream.SamplesPerSecond); fileWriter.Write((uint)audioStream.BytesPerSecond); fileWriter.Write((ushort)audioStream.Granularity); fileWriter.Write((ushort)audioStream.BitsPerSample); if (audioStream.FormatSpecificData != null) { fileWriter.Write((ushort)audioStream.FormatSpecificData.Length); fileWriter.Write(audioStream.FormatSpecificData); } else { fileWriter.Write((ushort)0); } } #endregion #region Header private void WriteHeader() { header = fileWriter.OpenList(KnownFourCCs.Lists.Header); WriteFileHeader(); foreach (var stream in streams) { WriteStreamList(stream); } WriteOdmlHeader(); WriteJunkInsteadOfMissingSuperIndexEntries(); fileWriter.CloseItem(header); } private void WriteJunkInsteadOfMissingSuperIndexEntries() { var missingEntriesCount = streamsInfo.Sum(si => maxSuperIndexEntries - si.SuperIndex.Count); if (missingEntriesCount > 0) { var junkDataSize = missingEntriesCount * sizeof(uint) * 4 - RiffItem.ITEM_HEADER_SIZE; var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.Junk, junkDataSize); fileWriter.SkipBytes(junkDataSize); fileWriter.CloseItem(chunk); } } private void WriteFileHeader() { // See AVIMAINHEADER structure var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.AviHeader); fileWriter.Write((uint)Decimal.Round(1000000m / FramesPerSecond)); // microseconds per frame // TODO: More correct computation of byterate fileWriter.Write((uint)Decimal.Truncate(FramesPerSecond * streamsInfo.Sum(s => s.MaxChunkDataSize))); // max bytes per second fileWriter.Write(0U); // padding granularity var flags = MainHeaderFlags.IsInterleaved | MainHeaderFlags.TrustChunkType; if (emitIndex1) { flags |= MainHeaderFlags.HasIndex; } fileWriter.Write((uint)flags); // MainHeaderFlags fileWriter.Write(riffAviFrameCount); // total frames (in the first RIFF list containing this header) fileWriter.Write(0U); // initial frames fileWriter.Write((uint)Streams.Count); // stream count fileWriter.Write(0U); // suggested buffer size var firstVideoStream = streams.OfType<IAviVideoStream>().First(); fileWriter.Write(firstVideoStream.Width); // video width fileWriter.Write(firstVideoStream.Height); // video height fileWriter.SkipBytes(4 * sizeof(uint)); // reserved fileWriter.CloseItem(chunk); } private void WriteOdmlHeader() { var list = fileWriter.OpenList(KnownFourCCs.Lists.OpenDml); var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.OpenDmlHeader); fileWriter.Write(streams.OfType<IAviVideoStream>().Max(s => streamsInfo[s.Index].FrameCount)); // total frames in file fileWriter.SkipBytes(61 * sizeof(uint)); // reserved fileWriter.CloseItem(chunk); fileWriter.CloseItem(list); } private void WriteStreamList(IAviStreamInternal stream) { var list = fileWriter.OpenList(KnownFourCCs.Lists.Stream); WriteStreamHeader(stream); WriteStreamFormat(stream); WriteStreamName(stream); WriteStreamSuperIndex(stream); fileWriter.CloseItem(list); } private void WriteStreamHeader(IAviStreamInternal stream) { var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamHeader); stream.WriteHeader(); fileWriter.CloseItem(chunk); } private void WriteStreamFormat(IAviStreamInternal stream) { var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamFormat); stream.WriteFormat(); fileWriter.CloseItem(chunk); } private void WriteStreamName(IAviStream stream) { if (!string.IsNullOrEmpty(stream.Name)) { var bytes = Encoding.ASCII.GetBytes(stream.Name); var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamName); fileWriter.Write(bytes); fileWriter.Write((byte)0); fileWriter.CloseItem(chunk); } } private void WriteStreamSuperIndex(IAviStream stream) { var superIndex = streamsInfo[stream.Index].SuperIndex; // See AVISUPERINDEX structure var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.StreamIndex); fileWriter.Write((ushort)4); // DWORDs per entry fileWriter.Write((byte)0); // index sub-type fileWriter.Write((byte)IndexType.Indexes); // index type fileWriter.Write((uint)superIndex.Count); // entries count fileWriter.Write((uint)((IAviStreamInternal)stream).ChunkId); // chunk ID of the stream fileWriter.SkipBytes(3 * sizeof(uint)); // reserved // entries foreach (var entry in superIndex) { fileWriter.Write((ulong)entry.ChunkOffset); // offset of sub-index chunk fileWriter.Write((uint)entry.ChunkSize); // size of sub-index chunk fileWriter.Write((uint)entry.Duration); // duration of sub-index data (number of frames it refers to) } fileWriter.CloseItem(chunk); } #endregion #region Index private void WriteIndex1() { var chunk = fileWriter.OpenChunk(KnownFourCCs.Chunks.Index1); var indices = streamsInfo.Select((si, i) => new {si.Index1, ChunkId = (uint)streams.ElementAt(i).ChunkId}). Where(a => a.Index1.Count > 0) .ToList(); while (index1Count > 0) { var minOffset = indices[0].Index1[0].DataOffset; var minIndex = 0; for (var i = 1; i < indices.Count; i++) { var offset = indices[i].Index1[0].DataOffset; if (offset < minOffset) { minOffset = offset; minIndex = i; } } var index = indices[minIndex]; fileWriter.Write(index.ChunkId); fileWriter.Write(index.Index1[0].IsKeyFrame ? 0x00000010U : 0); fileWriter.Write(index.Index1[0].DataOffset); fileWriter.Write(index.Index1[0].DataSize); index.Index1.RemoveAt(0); if (index.Index1.Count == 0) { indices.RemoveAt(minIndex); } index1Count--; } fileWriter.CloseItem(chunk); } private bool ShouldFlushStreamIndex(IList<StandardIndexEntry> index) { // Check maximum number of entries if (index.Count >= MAX_INDEX_ENTRIES) return true; // Check relative offset if (index.Count > 0 && fileWriter.BaseStream.Position - index[0].DataOffset > uint.MaxValue) return true; return false; } private void FlushStreamIndex(IAviStreamInternal stream) { var si = streamsInfo[stream.Index]; var index = si.StandardIndex; var entriesCount = index.Count; if (entriesCount == 0) return; var baseOffset = index[0].DataOffset; var indexSize = 24 + entriesCount * 8; CreateNewRiffIfNeeded(indexSize); // See AVISTDINDEX structure var chunk = fileWriter.OpenChunk(si.StandardIndexChunkId, indexSize); fileWriter.Write((ushort)2); // DWORDs per entry fileWriter.Write((byte)0); // index sub-type fileWriter.Write((byte)IndexType.Chunks); // index type fileWriter.Write((uint)entriesCount); // entries count fileWriter.Write((uint)stream.ChunkId); // chunk ID of the stream fileWriter.Write((ulong)baseOffset); // base offset for entries fileWriter.SkipBytes(sizeof(uint)); // reserved foreach (var entry in index) { fileWriter.Write((uint)(entry.DataOffset - baseOffset)); // chunk data offset fileWriter.Write(entry.DataSize); // chunk data size } fileWriter.CloseItem(chunk); var superIndex = streamsInfo[stream.Index].SuperIndex; var newEntry = new SuperIndexEntry { ChunkOffset = chunk.ItemStart, ChunkSize = chunk.ItemSize, Duration = entriesCount }; superIndex.Add(newEntry); index.Clear(); } #endregion } }
39.954809
137
0.567878
[ "MIT" ]
EliahKagan/SharpAvi
SharpAvi/Output/AviWriter.cs
34,483
C#
using System; using System.Collections.Generic; using Kastra.Module.Article.DTO; namespace Kastra.Module.Article.Business.Contracts { public interface IArticleBusiness { int CountArticles(int moduleId); IList<ArticleInfo> GetArticlesList(int moduleId); IList<ArticleInfo> GetArticlesList(int moduleId, int skip, int take); ArticleInfo GetArticle(int articleId); void SaveArticle(ArticleInfo article); void DeleteArticle(int articleId); } }
29.529412
77
0.723108
[ "MIT" ]
KastraCMS/kastra-module-article
src/Business/Contracts/IArticleBusiness.cs
504
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Core.Extensions; using WalkingTec.Mvvm.Demo.Models; namespace WalkingTec.Mvvm.Demo.ViewModels.MajorVMs { public class MajorTemplateVM : BaseTemplateVM { [Display(Name = "专业编码")] public ExcelPropety MajorCode_Excel = ExcelPropety.CreateProperty<Major>(x => x.MajorCode); [Display(Name = "专业名称")] public ExcelPropety MajorName_Excel = ExcelPropety.CreateProperty<Major>(x => x.MajorName); [Display(Name = "备注")] public ExcelPropety Remark_Excel = ExcelPropety.CreateProperty<Major>(x => x.Remark); [Display(Name = "所属学校")] public ExcelPropety SchoolId_Excel = ExcelPropety.CreateProperty<Major>(x => x.SchoolId); protected override void InitVM() { SchoolId_Excel.DataType = ColumnDataType.ComboBox; SchoolId_Excel.ListItems = DC.Set<School>().GetSelectListItems(LoginUserInfo.DataPrivileges, null, y => y.SchoolName); } } public class MajorImportVM : BaseImportVM<MajorTemplateVM, Major> { } }
32.236842
130
0.703673
[ "MIT" ]
17713017177/WTM
demo/WalkingTec.Mvvm.Demo/ViewModels/MajorVMs/MajorImportVM.cs
1,255
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TranslatorForm.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.483871
151
0.582788
[ "MIT" ]
Suasy/TranslatorForm
TranslatorForm/Properties/Settings.Designer.cs
1,071
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.WAFRegional.Inputs { public sealed class SqlInjectionMatchSetFieldToMatchArgs : Pulumi.ResourceArgs { [Input("data")] public Input<string>? Data { get; set; } [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public SqlInjectionMatchSetFieldToMatchArgs() { } } }
26.576923
82
0.675832
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/WAFRegional/Inputs/SqlInjectionMatchSetFieldToMatchArgs.cs
691
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.Number.Tests { public class LongFormTestConfiguration : INumberParserConfiguration { public LongFormTestConfiguration(char decimalSep, char nonDecimalSep) { this.DecimalSeparatorChar = decimalSep; this.NonDecimalSeparatorChar = nonDecimalSep; this.CultureInfo = new CultureInfo(Culture.English); this.CardinalNumberMap = ImmutableDictionary<string, long>.Empty; this.OrdinalNumberMap = ImmutableDictionary<string, long>.Empty; this.RoundNumberMap = ImmutableDictionary<string, long>.Empty; this.DigitalNumberRegex = new Regex( @"((?<=\b)(hundred|thousand|million|billion|trillion|dozen(s)?)(?=\b))|((?<=(\d|\b))(k|t|m|g|b)(?=\b))", RegexOptions.Singleline); } public ImmutableDictionary<string, long> CardinalNumberMap { get; } public ImmutableDictionary<string, string> RelativeReferenceMap { get; private set; } public ImmutableDictionary<string, string> RelativeReferenceOffsetMap { get; private set; } public ImmutableDictionary<string, string> RelativeReferenceRelativeToMap { get; private set; } public INumberOptionsConfiguration Config { get; } public ImmutableDictionary<string, long> OrdinalNumberMap { get; } public ImmutableDictionary<string, long> RoundNumberMap { get; } public CultureInfo CultureInfo { get; } public Regex DigitalNumberRegex { get; } public Regex FractionPrepositionRegex { get; } public string FractionMarkerToken { get; } public Regex HalfADozenRegex { get; } public string HalfADozenText { get; } public string LanguageMarker { get; } = "SelfDefined"; public char NonDecimalSeparatorChar { get; } public char DecimalSeparatorChar { get; } public string WordSeparatorToken { get; } public IEnumerable<string> WrittenDecimalSeparatorTexts { get; } public IEnumerable<string> WrittenGroupSeparatorTexts { get; } public IEnumerable<string> WrittenIntegerSeparatorTexts { get; } public IEnumerable<string> WrittenFractionSeparatorTexts { get; } // Test-specific initialization: the Regex matches nothing. public Regex NegativeNumberSignRegex { get; } = new Regex(@"[^\s\S]"); public bool IsCompoundNumberLanguage { get; } public bool IsMultiDecimalSeparatorCulture { get; } public IEnumerable<string> NormalizeTokenSet(IEnumerable<string> tokens, ParseResult context) { throw new NotImplementedException(); } public long ResolveCompositeNumber(string numberStr) { throw new NotImplementedException(); } } }
35.662651
146
0.683446
[ "MIT" ]
AmmariJawher/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DataDrivenTests/Number/LongFormTestConfiguration.cs
2,962
C#
using System.Xml; using FlowGraphBase.Process; namespace FlowGraphBase.Node { /// <summary> /// /// </summary> public abstract #if EDITOR partial #endif class EventNode : SequenceNode { /// <summary> /// /// </summary> /// <param name="node_"></param> public EventNode(XmlNode node) : base(node) { } /// <summary> /// /// </summary> protected override void InitializeSlots() { SlotFlag = SlotAvailableFlag.DefaultFlagEvent; } /// <summary> /// /// </summary> /// <param name="context_"></param> /// <param name="index_"></param> public void Triggered(ProcessingContext context, int index, object para) { TriggeredImpl(para); ActivateOutputLink(context, index); } /// <summary> /// /// </summary> /// <param name="para_"></param> protected abstract void TriggeredImpl(object para); } }
21.392157
80
0.493126
[ "MIT" ]
bubdm/FlowGraph
FlowGraph/FlowGraphBase/Node/EventNode.cs
1,093
C#
namespace SFA.DAS.Support.Shared.Discovery { /// <summary> /// Extend the enumeration for each new resource provided by a Service /// </summary> public enum SupportServiceResourceKey { None, EmployerUser, EmployerUserHeader, EmployerUserAccounts, CommitmentSearch, CommitmentApprenticeDetail, CommitmentCohortDetail, EmployerAccount, EmployerAccountHeader, EmployerAccountTeam, EmployerAccountFinance, EmployerAccountPayeSchemeLevys, EmployerAccountFinanceChallenge, } }
27.409091
78
0.660033
[ "MIT" ]
SkillsFundingAgency/das-support-portal
src/SFA.DAS.Support.Shared/Discovery/ServiceResourceKey.cs
605
C#
namespace CosmosBulkImport { using Akka.Actor; using CommandLine; using System; using System.IO; class Options { [Option('e', "endpoint", Required = true, HelpText = "The endpoint of your Cosmos DB account")] public string Endpoint { get; set; } [Option('k', "key", Required = true, HelpText = "The authentication key")] public string Key { get; set; } [Option('d', "database", Required = true, HelpText = "The name of the database")] public string Database { get; set; } [Option('c', "collection", Required = true, HelpText = "The name of the collection where you want to upload your documents")] public string Collection { get; set; } [Option('i', "inputFile", Required = true, HelpText = "The path to the file containing the documents")] public string InputFile { get; set; } } class Program { static void Main(string[] args) { var optionsParseResult = Parser.Default.ParseArguments<Options>(args); if (optionsParseResult is NotParsed<Options>) { return; } else if (optionsParseResult is Parsed<Options> parsedOptions) { if (!File.Exists(parsedOptions.Value.InputFile)) { Console.WriteLine("Can't find input file"); return; } var system = ActorSystem.Create("CosmosBulkImport"); var controllerRef = system.ActorOf(Props.Create(() => new BulkImporterActor()), "bulk-importer"); controllerRef.Tell(new BulkImporterActor.StartMessage(parsedOptions.Value), ActorRefs.NoSender); Console.ReadLine(); } } } }
38.404255
133
0.575623
[ "MIT" ]
ThomasWeiss/cosmos-bulk-import
CosmosBulkImport/Program.cs
1,807
C#
using GoBabyGoV2.Utilities; using GoBabyGoV2.Views; using Xamarin.Forms; namespace GoBabyGoV2 { /* * General Build Info: * * Change Configuration Mode (Debug/Release): Open Configuration Manager * Build > Configuration Manager * * * Android Release: * Linker: Don't link * * * * iOS Build Info: * * When targeting Release for deployment on Android, un-load iOS project if unable to Archive Android Solution (same key used) * * Use: Link Framework SDKs Only, if compilation errors arise due to linking * Recheck: Perform all 32-bit floating point operations as 64-bit, if needed for higher precision * * * Bundle Signing: * Use Manual Provisioning(Info.plist): Xcode app uses Automatic signing (Personal Team) * */ public partial class App : Application { public App() { InitializeComponent(); // Create MainPage as a NavigationPage MainPage = new NavigationPage(new CarWelcomePage()); // Set Status bar Color (Specifically for iOS) MainPage.SetValue(NavigationPage.BarTextColorProperty, Color.White); MainPage.SetValue(NavigationPage.BarBackgroundColorProperty, Resources["StatusBarPrimary"]); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps // If not null, try stop monitoring AccelerometerSensor.Monitor?.StopMonitoring(); } protected override void OnResume() { // Handle when your app resumes // If not null, start monitoring again AccelerometerSensor.Monitor?.StartMonitoring(); } } }
28.5
130
0.607124
[ "MIT" ]
CalebABG/CCSUGoBabyGo
GoBabyGoV2/GoBabyGoV2/App.xaml.cs
1,883
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal enum ConversionKind : byte { UnsetConversionKind = 0, NoConversion, Identity, ImplicitNumeric, ImplicitEnumeration, ImplicitThrow, ImplicitTupleLiteral, ImplicitTuple, ExplicitTupleLiteral, ExplicitTuple, ImplicitNullable, NullLiteral, ImplicitReference, Boxing, ImplicitPointerToVoid, ImplicitNullToPointer, // Any explicit conversions involving pointers not covered by PointerToVoid or NullToPointer. // Currently, this is just implicit function pointer conversions. ImplicitPointer, ImplicitDynamic, ExplicitDynamic, ImplicitConstant, ImplicitUserDefined, AnonymousFunction, MethodGroup, ExplicitNumeric, ExplicitEnumeration, ExplicitNullable, ExplicitReference, Unboxing, ExplicitUserDefined, ExplicitPointerToPointer, ExplicitIntegerToPointer, ExplicitPointerToInteger, // The IntPtr conversions are not described by the specification but we must // implement them for compatibility with the native compiler. IntPtr, InterpolatedString, // a conversion from an interpolated string to IFormattable or FormattableString SwitchExpression, // a conversion from a switch expression to a type which each arm can convert to ConditionalExpression, // a conversion from a conditional expression to a type which each side can convert to Deconstruction, // The Deconstruction conversion is not part of the language, it is an implementation detail StackAllocToPointerType, StackAllocToSpanType, // PinnedObjectToPointer is not directly a part of the language // It is used by lowering of "fixed" statements to represent conversion of an object reference (O) to an unmanaged pointer (*) // The conversion is unsafe and makes sense only if (O) is pinned. PinnedObjectToPointer, DefaultLiteral, // a conversion from a `default` literal to any type ObjectCreation, // a conversion from a `new()` expression to any type } }
38.514706
134
0.696067
[ "MIT" ]
Acidburn0zzz/roslyn
src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionKind.cs
2,621
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.IO; using System.Text.Json.Serialization.Converters; namespace System.Text.Json.Nodes { public abstract partial class JsonNode { /// <summary> /// Parses one JSON value (including objects or arrays) from the provided reader. /// </summary> /// <param name="reader">The reader to read.</param> /// <param name="nodeOptions">Options to control the behavior.</param> /// <returns> /// The <see cref="JsonNode"/> from the reader. /// </returns> /// <remarks> /// <para> /// If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/> /// is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the /// reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine /// the start of the value. /// </para> /// <para> /// Upon completion of this method <paramref name="reader"/> will be positioned at the /// final token in the JSON value. If an exception is thrown, the reader is reset to the state it was in when the method was called. /// </para> /// <para> /// This method makes a copy of the data the reader acted on, so there is no caller /// requirement to maintain data integrity beyond the return of this method. /// </para> /// </remarks> /// <exception cref="ArgumentException"> /// <paramref name="reader"/> is using unsupported options. /// </exception> /// <exception cref="ArgumentException"> /// The current <paramref name="reader"/> token does not start or represent a value. /// </exception> /// <exception cref="JsonException"> /// A value could not be read from the reader. /// </exception> public static JsonNode? Parse( ref Utf8JsonReader reader, JsonNodeOptions? nodeOptions = null) { JsonElement element = JsonElement.ParseValue(ref reader); return JsonNodeConverter.Create(element, nodeOptions); } /// <summary> /// Parse text representing a single JSON value. /// </summary> /// <param name="json">JSON text to parse.</param> /// <param name="nodeOptions">Options to control the node behavior after parsing.</param> /// <param name="documentOptions">Options to control the document behavior during parsing.</param> /// <returns> /// A <see cref="JsonNode"/> representation of the JSON value. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="json"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// <paramref name="json"/> does not represent a valid single JSON value. /// </exception> public static JsonNode? Parse( string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) { if (json == null) { throw new ArgumentNullException(nameof(json)); } JsonElement element = JsonElement.ParseValue(json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); } /// <summary> /// Parse text representing a single JSON value. /// </summary> /// <param name="utf8Json">JSON text to parse.</param> /// <param name="nodeOptions">Options to control the node behavior after parsing.</param> /// <param name="documentOptions">Options to control the document behavior during parsing.</param> /// <returns> /// A <see cref="JsonNode"/> representation of the JSON value. /// </returns> /// <exception cref="JsonException"> /// <paramref name="utf8Json"/> does not represent a valid single JSON value. /// </exception> public static JsonNode? Parse( ReadOnlySpan<byte> utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) { JsonElement element = JsonElement.ParseValue(utf8Json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); } /// <summary> /// Parse a <see cref="Stream"/> as UTF-8-encoded data representing a single JSON value into a /// <see cref="JsonNode"/>. The Stream will be read to completion. /// </summary> /// <param name="utf8Json">JSON text to parse.</param> /// <param name="nodeOptions">Options to control the node behavior after parsing.</param> /// <param name="documentOptions">Options to control the document behavior during parsing.</param> /// <returns> /// A <see cref="JsonNode"/> representation of the JSON value. /// </returns> /// <exception cref="JsonException"> /// <paramref name="utf8Json"/> does not represent a valid single JSON value. /// </exception> public static JsonNode? Parse( Stream utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) { if (utf8Json == null) { throw new ArgumentNullException(nameof(utf8Json)); } JsonElement element = JsonElement.ParseValue(utf8Json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); } } }
45.361538
145
0.591826
[ "MIT" ]
AerisG222/runtime
src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs
5,899
C#
/* Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using FirebaseAdmin; using Google.Apis.Auth.OAuth2; using System; using System.Net; using Nito.AsyncEx; using System.Threading.Tasks; using System.Collections.Specialized; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace TestCLI { class Program { static string FirebaseDatabaseUrl = String.Empty; enum Operation { Read, Delete, Update } static void Main(string[] args) { AsyncContext.Run(() => MainAsync(args)); } private static Uri MakeDatabaseUri(string path, string accessToken) { return new Uri(new Uri(FirebaseDatabaseUrl), path + ".json?access_token=" + accessToken); } // https://firebase.google.com/docs/reference/rest/database#section-api-usage private static string RunFirebaseOperationInternal(WebClient client, Operation operation, string path, string payload, string accessToken) { switch (operation) { case Operation.Read: return client.DownloadString(MakeDatabaseUri(path, accessToken)); case Operation.Delete: client.UploadValues(MakeDatabaseUri(path, accessToken), "DELETE", new NameValueCollection()); return null; case Operation.Update: client.UploadString(MakeDatabaseUri(path, accessToken), payload); return null; default: throw new ApplicationException("Invalid operation specified: " + operation); } } private async static Task<string> RunFirebaseOperation(Operation operation, string path, string payload) { Task<string> task = FirebaseApp.DefaultInstance.Options.Credential.UnderlyingCredential.GetAccessTokenForRequestAsync(); string accessToken = await task; using (WebClient client = new WebClient()) { return RunFirebaseOperationInternal(client, operation, path, payload, accessToken); } } async static void DeleteDummyData(string path) { string data = File.ReadAllText(path); JObject contents = (JObject)JsonConvert.DeserializeObject(data); foreach (var entry in contents) { Console.WriteLine(entry.Key); await RunFirebaseOperation(Operation.Delete, "/raw_pings/2999-01-01/" + entry.Key, null); } } async static void TestInsertReadDelete() { string data = await RunFirebaseOperation(Operation.Read, "/raw_pings/2999-01-01/-MKNkqMNkCV4ENXk7E6_", null); Console.WriteLine(data); await RunFirebaseOperation(Operation.Delete, "/raw_pings/2999-01-01/-MKNkqMNkCV4ENXk7E6_", null); data = await RunFirebaseOperation(Operation.Read, "/raw_pings/2999-01-01/-MKNkqMNkCV4ENXk7E6_", null); Console.WriteLine(data); var payload = JsonConvert.SerializeObject(new { ping = 23, time = DateTime.Now }); await RunFirebaseOperation(Operation.Update, "/raw_pings/2999-01-01/-MKNkqMNkCV4ENXk7E6_", payload); data = await RunFirebaseOperation(Operation.Read, "/raw_pings/2999-01-01/-MKNkqMNkCV4ENXk7E6_", null); Console.WriteLine(data); await RunFirebaseOperation(Operation.Delete, "/raw_pings/2999-01-01/-MKNkqMNkCV4ENXk7E6_", null); } static void MainAsync(string[] args) { Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"d:\Pinger\pinger-service-account-key.json"); FirebaseDatabaseUrl = String.Format("https://{0}.firebaseio.com", File.ReadAllText(@"d:\Pinger\firebase-project-name.txt").Trim()); FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }); TestInsertReadDelete(); } } }
39.644068
146
0.636383
[ "Apache-2.0" ]
davidair/pinger
TestCLI/Program.cs
4,680
C#
using Pipliz; using System.Collections.Generic; using ModLoaderInterfaces; namespace PvP { public enum AreaType { NotDefined, PvP, NonPvP } public struct Area { public Vector3Int min; public Vector3Int max; public AreaType areaType; public Area(Vector3Int corner1, Vector3Int corner2, AreaType areaType) { this.min = Vector3Int.Min(corner1, corner2); this.max = Vector3Int.Max(corner1, corner2); this.areaType = areaType; } //From Pipliz.BoundsInt public bool Contains(Vector3Int v) { return v >= min && v <= max; } //From Pipliz.BoundsInt public static bool Intersects(Area areaA, Area areaB) { return areaA.max.x >= areaB.min.x && areaA.max.y >= areaB.min.y && areaA.max.z >= areaB.min.z && areaA.min.x <= areaB.max.x && areaA.min.y <= areaB.max.y && areaA.min.z <= areaB.max.z; } } public class AreaManager : IOnPlayerMoved { public static List<Area> areas = new List<Area>(); public static Dictionary<NetworkID, AreaType> playersWithinAnArea = new Dictionary<NetworkID, AreaType>(); public void OnPlayerMoved(Players.Player player, UnityEngine.Vector3 newLocation) { Vector3Int playerPosition = new Vector3Int(player.Position); foreach (var area in areas) { if (area.Contains(playerPosition)) { if (!playersWithinAnArea.ContainsKey(player.ID) || playersWithinAnArea[player.ID] != area.areaType) { PvPPlayerSkin.ChangePlayerSkin(player.ID); Chatting.Chat.Send(player, (area.areaType == AreaType.PvP) ? "You have entered a <color=red>PvP</color> area." : "You have entered a <color=red>Non PvP</color> area."); } playersWithinAnArea[player.ID] = area.areaType; return; } } if (playersWithinAnArea.ContainsKey(player.ID)) { Chatting.Chat.Send(player, (playersWithinAnArea[player.ID] == AreaType.PvP) ? "You have left the <color=red>PvP</color> area." : "You have left the <color=red>Non PvP</color> area."); playersWithinAnArea.Remove(player.ID); PvPPlayerSkin.ChangePlayerSkin(player.ID); } } } }
33.493333
199
0.568073
[ "MIT" ]
Khanx/PvP
PvP/PvP/PvP/AreaManager.cs
2,514
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p8.Pisp.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for /// OBWriteDomesticScheduledConsentResponse5DataStatusEnum. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum OBWriteDomesticScheduledConsentResponse5DataStatusEnum { [EnumMember(Value = "Authorised")] Authorised, [EnumMember(Value = "AwaitingAuthorisation")] AwaitingAuthorisation, [EnumMember(Value = "Consumed")] Consumed, [EnumMember(Value = "Rejected")] Rejected } internal static class OBWriteDomesticScheduledConsentResponse5DataStatusEnumEnumExtension { internal static string ToSerializedValue(this OBWriteDomesticScheduledConsentResponse5DataStatusEnum? value) { return value == null ? null : ((OBWriteDomesticScheduledConsentResponse5DataStatusEnum)value).ToSerializedValue(); } internal static string ToSerializedValue(this OBWriteDomesticScheduledConsentResponse5DataStatusEnum value) { switch( value ) { case OBWriteDomesticScheduledConsentResponse5DataStatusEnum.Authorised: return "Authorised"; case OBWriteDomesticScheduledConsentResponse5DataStatusEnum.AwaitingAuthorisation: return "AwaitingAuthorisation"; case OBWriteDomesticScheduledConsentResponse5DataStatusEnum.Consumed: return "Consumed"; case OBWriteDomesticScheduledConsentResponse5DataStatusEnum.Rejected: return "Rejected"; } return null; } internal static OBWriteDomesticScheduledConsentResponse5DataStatusEnum? ParseOBWriteDomesticScheduledConsentResponse5DataStatusEnum(this string value) { switch( value ) { case "Authorised": return OBWriteDomesticScheduledConsentResponse5DataStatusEnum.Authorised; case "AwaitingAuthorisation": return OBWriteDomesticScheduledConsentResponse5DataStatusEnum.AwaitingAuthorisation; case "Consumed": return OBWriteDomesticScheduledConsentResponse5DataStatusEnum.Consumed; case "Rejected": return OBWriteDomesticScheduledConsentResponse5DataStatusEnum.Rejected; } return null; } } }
40.657143
158
0.673928
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.BankApiModels/UkObRw/V3p1p8/Pisp/Models/OBWriteDomesticScheduledConsentResponse5DataStatusEnum.cs
2,846
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.ComponentModel; namespace System.Windows.Forms { public partial class DomainUpDown { /// <summary> /// Encapsulates a collection of objects for use by the <see cref="DomainUpDown"/> /// class. /// </summary> public class DomainUpDownItemCollection : ArrayList { private readonly DomainUpDown _owner; internal DomainUpDownItemCollection(DomainUpDown owner) : base() { _owner = owner; } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override object? this[int index] { get { return base[index]; } set { base[index] = value; if (_owner.SelectedIndex == index) { _owner.SelectIndex(index); } if (_owner.Sorted) { _owner.SortDomainItems(); } } } /// <summary> /// </summary> public override int Add(object? item) { // Overridden to perform sorting after adding an item int ret = base.Add(item); if (_owner.Sorted) { _owner.SortDomainItems(); } return ret; } /// <summary> /// </summary> public override void Remove(object? item) { int index = IndexOf(item); if (index == -1) { throw new ArgumentOutOfRangeException(nameof(item), item, string.Format(SR.InvalidArgument, nameof(item), item)); } else { RemoveAt(index); } } /// <summary> /// </summary> public override void RemoveAt(int item) { // Overridden to update the domain index if necessary base.RemoveAt(item); if (item < _owner._domainIndex) { // The item removed was before the currently selected item _owner.SelectIndex(_owner._domainIndex - 1); } else if (item == _owner._domainIndex) { // The currently selected item was removed _owner.SelectIndex(-1); } } /// <summary> /// </summary> public override void Insert(int index, object? item) { base.Insert(index, item); if (_owner.Sorted) { _owner.SortDomainItems(); } } } } }
28.991228
133
0.439637
[ "MIT" ]
Kevin7806/winforms
src/System.Windows.Forms/src/System/Windows/Forms/DomainUpDown.DomainUpDownItemCollection.cs
3,307
C#
using Gov.Lclb.Cllb.Interfaces; using Gov.Lclb.Cllb.Public.Models; using Gov.Lclb.Cllb.Public.ViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; // TODO implement this with autorest namespace Gov.Lclb.Cllb.Public.Controllers { [Route("api/[controller]")] [ApiController] [Authorize(Policy = "Business-User")] public class AdoxioLicenceTypeController : ControllerBase { private readonly IDynamicsClient _dynamicsClient; public AdoxioLicenceTypeController(IDynamicsClient dynamicsClient) { _dynamicsClient = dynamicsClient; } /// GET all licence types in Dynamics [HttpGet()] public async Task<JsonResult> GetDynamicsLicenseTypes() { List<LicenseType> adoxioLiceseVMList = new List<LicenseType>(); // get all licence types in Dynamics var adoxioLicenceTypes = await _dynamicsClient.Licencetypes.GetAsync(); foreach (var licenceType in adoxioLicenceTypes.Value) { adoxioLiceseVMList.Add(licenceType.ToViewModel()); } return new JsonResult(adoxioLiceseVMList); } /// GET a specific licence type [HttpGet("{id}")] public ActionResult GetDynamicsLicenseType(string id) { Guid licenceTypeId; if (string.IsNullOrEmpty(id) || !Guid.TryParse(id, out licenceTypeId)) { return new NotFoundResult(); } // get all licenses in Dynamics by Licencee Id var adoxioLicenceType = _dynamicsClient.GetAdoxioLicencetypeById(licenceTypeId); if (adoxioLicenceType == null) { return new NotFoundResult(); } else { return new JsonResult(adoxioLicenceType.ToViewModel()); } } } }
30.089552
92
0.622024
[ "Apache-2.0" ]
ElizabethWolfe/jag-lcrb-carla-public
cllc-public-app/Controllers/AdoxioLicenceTypeController.cs
2,018
C#
using System; using System.Collections.Generic; using System.Linq; public enum Allergen { Eggs, Peanuts, Shellfish, Strawberries, Tomatoes, Chocolate, Pollen, Cats } public class Allergies { private readonly List<Allergen> _allergies; public Allergies(int codedAllergies) => _allergies = Enum.GetValues<Allergen>() .Where((_, shiftLeft) => (codedAllergies & 1 << shiftLeft) != 0) .ToList(); public bool IsAllergicTo(Allergen allergen) => _allergies.Contains(allergen); public List<Allergen> List() => _allergies; }
29.894737
98
0.693662
[ "Apache-2.0" ]
ErikSchierboom/exercism
csharp/allergies/Allergies.cs
568
C#
using Xamarin.Forms; using Xunit; namespace MagicGradients.Tests { public class GradientBuilderTestCases : TheoryData<GradientBuilderTestCase> { public GradientBuilderTestCases() { Add(new LinearTestCase()); Add(new RadialTestCase()); } } public abstract class GradientBuilderTestCase { public abstract void AddGradient(GradientBuilder builder); } public class LinearTestCase : GradientBuilderTestCase { public override void AddGradient(GradientBuilder builder) { builder.AddLinearGradient(45); } } public class RadialTestCase : GradientBuilderTestCase { public override void AddGradient(GradientBuilder builder) { builder.AddRadialGradient( new Point(0.5, 0.5), RadialGradientShape.Circle, RadialGradientSize.ClosestSide); } } }
24.589744
79
0.625652
[ "MIT" ]
filipoff2/MagicGradients
MagicGradients.Tests/GradientBuilderTestCases.cs
961
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CommentSelection { internal interface ICommentSelectionService : ILanguageService { Task<CommentSelectionInfo> GetInfoAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); Task<Document> FormatAsync(Document document, ImmutableArray<TextSpan> changes, SyntaxFormattingOptions formattingOptions, CancellationToken cancellationToken); } }
39.714286
168
0.809353
[ "MIT" ]
AlexanderSemenyak/roslyn
src/Features/Core/Portable/CommentSelection/ICommentSelectionService.cs
836
C#
using System; namespace Thriot.Framework.Logging { public interface ILogger { void Debug(string message); void Debug(string message, params object[] values); void Fatal(string message); void Fatal(string message, params object[] values); void Error(string message); void Error(string message, params object[] values); void Info(string message); void Info(string message, params object[] values); void Trace(string message); void Trace(string message, params object[] values); void Warning(string message); void Warning(string message, params object[] values); void Exception(Exception exception); } }
26.814815
61
0.64779
[ "MIT" ]
kpocza/thriot
Service/Framework/Thriot.Framework/Logging/ILogger.cs
726
C#
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace _008_AsyncAwait_Task_Decompiled_Clean { internal class Program { static void Main(string[] args) { Console.WriteLine($"Main ThreadId {Thread.CurrentThread.ManagedThreadId}"); var my = new MyClass(); var task = my.OperationAsync(100); task.ContinueWith(t => Console.WriteLine($"Result: {t.Result}")); Console.ReadLine(); } } public class MyClass { public int Operation(int arg) { Console.WriteLine($"Operation ThreadId {Thread.CurrentThread.ManagedThreadId}"); Thread.Sleep(2000); return 2 * arg; } public Task<int> OperationAsync(int arg) { AsyncStateMachine stateMachine = new(); stateMachine.outer = this; stateMachine.builder = AsyncTaskMethodBuilder<int>.Create(); stateMachine.state = -1; stateMachine.arg = arg; stateMachine.builder.Start(ref stateMachine); return stateMachine.builder.Task; } [CompilerGenerated] [StructLayout(LayoutKind.Auto)] private class AsyncStateMachine : IAsyncStateMachine { //public AsyncVoidMethodBuilder builder; // for void OperationAsync public AsyncTaskMethodBuilder<int> builder; // for Task OperationAsync public MyClass outer; public int state; public int arg; TaskAwaiter<int> awaiter; void IAsyncStateMachine.MoveNext() { if (state == -1) { awaiter = Task<int>.Factory.StartNew(() => outer.Operation(arg)).GetAwaiter(); state = 0; var stateMachine = this; builder.AwaitOnCompleted(ref awaiter, ref stateMachine); return; } //The task is marked as completed successfully. int result = awaiter.GetResult(); builder.SetResult(result); } void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine) { this.builder.SetStateMachine(stateMachine); } } } }
29.853659
98
0.565359
[ "Apache-2.0" ]
arttonoyan/dotnet-courses
Lesson_AsyncAwait/008_AsyncAwait_Task_Decompiled_Clean/Program.cs
2,450
C#
using MediatR; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { [Method(WorkspaceNames.WorkspaceConfiguration)] public class ConfigurationParams : IRequest<Container<JToken>> { public Container<ConfigurationItem> Items { get; set; } } }
26.230769
66
0.762463
[ "MIT" ]
TanayParikh/csharp-language-server-protocol
src/Protocol/Models/ConfigurationParams.cs
341
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using XInspector.Converters; using XInspector.SampleModels; using XInspector.ViewModels; namespace XInspector.NUnit { [TestFixture] public class ConverterTests { [SetUp] public void SetUp() { ConverterViewModelRegistry.Instance.FindAllConverters(); } [Test] public void PersonTest() { List<IPropertyViewModel> lResult = new InstanceViewModelConverter().Convert(new Simple()); // Assert Assert.That(lResult.Count, Is.EqualTo(3)); } } }
21.424242
102
0.647808
[ "MIT" ]
mastertnt/XInspector
XInspector.NUnit/ConverterTests.cs
709
C#
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. using System; using System.Runtime.InteropServices; using static TorchSharp.torch; using static TorchSharp.torch.nn; #nullable enable namespace TorchSharp { using Modules; namespace Modules { public class RNNCell : torch.nn.Module { internal RNNCell(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { } public new static RNNCell Load(String modelPath) { var res = Module.Load(modelPath); return new RNNCell(res.handle.DangerousGetHandle(), IntPtr.Zero); } [DllImport("LibTorchSharp")] extern static IntPtr THSNN_RNNCell_forward(torch.nn.Module.HType module, IntPtr input, IntPtr h_0); /// <summary> /// Apply the RNN cell to an input tensor. /// </summary> /// <param name="input">Tensor of shape (batch, input_size) containing the features of the input sequence.</param> /// <param name="h0">Tensor of shape (batch, hidden_size) containing the initial hidden state for each element in the batch.</param> /// <returns></returns> public override Tensor forward(Tensor input, Tensor? h0 = null) { var hN = THSNN_RNNCell_forward(handle, input.Handle, h0?.Handle ?? IntPtr.Zero); if (hN == IntPtr.Zero) { torch.CheckForErrors(); } return new Tensor(hN); } [DllImport("LibTorchSharp")] extern static IntPtr THSNN_RNNCell_bias_ih(torch.nn.Module.HType module); [DllImport("LibTorchSharp")] extern static void THSNN_RNNCell_set_bias_ih(torch.nn.Module.HType module, IntPtr tensor); [DllImport("LibTorchSharp")] extern static IntPtr THSNN_RNNCell_bias_hh(torch.nn.Module.HType module); [DllImport("LibTorchSharp")] extern static void THSNN_RNNCell_set_bias_hh(torch.nn.Module.HType module, IntPtr tensor); public Parameter? bias_ih { get { var res = THSNN_RNNCell_bias_ih(handle); if (res == IntPtr.Zero) { torch.CheckForErrors(); } return ((res == IntPtr.Zero) ? null : new Parameter(res)); } set { THSNN_RNNCell_set_bias_ih(handle, (value is null ? IntPtr.Zero : value.Handle)); torch.CheckForErrors(); ConditionallyRegisterParameter("bias_ih", value); } } public Parameter? bias_hh { get { var res = THSNN_RNNCell_bias_hh(handle); if (res == IntPtr.Zero) { torch.CheckForErrors(); } return ((res == IntPtr.Zero) ? null : new Parameter(res)); } set { THSNN_RNNCell_set_bias_hh(handle, (value is null ? IntPtr.Zero : value.Handle)); torch.CheckForErrors(); ConditionallyRegisterParameter("bias_hh", value); } } [DllImport("LibTorchSharp")] extern static IntPtr THSNN_RNNCell_weight_ih(torch.nn.Module.HType module); [DllImport("LibTorchSharp")] extern static void THSNN_RNNCell_set_weight_ih(torch.nn.Module.HType module, IntPtr tensor); [DllImport("LibTorchSharp")] extern static IntPtr THSNN_RNNCell_weight_hh(torch.nn.Module.HType module); [DllImport("LibTorchSharp")] extern static void THSNN_RNNCell_set_weight_hh(torch.nn.Module.HType module, IntPtr tensor); public Parameter weight_ih { get { var res = THSNN_RNNCell_weight_ih(handle); if (res == IntPtr.Zero) { torch.CheckForErrors(); } return new Parameter(res); } set { THSNN_RNNCell_set_weight_ih(handle, value.Handle); torch.CheckForErrors(); ConditionallyRegisterParameter("weight_ih", value); } } public Parameter weight_hh { get { var res = THSNN_RNNCell_weight_hh(handle); if (res == IntPtr.Zero) { torch.CheckForErrors(); } return new Parameter(res); } set { THSNN_RNNCell_set_weight_hh(handle, value.Handle); torch.CheckForErrors(); ConditionallyRegisterParameter("weight_hh", value); } } } } public static partial class torch { public static partial class nn { [DllImport("LibTorchSharp")] private static extern IntPtr THSNN_RNNCell_ctor(long input_size, long hidden_size, long nonlinearity, bool bias, out IntPtr pBoxedModule); /// <summary> /// An Elman RNN cell with tanh or ReLU non-linearity. /// </summary> /// <param name="inputSize">The number of expected features in the input x</param> /// <param name="hiddenSize">The number of features in the hidden state h</param> /// <param name="nonLinearity">The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'</param> /// <param name="bias">If False, then the layer does not use bias weights b_ih and b_hh. Default: True</param> /// <returns></returns> static public RNNCell RNNCell(long inputSize, long hiddenSize, NonLinearities nonLinearity = nn.NonLinearities.Tanh, bool bias = true) { var res = THSNN_RNNCell_ctor(inputSize, hiddenSize, (long)nonLinearity, bias, out var boxedHandle); if (res == IntPtr.Zero) { torch.CheckForErrors(); } return new RNNCell(res, boxedHandle); } } } }
43.77305
150
0.566105
[ "MIT" ]
dayo05/TorchSharp
src/TorchSharp/NN/Recurrent/RNNCell.cs
6,172
C#
using System.Collections.Generic; using RimWorld; using SirRandoo.ToolkitRaids.Interfaces; using Verse; namespace SirRandoo.ToolkitRaids.Workers.Effects { public class DefaultEffect : IEffectWorker { private static readonly List<HediffDef> Effects = new List<HediffDef> { DrugHediffs.FlakeHigh, DrugHediffs.GoJuiceHigh, DrugHediffs.LuciferiumHigh, DrugHediffs.WakeUpHigh, DrugHediffs.YayoHigh }; public float Chance { get { #if DEBUG return 1f; #else return 0.1f; #endif } } public void Apply(Pawn pawn) { HediffDef drugHediff = Effects.RandomElement(); HediffGiverUtility.TryApply(pawn, drugHediff, null); if (drugHediff == DrugHediffs.LuciferiumHigh && !Rand.Chance(Settings.AddictionlessLuciferium)) { HediffGiverUtility.TryApply(pawn, DrugHediffs.LuciferiumAddiction, null); } } } }
25.953488
107
0.5681
[ "MIT" ]
SirRandoo/ToolkitRaids
ToolkitRaids/Workers/Effects/DefaultEffect.cs
1,118
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Commands.Common.Compute.Version_2018_04 { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SnapshotsOperations operations. /// </summary> internal partial class SnapshotsOperations : IServiceOperations<ComputeManagementClient>, ISnapshotsOperations { /// <summary> /// Initializes a new instance of the SnapshotsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SnapshotsOperations(ComputeManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ComputeManagementClient /// </summary> public ComputeManagementClient Client { get; private set; } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Snapshot>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Snapshot snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Snapshot> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Snapshot>> UpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Snapshot> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets information about a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Snapshot>> GetWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (snapshotName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshotName"); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("snapshotName", snapshotName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{snapshotName}", System.Uri.EscapeDataString(snapshotName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Snapshot>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Snapshot>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<OperationStatusResponse>> DeleteWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<OperationStatusResponse> _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, snapshotName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Snapshot>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Snapshot>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Snapshot>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Snapshot>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/snapshots").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Snapshot>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Snapshot>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<AccessUri>> GrantAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<AccessUri> _response = await BeginGrantAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, grantAccessData, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<OperationStatusResponse>> RevokeAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<OperationStatusResponse> _response = await BeginRevokeAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Snapshot>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Snapshot snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (snapshotName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshotName"); } if (snapshot == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshot"); } if (snapshot != null) { snapshot.Validate(); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("snapshotName", snapshotName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("snapshot", snapshot); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{snapshotName}", System.Uri.EscapeDataString(snapshotName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(snapshot != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(snapshot, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Snapshot>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Snapshot>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Snapshot>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Snapshot>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (snapshotName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshotName"); } if (snapshot == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshot"); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("snapshotName", snapshotName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("snapshot", snapshot); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{snapshotName}", System.Uri.EscapeDataString(snapshotName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(snapshot != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(snapshot, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Snapshot>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Snapshot>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Snapshot>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationStatusResponse>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (snapshotName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshotName"); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("snapshotName", snapshotName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{snapshotName}", System.Uri.EscapeDataString(snapshotName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationStatusResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationStatusResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AccessUri>> BeginGrantAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (snapshotName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshotName"); } if (grantAccessData == null) { throw new ValidationException(ValidationRules.CannotBeNull, "grantAccessData"); } if (grantAccessData != null) { grantAccessData.Validate(); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("snapshotName", snapshotName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("grantAccessData", grantAccessData); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginGrantAccess", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/beginGetAccess").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{snapshotName}", System.Uri.EscapeDataString(snapshotName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(grantAccessData != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(grantAccessData, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AccessUri>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AccessUri>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot that is being created. The name can't be changed /// after the snapshot is created. Supported characters for the name are a-z, /// A-Z, 0-9 and _. The max name length is 80 characters. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationStatusResponse>> BeginRevokeAccessWithHttpMessagesAsync(string resourceGroupName, string snapshotName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (snapshotName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "snapshotName"); } string apiVersion = "2018-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("snapshotName", snapshotName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginRevokeAccess", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/snapshots/{snapshotName}/endGetAccess").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{snapshotName}", System.Uri.EscapeDataString(snapshotName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationStatusResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationStatusResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Snapshot>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Snapshot>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Snapshot>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Snapshot>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Snapshot>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Snapshot>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
48.109977
300
0.554511
[ "MIT" ]
Azure/azure-powershell-common
src/Compute/Version2018_04_01/SnapshotsOperations.cs
103,677
C#
using System.Resources; 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("$safeprojectname$")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("$registeredorganization$")] [assembly: AssemblyProduct("$safeprojectname$")] [assembly: AssemblyCopyright("Copyright © $registeredorganization$ $year$")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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")]
36.741935
84
0.748903
[ "MIT" ]
NewBLife/Prism.Forms.Plugin
TemplatesForPrism/ProjectTemplates/Prism.Forms.Plugin/Prism.Forms.Plugin.Abstractions/Properties/AssemblyInfo.cs
1,142
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace SitecoreBlazorHosted.Shared.Models { public class BlazorSitecoreField<T> : IBlazorSitecoreField { public T Value { get; set; } public string Editable { get; set; } public string Type { get; set; } public string FieldName { get; set; } } }
21.105263
62
0.67581
[ "Apache-2.0" ]
OsvaldoMartini/Blazor_Projects
SitecoreBlazor/SitecoreBlazorHosted.Shared/Models/BlazorSitecoreField.cs
403
C#
// // Copyright (c) Rubal Walia. All rights reserved. // Licensed under the 3-Clause BSD license. See LICENSE file in the project root for full license information. // using Jaya.Shared.Models; using System; namespace Jaya.Provider.FileSystem.Models { public class AccountModel: AccountModelBase { public AccountModel() : base(Environment.MachineName, Environment.MachineName) { } } }
24.222222
110
0.68578
[ "BSD-3-Clause" ]
JayaFM/Jaya
src/Jaya.Provider.FileSystem/Models/AccountModel.cs
438
C#
#region license /* Copyright (c) 2013, Milosz Krajewski All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.IO; namespace LittleTushy.Client.LZ4 { // ReSharper disable once PartialTypeWithSinglePart /// <summary>Block compression stream. Allows to use LZ4 for stream compression.</summary> public partial class LZ4Stream: Stream { #region ChunkFlags /// <summary> /// Flags of a chunk. Please note, this /// </summary> [Flags] public enum ChunkFlags { /// <summary>None.</summary> None = 0x00, /// <summary>Set if chunk is compressed.</summary> Compressed = 0x01, /// <summary>Set if high compression has been selected (does not affect decoder, /// but might be useful when rewriting)</summary> HighCompression = 0x02, /// <summary>3 bits for number of passes. Currently only 1 pass (value 0) /// is supported.</summary> Passes = 0x04 | 0x08 | 0x10, // not used currently } #endregion #region fields /// <summary>The inner stream.</summary> private readonly Stream _innerStream; /// <summary>The compression mode.</summary> private readonly LZ4StreamMode _compressionMode; /// <summary>The high compression flag (compression only).</summary> private readonly bool _highCompression; /// <summary>Determines if reading tries to return something ASAP or wait /// for full chunk (decompression only).</summary> private readonly bool _interactiveRead; /// <summary>Isolates inner stream which will not be closed /// when this stream is closed.</summary> private readonly bool _isolateInnerStream; /// <summary>The block size (compression only).</summary> private readonly int _blockSize; /// <summary>The buffer.</summary> private byte[] _buffer; /// <summary>The buffer length (can be different then _buffer.Length).</summary> private int _bufferLength; /// <summary>The offset in a buffer.</summary> private int _bufferOffset; #endregion #region constructor /// <summary>Initializes a new instance of the <see cref="LZ4Stream" /> class.</summary> /// <param name="innerStream">The inner stream.</param> /// <param name="compressionMode">The compression mode.</param> /// <param name="highCompression">if set to <c>true</c> high compression is used.</param> /// <param name="blockSize">Size of the block.</param> /// <param name="interactiveRead">if set to <c>true</c> interactive read mode is used. /// It means that <see cref="Read"/> method tries to return data as soon as possible. /// Please note, that this should be default behavior but has been made optional for /// backward compatibility. This constructor will be changed in next major release.</param> [Obsolete("This constructor is obsolete")] public LZ4Stream( Stream innerStream, LZ4StreamMode compressionMode, bool highCompression, int blockSize = 1024*1024, bool interactiveRead = false) { _innerStream = innerStream; _compressionMode = compressionMode; _highCompression = highCompression; _interactiveRead = interactiveRead; _isolateInnerStream = false; _blockSize = Math.Max(16, blockSize); } /// <summary>Initializes a new instance of the <see cref="LZ4Stream" /> class.</summary> /// <param name="innerStream">The inner stream.</param> /// <param name="compressionMode">The compression mode.</param> /// <param name="compressionFlags">The compression flags.</param> /// <param name="blockSize">Size of the block.</param> public LZ4Stream( Stream innerStream, LZ4StreamMode compressionMode, LZ4StreamFlags compressionFlags = LZ4StreamFlags.Default, int blockSize = 1024*1024) { _innerStream = innerStream; _compressionMode = compressionMode; _highCompression = (compressionFlags & LZ4StreamFlags.HighCompression) != 0; _interactiveRead = (compressionFlags & LZ4StreamFlags.InteractiveRead) != 0; _isolateInnerStream = (compressionFlags & LZ4StreamFlags.IsolateInnerStream) != 0; _blockSize = Math.Max(16, blockSize); } #endregion #region utilities /// <summary>Returns NotSupportedException.</summary> /// <param name="operationName">Name of the operation.</param> /// <returns>NotSupportedException</returns> private static NotSupportedException NotSupported(string operationName) { return new NotSupportedException( string.Format( "Operation '{0}' is not supported", operationName)); } /// <summary>Returns EndOfStreamException.</summary> /// <returns>EndOfStreamException</returns> private static EndOfStreamException EndOfStream() { return new EndOfStreamException("Unexpected end of stream"); } /// <summary>Tries to read variable length int.</summary> /// <param name="result">The result.</param> /// <returns><c>true</c> if integer has been read, <c>false</c> if end of stream has been /// encountered. If end of stream has been encountered in the middle of value /// <see cref="EndOfStreamException"/> is thrown.</returns> private bool TryReadVarInt(out ulong result) { var buffer = new byte[1]; var count = 0; result = 0; while (true) { if (_innerStream.Read(buffer, 0, 1) == 0) { if (count == 0) return false; throw EndOfStream(); } var b = buffer[0]; result = result + ((ulong)(b & 0x7F) << count); count += 7; if ((b & 0x80) == 0 || count >= 64) break; } return true; } /// <summary>Reads the variable length int. Work with assumption that value is in the stream /// and throws exception if it isn't. If you want to check if value is in the stream /// use <see cref="TryReadVarInt"/> instead.</summary> /// <returns></returns> private ulong ReadVarInt() { ulong result; if (!TryReadVarInt(out result)) throw EndOfStream(); return result; } /// <summary>Reads the block of bytes. /// Contrary to <see cref="Stream.Read"/> does not read partial data if possible. /// If there is no data (yet) it waits.</summary> /// <param name="buffer">The buffer.</param> /// <param name="offset">The offset.</param> /// <param name="length">The length.</param> /// <returns>Number of bytes read.</returns> private int ReadBlock(byte[] buffer, int offset, int length) { var total = 0; while (length > 0) { var read = _innerStream.Read(buffer, offset, length); if (read == 0) break; offset += read; length -= read; total += read; } return total; } /// <summary>Writes the variable length integer.</summary> /// <param name="value">The value.</param> private void WriteVarInt(ulong value) { var buffer = new byte[1]; while (true) { var b = (byte)(value & 0x7F); value >>= 7; buffer[0] = (byte)(b | (value == 0 ? 0 : 0x80)); _innerStream.Write(buffer, 0, 1); if (value == 0) break; } } /// <summary>Flushes current chunk.</summary> private void FlushCurrentChunk() { if (_bufferOffset <= 0) return; var compressed = new byte[_bufferOffset]; var compressedLength = _highCompression ? LZ4Codec.EncodeHC(_buffer, 0, _bufferOffset, compressed, 0, _bufferOffset) : LZ4Codec.Encode(_buffer, 0, _bufferOffset, compressed, 0, _bufferOffset); if (compressedLength <= 0 || compressedLength >= _bufferOffset) { // incompressible block compressed = _buffer; compressedLength = _bufferOffset; } var isCompressed = compressedLength < _bufferOffset; var flags = ChunkFlags.None; if (isCompressed) flags |= ChunkFlags.Compressed; if (_highCompression) flags |= ChunkFlags.HighCompression; WriteVarInt((ulong)flags); WriteVarInt((ulong)_bufferOffset); if (isCompressed) WriteVarInt((ulong)compressedLength); _innerStream.Write(compressed, 0, compressedLength); _bufferOffset = 0; } /// <summary>Reads the next chunk from stream.</summary> /// <returns><c>true</c> if next has been read, or <c>false</c> if it is legitimate end of file. /// Throws <see cref="EndOfStreamException"/> if end of stream was unexpected.</returns> private bool AcquireNextChunk() { do { ulong varint; if (!TryReadVarInt(out varint)) return false; var flags = (ChunkFlags)varint; var isCompressed = (flags & ChunkFlags.Compressed) != 0; var originalLength = (int)ReadVarInt(); var compressedLength = isCompressed ? (int)ReadVarInt() : originalLength; if (compressedLength > originalLength) throw EndOfStream(); // corrupted var compressed = new byte[compressedLength]; var chunk = ReadBlock(compressed, 0, compressedLength); if (chunk != compressedLength) throw EndOfStream(); // corrupted if (!isCompressed) { _buffer = compressed; // no compression on this chunk _bufferLength = compressedLength; } else { if (_buffer == null || _buffer.Length < originalLength) _buffer = new byte[originalLength]; var passes = (int)flags >> 2; if (passes != 0) throw new NotSupportedException("Chunks with multiple passes are not supported."); LZ4Codec.Decode(compressed, 0, compressedLength, _buffer, 0, originalLength, true); _bufferLength = originalLength; } _bufferOffset = 0; } while (_bufferLength == 0); // skip empty block (shouldn't happen but...) return true; } #endregion #region overrides /// <summary>When overridden in a derived class, gets a value indicating whether the current stream supports reading.</summary> /// <returns>true if the stream supports reading; otherwise, false.</returns> public override bool CanRead { get { return _compressionMode == LZ4StreamMode.Decompress; } } /// <summary>When overridden in a derived class, gets a value indicating whether the current stream supports seeking.</summary> /// <returns>true if the stream supports seeking; otherwise, false.</returns> public override bool CanSeek { get { return false; } } /// <summary>When overridden in a derived class, gets a value indicating whether the current stream supports writing.</summary> /// <returns>true if the stream supports writing; otherwise, false.</returns> public override bool CanWrite { get { return _compressionMode == LZ4StreamMode.Compress; } } /// <summary>When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.</summary> public override void Flush() { if (_bufferOffset > 0 && CanWrite) FlushCurrentChunk(); } /// <summary>When overridden in a derived class, gets the length in bytes of the stream.</summary> /// <returns>A long value representing the length of the stream in bytes.</returns> public override long Length { get { return -1; } } /// <summary>When overridden in a derived class, gets or sets the position within the current stream.</summary> /// <returns>The current position within the stream.</returns> public override long Position { get { return -1; } set { throw NotSupported("SetPosition"); } } /// <summary>Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.</summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { if (!CanRead) throw NotSupported("Read"); if (_bufferOffset >= _bufferLength && !AcquireNextChunk()) return -1; // that's just end of stream return _buffer[_bufferOffset++]; } /// <summary>When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.</summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> public override int Read(byte[] buffer, int offset, int count) { if (!CanRead) throw NotSupported("Read"); var total = 0; while (count > 0) { var chunk = Math.Min(count, _bufferLength - _bufferOffset); if (chunk > 0) { Buffer.BlockCopy(_buffer, _bufferOffset, buffer, offset, chunk); _bufferOffset += chunk; total += chunk; if (_interactiveRead) break; offset += chunk; count -= chunk; } else { if (!AcquireNextChunk()) break; } } return total; } /// <summary>When overridden in a derived class, sets the position within the current stream.</summary> /// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param> /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> public override long Seek(long offset, SeekOrigin origin) { throw NotSupported("Seek"); } /// <summary>When overridden in a derived class, sets the length of the current stream.</summary> /// <param name="value">The desired length of the current stream in bytes.</param> public override void SetLength(long value) { throw NotSupported("SetLength"); } /// <summary>Writes a byte to the current position in the stream and advances the position within the stream by one byte.</summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) { if (!CanWrite) throw NotSupported("Write"); if (_buffer == null) { _buffer = new byte[_blockSize]; _bufferLength = _blockSize; _bufferOffset = 0; } if (_bufferOffset >= _bufferLength) { FlushCurrentChunk(); } _buffer[_bufferOffset++] = value; } /// <summary>When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.</summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> public override void Write(byte[] buffer, int offset, int count) { if (!CanWrite) throw NotSupported("Write"); if (_buffer == null) { _buffer = new byte[_blockSize]; _bufferLength = _blockSize; _bufferOffset = 0; } while (count > 0) { var chunk = Math.Min(count, _bufferLength - _bufferOffset); if (chunk > 0) { Buffer.BlockCopy(buffer, offset, _buffer, _bufferOffset, chunk); offset += chunk; count -= chunk; _bufferOffset += chunk; } else { FlushCurrentChunk(); } } } /// <summary>Releases the unmanaged resources used by the <see cref="T:System.IO.Stream" /> and optionally releases the managed resources.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { Flush(); if (!_isolateInnerStream) _innerStream.Dispose(); base.Dispose(disposing); } #endregion } }
35.523711
292
0.697487
[ "MIT" ]
keithwill/LittleTushy
src/LittleTushy.Client/LZ4.netcore/LZ4Stream.cs
17,231
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO.Pipelines; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Azure.SignalR.IntegrationTests.Infrastructure; namespace Microsoft.Azure.SignalR.IntegrationTests.MockService { internal interface IMockService { public MockServiceSideConnection RegisterSDKConnectionContext(MockServiceConnectionContext sdkSIdeConnCtx, HubServiceEndpoint endpoint, string target, IDuplexPipe pipe); public void RegisterSDKConnection(MockServiceConnection sdkSideConnection); public bool RemoveUnregisteredConnections { get; set; } public void UnregisterMockServiceSideConnection(MockServiceSideConnection conn); public void UnregisterMockServiceConnection(MockServiceConnectionContext conn); List<MockServiceSideConnection> ServiceSideConnections { get; } IInvocationBinder CurrentInvocationBinder { get; set; } Task AllConnectionsEstablished(); } }
49.478261
177
0.799649
[ "MIT" ]
Arash-Sabet/azure-signalr
test/Microsoft.Azure.SignalR.IntegrationTests/MockService/IMockService.cs
1,138
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.Networking; namespace CatAsset { /// <summary> /// 下载文件任务 /// </summary> public class DownloadFileTask : BaseTask { private UnityWebRequestAsyncOperation op; /// <summary> /// AssetBundle清单信息 /// </summary> private BundleManifestInfo bundleInfo; /// <summary> /// 发起此下载任务的更新器 /// </summary> private Updater updater; /// <summary> /// 下载地址 /// </summary> private string downloadUri; /// <summary> /// 本地文件路径 /// </summary> private string localFilePath; /// <summary> /// 本地临时文件路径 /// </summary> private string localTempFilePath; private Action<bool,BundleManifestInfo> onFinished; internal override Delegate FinishedCallback { get { return onFinished; } set { onFinished = (Action<bool, BundleManifestInfo>)value; } } public override float Progress { get { if (op == null) { return 0; } return op.progress; } } public DownloadFileTask(TaskExcutor owner, string name,BundleManifestInfo bundleInfo,Updater updater, string localFilePath, string downloadUri, Action<bool,BundleManifestInfo> onFinished) : base(owner, name) { this.bundleInfo = bundleInfo; this.updater = updater; this.localFilePath = localFilePath; this.downloadUri = downloadUri; this.onFinished = onFinished; } public override void Execute() { if (updater.state == UpdaterStatus.Paused) { //处理下载暂停 暂停只对还未开始执行的下载任务有效 return; } localTempFilePath = localFilePath + ".downloading"; //开始位置 int startLength = 0; //先检查本地是否已存在临时下载文件 if (File.Exists(localTempFilePath)) { using (FileStream fs = File.OpenWrite(localTempFilePath)) { //检查已下载的字节数 fs.Seek(0, SeekOrigin.End); startLength = (int)fs.Length; } } UnityWebRequest uwr = new UnityWebRequest(downloadUri); if (startLength > 0) { //处理断点续传 uwr.SetRequestHeader("Range", $"bytes={{{startLength}}}-"); } uwr.downloadHandler = new DownloadHandlerFile(localTempFilePath, startLength > 0); op = uwr.SendWebRequest(); } public override void Update() { if (op == null) { //被暂停了 TaskState = TaskStatus.Free; return; } if (!op.webRequest.isDone) { //下载中 TaskState = TaskStatus.Executing; return; } //下载完毕 TaskState = TaskStatus.Finished; if (op.webRequest.isNetworkError || op.webRequest.isHttpError) { //下载失败 Debug.LogError($"下载失败:{Name},错误信息:{op.webRequest.error}"); onFinished?.Invoke(false , bundleInfo); return; } Debug.Log("下载成功:" + Name); //下载成功 //TODO:文件校验 //将临时下载文件移动到正式文件 if (File.Exists(localFilePath)) { File.Delete(localFilePath); } File.Move(localTempFilePath, localFilePath); onFinished?.Invoke(true,bundleInfo); } } }
24.262195
215
0.481779
[ "MIT" ]
ErQing/CatAsset
Assets/CatAsset/Runtime/TaskSystem/Tasks/DownloadFileTask.cs
4,279
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.ComponentModel; namespace Azure.ResourceManager.Sql.Models { /// <summary> Whether or not public endpoint access is allowed for this server. Value is optional but if passed in, must be &apos;Enabled&apos; or &apos;Disabled&apos;. </summary> public readonly partial struct ServerPublicNetworkAccess : IEquatable<ServerPublicNetworkAccess> { private readonly string _value; /// <summary> Determines if two <see cref="ServerPublicNetworkAccess"/> values are the same. </summary> /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception> public ServerPublicNetworkAccess(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } private const string EnabledValue = "Enabled"; private const string DisabledValue = "Disabled"; /// <summary> Enabled. </summary> public static ServerPublicNetworkAccess Enabled { get; } = new ServerPublicNetworkAccess(EnabledValue); /// <summary> Disabled. </summary> public static ServerPublicNetworkAccess Disabled { get; } = new ServerPublicNetworkAccess(DisabledValue); /// <summary> Determines if two <see cref="ServerPublicNetworkAccess"/> values are the same. </summary> public static bool operator ==(ServerPublicNetworkAccess left, ServerPublicNetworkAccess right) => left.Equals(right); /// <summary> Determines if two <see cref="ServerPublicNetworkAccess"/> values are not the same. </summary> public static bool operator !=(ServerPublicNetworkAccess left, ServerPublicNetworkAccess right) => !left.Equals(right); /// <summary> Converts a string to a <see cref="ServerPublicNetworkAccess"/>. </summary> public static implicit operator ServerPublicNetworkAccess(string value) => new ServerPublicNetworkAccess(value); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ServerPublicNetworkAccess other && Equals(other); /// <inheritdoc /> public bool Equals(ServerPublicNetworkAccess other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; /// <inheritdoc /> public override string ToString() => _value; } }
51.076923
184
0.702184
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/ServerPublicNetworkAccess.cs
2,656
C#
//----------------------------------------------------------------------- // ETP DevKit, 1.2 // // Copyright 2021 Energistics // // 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. //----------------------------------------------------------------------- // //----------------------------------------------------------------------- // This code has been automatically generated. // Changes will be lost the next time it is regenerated. //----------------------------------------------------------------------- using Energistics.Avro; namespace Energistics.Etp.v12.Datatypes { [AvroNamedType("EndpointCapabilityKind", "Energistics.Etp.v12.Datatypes")] public enum EndpointCapabilityKind { [AvroEnumSymbol("ActiveTimeoutPeriod")] ActiveTimeoutPeriod, [AvroEnumSymbol("AuthorizationDetails")] AuthorizationDetails, [AvroEnumSymbol("ChangePropagationPeriod")] ChangePropagationPeriod, [AvroEnumSymbol("ChangeRetentionPeriod")] ChangeRetentionPeriod, [AvroEnumSymbol("MaxConcurrentMultipart")] MaxConcurrentMultipart, [AvroEnumSymbol("MaxDataObjectSize")] MaxDataObjectSize, [AvroEnumSymbol("MaxPartSize")] MaxPartSize, [AvroEnumSymbol("MaxSessionClientCount")] MaxSessionClientCount, [AvroEnumSymbol("MaxSessionGlobalCount")] MaxSessionGlobalCount, [AvroEnumSymbol("MaxWebSocketFramePayloadSize")] MaxWebSocketFramePayloadSize, [AvroEnumSymbol("MaxWebSocketMessagePayloadSize")] MaxWebSocketMessagePayloadSize, [AvroEnumSymbol("MultipartMessageTimeoutPeriod")] MultipartMessageTimeoutPeriod, [AvroEnumSymbol("ResponseTimeoutPeriod")] ResponseTimeoutPeriod, [AvroEnumSymbol("RequestSessionTimeoutPeriod")] RequestSessionTimeoutPeriod, [AvroEnumSymbol("SessionEstablishmentTimeoutPeriod")] SessionEstablishmentTimeoutPeriod, [AvroEnumSymbol("SupportsAlternateRequestUris")] SupportsAlternateRequestUris, [AvroEnumSymbol("SupportsMessageHeaderExtensions")] SupportsMessageHeaderExtensions, } }
40.089552
78
0.64073
[ "Apache-2.0" ]
pds-technology/etp.net
src/ETP.Messages/v12/Datatypes/EndpointCapabilityKind.cs
2,688
C#
using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UACHelper.Native.ComInterop { [ComImport] [Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85")] internal interface IShellWindows { // ReSharper disable once IdentifierTypo void _VtblGap0_8(); // Skip 8 members. [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] [return: MarshalAs(UnmanagedType.IDispatch)] // ReSharper disable once TooManyArguments object FindWindowSW( [MarshalAs(UnmanagedType.Struct)] [In] ref object locationPIDL, [MarshalAs(UnmanagedType.Struct)] [In] ref object locationRootPIDL, [In] ShellWindowsClass windowClass, out int windowHandle, [In] ShellWindowsFindOptions options ); } }
35.75
93
0.685315
[ "MIT" ]
IMULMUL/UACHelper
UACHelper/Native/ComInterop/IShellWindows.cs
860
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.IO.Compression; using Windows.Security.Cryptography; using Windows.Security.Cryptography.Core; using Windows.Storage.Streams; using AppStudio.DataProviders.Exceptions; using Newtonsoft.Json; namespace AppStudio.DataProviders.Twitter { public class TwitterDataProvider : DataProviderBase<TwitterDataConfig, TwitterSchema> { private TwitterOAuthTokens _tokens; private const string BaseUrl = "https://api.twitter.com/1.1"; public override bool HasMoreItems { get { return !string.IsNullOrEmpty(ContinuationToken); } } public TwitterDataProvider(TwitterOAuthTokens tokens) { _tokens = tokens; } protected override async Task<IEnumerable<TSchema>> GetDataAsync<TSchema>(TwitterDataConfig config, int pageSize, IParser<TSchema> parser) { IEnumerable<TSchema> items; switch (config.QueryType) { case TwitterQueryType.User: items = await GetUserTimeLineAsync(config.Query, pageSize, parser); break; case TwitterQueryType.Search: items = await SearchAsync(config.Query, pageSize, parser); break; case TwitterQueryType.Home: default: items = await GetHomeTimeLineAsync(pageSize, parser); break; } return items; } protected override async Task<IEnumerable<TSchema>> GetMoreDataAsync<TSchema>(TwitterDataConfig config, int pageSize, IParser<TSchema> parser) { IEnumerable<TSchema> items; switch (config.QueryType) { case TwitterQueryType.User: items = await GetMoreUserTimeLineAsync(config.Query, pageSize, parser); break; case TwitterQueryType.Search: items = await SearchMoreAsync(config.Query, pageSize, parser); break; case TwitterQueryType.Home: default: items = await GetMoreHomeTimeLineAsync(pageSize, parser); break; } return items; } public async Task<IEnumerable<TwitterSchema>> GetUserTimeLineAsync(string screenName, int pageSize) { return await GetUserTimeLineAsync(screenName, pageSize, new TwitterTimelineParser()); } public async Task<IEnumerable<TSchema>> GetUserTimeLineAsync<TSchema>(string screenName, int pageSize, IParser<TSchema> parser) where TSchema : SchemaBase { var url = GetUserTimeLineUrl(screenName, pageSize); var uri = new Uri(url); return await GetDataFromProvider(parser, uri); } public async Task<IEnumerable<TwitterSchema>> GetMoreUserTimeLineAsync(string screenName, int pageSize) { return await GetMoreUserTimeLineAsync(screenName, pageSize, new TwitterTimelineParser()); } public async Task<IEnumerable<TSchema>> GetMoreUserTimeLineAsync<TSchema>(string screenName, int pageSize, IParser<TSchema> parser) where TSchema : SchemaBase { var url = GetUserTimeLineUrl(screenName, pageSize); if (HasMoreItems) { url += $"&max_id={ContinuationToken}"; } var uri = new Uri(url); return await GetDataFromProvider(parser, uri); } public async Task<IEnumerable<TwitterSchema>> SearchAsync(string hashTag, int pageSize) { return await SearchAsync(hashTag, pageSize, new TwitterSearchParser()); } public async Task<IEnumerable<TwitterSchema>> SearchMoreAsync(string hashTag, int pageSize) { return await SearchMoreAsync(hashTag, pageSize, new TwitterSearchParser()); } public async Task<IEnumerable<TSchema>> SearchAsync<TSchema>(string hashTag, int pageSize, IParser<TSchema> parser) where TSchema : SchemaBase { var url = GetSearchUrl(hashTag, pageSize); var uri = new Uri(url); return await GetDataFromProvider(parser, uri); } public async Task<IEnumerable<TSchema>> SearchMoreAsync<TSchema>(string hashTag, int pageSize, IParser<TSchema> parser) where TSchema : SchemaBase { var url = GetSearchUrl(hashTag, pageSize); if (HasMoreItems) { url += $"&max_id={ContinuationToken}"; } var uri = new Uri(url); return await GetDataFromProvider(parser, uri); } protected override IParser<TwitterSchema> GetDefaultParserInternal(TwitterDataConfig config) { if (config == null) { throw new ConfigNullException(); } switch (config.QueryType) { case TwitterQueryType.Search: return new TwitterSearchParser(); case TwitterQueryType.Home: case TwitterQueryType.User: default: return new TwitterTimelineParser(); } } protected override void ValidateConfig(TwitterDataConfig config) { if (config == null) { throw new ConfigNullException(); } if (config.Query == null && config.QueryType != TwitterQueryType.Home) { throw new ConfigParameterNullException("Query"); } if (_tokens == null) { throw new ConfigParameterNullException("Tokens"); } if (string.IsNullOrEmpty(_tokens.ConsumerKey)) { throw new OAuthKeysNotPresentException("ConsumerKey"); } if (string.IsNullOrEmpty(_tokens.ConsumerSecret)) { throw new OAuthKeysNotPresentException("ConsumerSecret"); } if (string.IsNullOrEmpty(_tokens.AccessToken)) { throw new OAuthKeysNotPresentException("AccessToken"); } if (string.IsNullOrEmpty(_tokens.AccessTokenSecret)) { throw new OAuthKeysNotPresentException("AccessTokenSecret"); } } private async Task<IEnumerable<TSchema>> GetHomeTimeLineAsync<TSchema>(int pageSize, IParser<TSchema> parser) where TSchema : SchemaBase { var url = GetHomeTimeLineUrl(pageSize); var uri = new Uri(url); return await GetDataFromProvider(parser, uri); } private async Task<IEnumerable<TSchema>> GetMoreHomeTimeLineAsync<TSchema>(int pageSize, IParser<TSchema> parser) where TSchema : SchemaBase { var url = GetHomeTimeLineUrl(pageSize); if (HasMoreItems) { url += $"&max_id={ContinuationToken}"; } var uri = new Uri(url); return await GetDataFromProvider(parser, uri); } private async Task<IEnumerable<TSchema>> GetDataFromProvider<TSchema>(IParser<TSchema> parser, Uri uri) where TSchema : SchemaBase { try { OAuthRequest request = new OAuthRequest(); var rawResult = await request.ExecuteAsync(uri, _tokens); var items = await parser.ParseAsync(rawResult); ContinuationToken = await GetContinuationTokenAsync(rawResult); return items; } catch (WebException wex) { HttpWebResponse response = wex.Response as HttpWebResponse; if (response != null) { if ((int)response.StatusCode == 429) { throw new TooManyRequestsException(); } if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new OAuthKeysRevokedException(); } } throw; } } private static string GetUserTimeLineUrl(string screenName, int pageSize) { var url = $"{BaseUrl}/statuses/user_timeline.json?screen_name={screenName}&count={pageSize}&include_rts=1"; return url; } private static string GetHomeTimeLineUrl(int pageSize) { var url = $"{BaseUrl}/statuses/home_timeline.json?count={pageSize}"; return url; } private static string GetSearchUrl(string hashTag, int pageSize) { var url = $"{BaseUrl}/search/tweets.json?q={Uri.EscapeDataString(hashTag)}&count={pageSize}"; return url; } private async Task<string> GetContinuationTokenAsync(string data) { var defaultParser = GetDefaultParser(Config); var items = await defaultParser.ParseAsync(data); var id_str = items?.LastOrDefault()?._id; long id; if (long.TryParse(id_str, out id)) { var result = id - 1; return result.ToString(); } return string.Empty; } } internal class OAuthRequest { public async Task<string> ExecuteAsync(Uri requestUri, TwitterOAuthTokens tokens) { string result = string.Empty; var request = CreateRequest(requestUri, tokens); var response = await request.GetResponseAsync(); var responseStream = GetResponseStream(response); using (StreamReader sr = new StreamReader(responseStream)) { result = sr.ReadToEnd(); } return result; } private static Stream GetResponseStream(WebResponse response) { var encoding = response.Headers["content-encoding"]; if (encoding != null && encoding == "gzip") { return new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); } else { return response.GetResponseStream(); } } private static WebRequest CreateRequest(Uri requestUri, TwitterOAuthTokens tokens) { var requestBuilder = new OAuthRequestBuilder(requestUri, tokens); var request = (HttpWebRequest)WebRequest.Create(requestBuilder.EncodedRequestUri); request.UseDefaultCredentials = true; request.Method = OAuthRequestBuilder.Verb; request.Headers["Authorization"] = requestBuilder.AuthorizationHeader; return request; } } internal class OAuthRequestBuilder { public const string Realm = "Twitter API"; public const string Verb = "GET"; public Uri EncodedRequestUri { get; private set; } public Uri RequestUriWithoutQuery { get; private set; } public IEnumerable<OAuthParameter> QueryParams { get; private set; } public OAuthParameter Version { get; private set; } public OAuthParameter Nonce { get; private set; } public OAuthParameter Timestamp { get; private set; } public OAuthParameter SignatureMethod { get; private set; } public OAuthParameter ConsumerKey { get; private set; } public OAuthParameter ConsumerSecret { get; private set; } public OAuthParameter Token { get; private set; } public OAuthParameter TokenSecret { get; private set; } public OAuthParameter Signature { get { return new OAuthParameter("oauth_signature", GenerateSignature()); } } public string AuthorizationHeader { get { return GenerateAuthorizationHeader(); } } public OAuthRequestBuilder(Uri requestUri, TwitterOAuthTokens tokens) { RequestUriWithoutQuery = new Uri(requestUri.AbsoluteWithoutQuery()); QueryParams = requestUri.GetQueryParams() .Select(p => new OAuthParameter(p.Key, p.Value)) .ToList(); EncodedRequestUri = GetEncodedUri(requestUri, QueryParams); Version = new OAuthParameter("oauth_version", "1.0"); Nonce = new OAuthParameter("oauth_nonce", GenerateNonce()); Timestamp = new OAuthParameter("oauth_timestamp", GenerateTimeStamp()); SignatureMethod = new OAuthParameter("oauth_signature_method", "HMAC-SHA1"); ConsumerKey = new OAuthParameter("oauth_consumer_key", tokens.ConsumerKey); ConsumerSecret = new OAuthParameter("oauth_consumer_secret", tokens.ConsumerSecret); Token = new OAuthParameter("oauth_token", tokens.AccessToken); TokenSecret = new OAuthParameter("oauth_token_secret", tokens.AccessTokenSecret); } private static Uri GetEncodedUri(Uri requestUri, IEnumerable<OAuthParameter> parameters) { StringBuilder requestParametersBuilder = new StringBuilder(requestUri.AbsoluteWithoutQuery()); if (parameters.Count() > 0) { requestParametersBuilder.Append("?"); foreach (var queryParam in parameters) { requestParametersBuilder.AppendFormat("{0}&", queryParam.ToString()); } requestParametersBuilder.Remove(requestParametersBuilder.Length - 1, 1); } return new Uri(requestParametersBuilder.ToString()); } private static string GenerateNonce() { return new Random() .Next(123400, int.MaxValue) .ToString("X", CultureInfo.InvariantCulture); } private static string GenerateTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds, CultureInfo.CurrentCulture).ToString(CultureInfo.CurrentCulture); } private string GenerateSignature() { string signatureBaseString = string.Format( CultureInfo.InvariantCulture, "GET&{0}&{1}", OAuthEncoder.UrlEncode(RequestUriWithoutQuery.Normalize()), OAuthEncoder.UrlEncode(GetSignParameters())); string key = string.Format( CultureInfo.InvariantCulture, "{0}&{1}", OAuthEncoder.UrlEncode(ConsumerSecret.Value), OAuthEncoder.UrlEncode(TokenSecret.Value)); return OAuthEncoder.GenerateHash(signatureBaseString, key); } private string GenerateAuthorizationHeader() { StringBuilder authHeaderBuilder = new StringBuilder(); authHeaderBuilder.AppendFormat("OAuth realm=\"{0}\",", Realm); authHeaderBuilder.Append(string.Join(",", GetAuthHeaderParameters().OrderBy(p => p.Key).Select(p => p.ToString(true)).ToArray())); authHeaderBuilder.AppendFormat(",{0}", Signature.ToString(true)); return authHeaderBuilder.ToString(); } private IEnumerable<OAuthParameter> GetSignParameters() { foreach (var queryParam in QueryParams) { yield return queryParam; } yield return Version; yield return Nonce; yield return Timestamp; yield return SignatureMethod; yield return ConsumerKey; yield return Token; } private IEnumerable<OAuthParameter> GetAuthHeaderParameters() { yield return Version; yield return Nonce; yield return Timestamp; yield return SignatureMethod; yield return ConsumerKey; yield return Token; } } internal static class OAuthUriExtensions { public static IDictionary<string, string> GetQueryParams(this Uri uri) { var result = new Dictionary<string, string>(); foreach (Match item in Regex.Matches(uri.Query, @"(?<key>[^&?=]+)=(?<value>[^&?=]+)")) { result.Add(item.Groups["key"].Value, item.Groups["value"].Value); } return result; } public static string AbsoluteWithoutQuery(this Uri uri) { if (string.IsNullOrEmpty(uri.Query)) { return uri.AbsoluteUri; } return uri.AbsoluteUri.Replace(uri.Query, string.Empty); } public static string Normalize(this Uri uri) { var result = new StringBuilder(string.Format(CultureInfo.InvariantCulture, "{0}://{1}", uri.Scheme, uri.Host)); if (!((uri.Scheme == "http" && uri.Port == 80) || (uri.Scheme == "https" && uri.Port == 443))) { result.Append(string.Concat(":", uri.Port)); } result.Append(uri.AbsolutePath); return result.ToString(); } } internal class OAuthParameter { public string Key { get; set; } public string Value { get; set; } public OAuthParameter(string key, string value) { Key = key; Value = value; } public override string ToString() { return ToString(false); } public string ToString(bool withQuotes) { string format = null; if (withQuotes) { format = "{0}=\"{1}\""; } else { format = "{0}={1}"; } return string.Format(CultureInfo.InvariantCulture, format, OAuthEncoder.UrlEncode(Key), OAuthEncoder.UrlEncode(Value)); } } internal static class OAuthEncoder { public static string UrlEncode(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } var result = Uri.EscapeDataString(value); // UrlEncode escapes with lowercase characters (e.g. %2f) but oAuth needs %2F result = Regex.Replace(result, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()); // these characters are not escaped by UrlEncode() but needed to be escaped result = result .Replace("(", "%28") .Replace(")", "%29") .Replace("$", "%24") .Replace("!", "%21") .Replace("*", "%2A") .Replace("'", "%27"); // these characters are escaped by UrlEncode() but will fail if unescaped! result = result.Replace("%7E", "~"); return result; } public static string UrlEncode(IEnumerable<OAuthParameter> parameters) { string rawUrl = string.Join("&", parameters.OrderBy(p => p.Key).Select(p => p.ToString()).ToArray()); return UrlEncode(rawUrl); } public static string GenerateHash(string input, string key) { MacAlgorithmProvider mac = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8); CryptographicKey cryptoKey = mac.CreateKey(keyMaterial); IBuffer hash = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8)); return CryptographicBuffer.EncodeToBase64String(hash); } } }
36.269162
166
0.571485
[ "MIT" ]
Appnet1337/waslibs
src/AppStudio.DataProviders/Twitter/TwitterDataProvider.cs
20,349
C#
using dnlib.DotNet; using dnlib.DotNet.Emit; using System; namespace CS2ASM { public static unsafe partial class Amd64Transformation { [ILTransformation(Code.Conv_Ovf_U2)] public static void Conv_Ovf_U2(Context context) { throw new NotImplementedException("Conv_Ovf_U2 is not implemented"); } } }
22.125
80
0.680791
[ "MIT" ]
nifanfa/CS2ASM
CS2ASM/Amd64/Transformations/Conv_Ovf_U2.cs
354
C#
using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; namespace LiteBorder.AspNetCore.Identity.DynamoDb { public class UserLoginMetaConverter : IPropertyConverter { public DynamoDBEntry ToEntry(object value) { return $"UserLogin#{value}"; } public object FromEntry(DynamoDBEntry entry) { return entry.AsString().Replace("UserLogin#", ""); } } }
23.789474
62
0.643805
[ "Apache-2.0" ]
liteborder/dotnet-identity-dynamo
src/Mappers/UserLoginMetaConverter.cs
454
C#
using System.Web; using Microsoft.AspNetCore.Razor.TagHelpers; using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Core.Extensions; namespace WalkingTec.Mvvm.TagHelpers.LayUI.Form { [HtmlTargetElement("wt:ueditor", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.WithoutEndTag)] public class UEditorTagHelper : BaseFieldTag { //文本框为空显示的PlaceHolder public string EmptyText { get; set; } //定义高度 public new int? Height { get; set; } //定义宽度 public new int? Width { get; set; } public string UploadGroupName { get; set; } public string UploadSubdir { get; set; } public string ConnectionString { get; set; } public string UploadMode { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { string placeHolder = EmptyText ?? string.Empty; output.TagName = "div"; output.TagMode = TagMode.StartTagAndEndTag; string strWidth = Width == null ? "100%" : (Width + "px"); string strHeight = Height == null ? "200px" : (Height + "px"); output.Attributes.Add("style", $"width:{strWidth};height:{strHeight};"); output.Attributes.Add("isrich", "1"); var vm = context.Items["model"] as BaseVM; string url = "UploadForLayUIUEditor"; if (string.IsNullOrEmpty(ConnectionString) == true) { if (vm != null) { url = url.AppendQuery($"_DONOT_USE_CS={vm.CurrentCS}"); } } else { url = url.AppendQuery($"_DONOT_USE_CS={ConnectionString}"); } if (string.IsNullOrEmpty(UploadGroupName) == false) { url = url.AppendQuery($"groupName={UploadGroupName}"); } if (string.IsNullOrEmpty(UploadSubdir) == false) { url = url.AppendQuery($"subdir={UploadSubdir}"); } if (string.IsNullOrEmpty(UploadMode) == false) { url = url.AppendQuery($"sm={UploadMode}"); } if (vm != null) { vm.ConfigInfo.UEditorOptions.FileActionName = url; vm.ConfigInfo.UEditorOptions.ImageActionName = url; vm.ConfigInfo.UEditorOptions.ScrawlActionName = url; vm.ConfigInfo.UEditorOptions.SnapscreenActionName = url; vm.ConfigInfo.UEditorOptions.VideoActionName = url; } output.PostElement.AppendHtml($@" <script> layui.use(['ueditorconfig'], function () {{ layui.ueditor.loadEditor('{Id}').ready(function(){{this.setContent('{(DefaultValue != null ? DefaultValue.ToString() : Field?.Model?.ToString())}')}}); }}); </script> "); base.Process(context, output); } } }
37.291139
155
0.565173
[ "MIT" ]
Mingyu-zhang/iotgateway
WalkingTec.Mvvm/WalkingTec.Mvvm.TagHelpers.LayUI/Form/UEditorTagHelper.cs
2,978
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Lightsail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Lightsail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetDistributions operation /// </summary> public class GetDistributionsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetDistributionsResponse response = new GetDistributionsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("distributions", targetDepth)) { var unmarshaller = new ListUnmarshaller<LightsailDistribution, LightsailDistributionUnmarshaller>(LightsailDistributionUnmarshaller.Instance); response.Distributions = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("nextPageToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextPageToken = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInputException")) { return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("OperationFailureException")) { return OperationFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException")) { return ServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthenticatedException")) { return UnauthenticatedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonLightsailException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static GetDistributionsResponseUnmarshaller _instance = new GetDistributionsResponseUnmarshaller(); internal static GetDistributionsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetDistributionsResponseUnmarshaller Instance { get { return _instance; } } } }
42.573529
193
0.621934
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/GetDistributionsResponseUnmarshaller.cs
5,790
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableArrayTest : SimpleElementImmutablesTestBase { private static readonly ImmutableArray<int> s_emptyDefault; private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>(); private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1); private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3); private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1)); private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null); [Fact] public void Clear() { Assert.Equal(ImmutableArray<int>.Empty, ImmutableArray.Create<int>().Clear()); Assert.Equal(ImmutableArray<int>.Empty, ImmutableArray.Create<int>(1).Clear()); Assert.Equal(ImmutableArray<int>.Empty, ImmutableArray.Create<int>(1, 2, 3).Clear()); } [Fact] public void CreateEmpty() { Assert.Equal(ImmutableArray<int>.Empty, ImmutableArray.Create<int>()); Assert.Equal(ImmutableArray<int>.Empty, ImmutableArray.Create<int>(new int[0])); } [Fact] public void CreateFromEnumerable() { Assert.Throws<ArgumentNullException>("items", () => ImmutableArray.CreateRange((IEnumerable<int>)null)); IEnumerable<int> source = new[] { 1, 2, 3 }; var array = ImmutableArray.CreateRange(source); Assert.Equal(3, array.Length); } [Fact] public void CreateFromEmptyEnumerableReturnsSingleton() { IEnumerable<int> emptySource1 = new int[0]; var immutable = ImmutableArray.CreateRange(emptySource1); // This equality check returns true if the underlying arrays are the same instance. Assert.Equal(s_empty, immutable); } [Fact] public void CreateRangeFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, i => i + 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, i => i + 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, i => i)); Assert.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(array, (Func<int, int>)null)); } [Fact] public void CreateRangeFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, (i, j) => i + j, 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, (i, j) => i + j, 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); var copy3 = ImmutableArray.CreateRange(array, (int i, object j) => i, null); Assert.Equal(new[] { 4, 5, 6, 7 }, copy3); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(array, (Func<int, int, int>)null, 0)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, i => i + 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, i => i); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, i => i * 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, i => i + 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, i => i); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, i => i); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, i => i); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, i => i); Assert.Equal(new int[] { }, copy8); Assert.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(s_empty, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(array, -1, 1, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(array, -1, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 0, 5, i => i)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 4, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 3, 2, i => i)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 1, -1, i => i)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, (i, j) => i * j, 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, (i, j) => i + j, 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, (i, j) => i + j, 0); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, (i, j) => i + j, 0); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy8); var copy9 = ImmutableArray.CreateRange(array, 0, 1, (int i, object j) => i, null); Assert.Equal(new int[] { 4 }, copy9); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, 0, 0, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentNullException>("selector", () => ImmutableArray.CreateRange(s_empty, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(s_empty, -1, 1, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.CreateRange(array, -1, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 0, 5, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 4, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 3, 2, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.CreateRange(array, 1, -1, (i, j) => i + j, 0)); } [Fact] public void CreateFromSliceOfImmutableArray() { var array = ImmutableArray.Create(4, 5, 6, 7); Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Equal(new int[] { }, ImmutableArray.Create(s_empty, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(s_empty, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfImmutableArrayOptimizations() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 0, array.Length); Assert.Equal(array, slice); // array instance actually shared between the two } [Fact] public void CreateFromSliceOfImmutableArrayEmptyReturnsSingleton() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(s_empty, slice); } [Fact] public void CreateFromSliceOfArray() { var array = new int[] { 4, 5, 6, 7 }; Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>("start", () => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfArrayEmptyReturnsSingleton() { var array = new int[] { 4, 5, 6, 7 }; var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(s_empty, slice); slice = ImmutableArray.Create(array, array.Length, 0); Assert.Equal(s_empty, slice); } [Fact] public void CreateFromArray() { var source = new[] { 1, 2, 3 }; var immutable = ImmutableArray.Create(source); Assert.Equal(source, immutable); } [Fact] public void CreateFromNullArray() { int[] nullArray = null; ImmutableArray<int> immutable = ImmutableArray.Create(nullArray); Assert.False(immutable.IsDefault); Assert.Equal(0, immutable.Length); } [Fact] public void Covariance() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.False(baseImmutable.IsDefault); // Must cast to object or the IEnumerable<object> overload of Equals would be used Assert.Equal((object)derivedImmutable, baseImmutable, EqualityComparer<object>.Default); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.False(derivedImmutable2.IsDefault); Assert.Equal(derivedImmutable, derivedImmutable2); // Try a cast that would fail. Assert.True(baseImmutable.As<Encoder>().IsDefault); } [Fact] public void DowncastOfDefaultStructs() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } /// <summary> /// Verifies that using an ordinary Create factory method is smart enough to reuse /// an underlying array when possible. /// </summary> [Fact] public void CovarianceImplicit() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = ImmutableArray.CreateRange<object>(derivedImmutable); // Must cast to object or the IEnumerable<object> overload of Equals would be used Assert.Equal((object)derivedImmutable, baseImmutable, EqualityComparer<object>.Default); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.Equal(derivedImmutable, derivedImmutable2); } [Fact] public void CastUpReference() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable); // Must cast to object or the IEnumerable<object> overload of Equals would be used Assert.Equal((object)derivedImmutable, baseImmutable, EqualityComparer<object>.Default); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. Assert.Equal(derivedImmutable, baseImmutable.As<string>()); Assert.Equal(derivedImmutable, baseImmutable.CastArray<string>()); } [Fact] public void CastUpReferenceDefaultValue() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } [Fact] public void CastUpRefToInterface() { var stringArray = ImmutableArray.Create("a", "b"); var enumArray = ImmutableArray<IEnumerable>.CastUp(stringArray); Assert.Equal(2, enumArray.Length); Assert.Equal(stringArray, enumArray.CastArray<string>()); Assert.Equal(stringArray, enumArray.As<string>()); } [Fact] public void CastUpInterfaceToInterface() { var genericEnumArray = ImmutableArray.Create<IEnumerable<int>>(new List<int>(), new List<int>()); var legacyEnumArray = ImmutableArray<IEnumerable>.CastUp(genericEnumArray); Assert.Equal(2, legacyEnumArray.Length); Assert.Equal(genericEnumArray, legacyEnumArray.As<IEnumerable<int>>()); Assert.Equal(genericEnumArray, legacyEnumArray.CastArray<IEnumerable<int>>()); } [Fact] public void CastUpArrayToSystemArray() { var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 }); var sysArray = ImmutableArray<Array>.CastUp(arrayArray); Assert.Equal(2, sysArray.Length); Assert.Equal(arrayArray, sysArray.As<int[]>()); Assert.Equal(arrayArray, sysArray.CastArray<int[]>()); } [Fact] public void CastUpArrayToObject() { var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 }); var objArray = ImmutableArray<object>.CastUp(arrayArray); Assert.Equal(2, objArray.Length); Assert.Equal(arrayArray, objArray.As<int[]>()); Assert.Equal(arrayArray, objArray.CastArray<int[]>()); } [Fact] public void CastUpDelegateToSystemDelegate() { var delArray = ImmutableArray.Create<Action>(() => { }, () => { }); var sysDelArray = ImmutableArray<Delegate>.CastUp(delArray); Assert.Equal(2, sysDelArray.Length); Assert.Equal(delArray, sysDelArray.As<Action>()); Assert.Equal(delArray, sysDelArray.CastArray<Action>()); } [Fact] public void CastArrayUnrelatedInterface() { var strArray = ImmutableArray.Create<string>("cat", "dog"); var compArray = ImmutableArray<IComparable>.CastUp(strArray); var enumArray = compArray.CastArray<IEnumerable>(); Assert.Equal(2, enumArray.Length); Assert.Equal(strArray, enumArray.As<string>()); Assert.Equal(strArray, enumArray.CastArray<string>()); } [Fact] public void CastArrayBadInterface() { var formattableArray = ImmutableArray.Create<IFormattable>(1, 2); Assert.Throws<InvalidCastException>(() => formattableArray.CastArray<IComparable>()); } [Fact] public void CastArrayBadRef() { var objArray = ImmutableArray.Create<object>("cat", "dog"); Assert.Throws<InvalidCastException>(() => objArray.CastArray<string>()); } [Fact] public void ToImmutableArray() { IEnumerable<int> source = new[] { 1, 2, 3 }; ImmutableArray<int> immutable = source.ToImmutableArray(); Assert.Equal(source, immutable); ImmutableArray<int> immutable2 = immutable.ToImmutableArray(); Assert.Equal(immutable, immutable2); // this will compare array reference equality. } [Fact] public void Count() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Length); Assert.Throws<InvalidOperationException>(() => ((ICollection)s_emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((ICollection<int>)s_emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyCollection<int>)s_emptyDefault).Count); Assert.Equal(0, s_empty.Length); Assert.Equal(0, ((ICollection)s_empty).Count); Assert.Equal(0, ((ICollection<int>)s_empty).Count); Assert.Equal(0, ((IReadOnlyCollection<int>)s_empty).Count); Assert.Equal(1, s_oneElement.Length); Assert.Equal(1, ((ICollection)s_oneElement).Count); Assert.Equal(1, ((ICollection<int>)s_oneElement).Count); Assert.Equal(1, ((IReadOnlyCollection<int>)s_oneElement).Count); } [Fact] public void IsEmpty() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.IsEmpty); Assert.True(s_empty.IsEmpty); Assert.False(s_oneElement.IsEmpty); } [Fact] public void IndexOfDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5, 0, 0)); } [Fact] public void LastIndexOfDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5, 0, 0)); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void Contains() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Contains(0)); Assert.False(s_empty.Contains(0)); Assert.True(s_oneElement.Contains(1)); Assert.False(s_oneElement.Contains(2)); Assert.True(s_manyElements.Contains(3)); Assert.False(s_oneElementRefType.Contains(null)); Assert.True(s_twoElementRefTypeWithNull.Contains(null)); } [Fact] public void ContainsEqualityComparer() { var array = ImmutableArray.Create("a", "B"); Assert.False(array.Contains("A", StringComparer.Ordinal)); Assert.True(array.Contains("A", StringComparer.OrdinalIgnoreCase)); Assert.False(array.Contains("b", StringComparer.Ordinal)); Assert.True(array.Contains("b", StringComparer.OrdinalIgnoreCase)); } [Fact] public void Enumerator() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.GetEnumerator()); ImmutableArray<int>.Enumerator enumerator = default(ImmutableArray<int>.Enumerator); Assert.Throws<NullReferenceException>(() => enumerator.Current); Assert.Throws<NullReferenceException>(() => enumerator.MoveNext()); enumerator = s_empty.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = s_manyElements.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); } [Fact] public void ObjectEnumerator() { Assert.Throws<InvalidOperationException>(() => ((IEnumerable<int>)s_emptyDefault).GetEnumerator()); IEnumerator<int> enumerator = ((IEnumerable<int>)s_empty).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = ((IEnumerable<int>)s_manyElements).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); for (int i = 0; i < 2; i++) { Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); if (i == 0) enumerator.Reset(); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public void EnumeratorWithNullValues() { var enumerationResult = System.Linq.Enumerable.ToArray(s_twoElementRefTypeWithNull); Assert.Equal("1", enumerationResult[0]); Assert.Null(enumerationResult[1]); } [Fact] public void EqualityCheckComparesInternalArrayByReference() { var immutable1 = ImmutableArray.Create(1); var immutable2 = ImmutableArray.Create(1); Assert.NotEqual(immutable1, immutable2); Assert.True(immutable1.Equals(immutable1)); Assert.True(immutable1.Equals((object)immutable1)); } [Fact] public void EqualsObjectNull() { Assert.False(s_empty.Equals((object)null)); } [Fact] public void OperatorsAndEquality() { Assert.True(s_empty.Equals(s_empty)); var emptySame = s_empty; Assert.True(s_empty == emptySame); Assert.False(s_empty != emptySame); // empty and default should not be seen as equal Assert.False(s_empty.Equals(s_emptyDefault)); Assert.False(s_empty == s_emptyDefault); Assert.True(s_empty != s_emptyDefault); Assert.False(s_emptyDefault == s_empty); Assert.True(s_emptyDefault != s_empty); Assert.False(s_empty.Equals(s_oneElement)); Assert.False(s_empty == s_oneElement); Assert.True(s_empty != s_oneElement); Assert.False(s_oneElement == s_empty); Assert.True(s_oneElement != s_empty); } [Fact] public void NullableOperators() { ImmutableArray<int>? nullArray = null; ImmutableArray<int>? nonNullDefault = s_emptyDefault; ImmutableArray<int>? nonNullEmpty = s_empty; Assert.True(nullArray == nonNullDefault); Assert.False(nullArray != nonNullDefault); Assert.True(nonNullDefault == nullArray); Assert.False(nonNullDefault != nullArray); Assert.False(nullArray == nonNullEmpty); Assert.True(nullArray != nonNullEmpty); Assert.False(nonNullEmpty == nullArray); Assert.True(nonNullEmpty != nullArray); } [Fact] public void GetHashCodeTest() { Assert.Equal(0, s_emptyDefault.GetHashCode()); Assert.NotEqual(0, s_empty.GetHashCode()); Assert.NotEqual(0, s_oneElement.GetHashCode()); } [Fact] public void Add() { var source = new[] { 1, 2 }; var array1 = ImmutableArray.Create(source); var array2 = array1.Add(3); Assert.Equal(source, array1); Assert.Equal(new[] { 1, 2, 3 }, array2); Assert.Equal(new[] { 1 }, s_empty.Add(1)); } [Fact] public void AddRange() { var nothingToEmpty = s_empty.AddRange(Enumerable.Empty<int>()); Assert.False(nothingToEmpty.IsDefault); Assert.True(nothingToEmpty.IsEmpty); Assert.Equal(new[] { 1, 2 }, s_empty.AddRange(Enumerable.Range(1, 2))); Assert.Equal(new[] { 1, 2 }, s_empty.AddRange(new[] { 1, 2 })); Assert.Equal(new[] { 1, 2, 3, 4 }, s_manyElements.AddRange(new[] { 4 })); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, s_manyElements.AddRange(new[] { 4, 5 })); Assert.Equal(new[] { 1, 2, 3, 4 }, s_manyElements.AddRange(ImmutableArray.Create(4))); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, s_manyElements.AddRange(ImmutableArray.Create(4, 5))); } [Fact] public void AddRangeDefaultEnumerable() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(Enumerable.Range(1, 2))); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(new[] { 1, 2 })); } [Fact] public void AddRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(s_empty)); Assert.Throws<NullReferenceException>(() => s_empty.AddRange(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(s_oneElement)); Assert.Throws<NullReferenceException>(() => s_oneElement.AddRange(s_emptyDefault)); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.AddRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.AddRange(emptyDefaultBoxed)); } [Fact] public void AddRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.AddRange(s_empty)); Assert.Equal(s_oneElement, s_empty.AddRange(s_oneElement)); // struct overload Assert.Equal(s_oneElement, s_empty.AddRange((IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.AddRange(s_empty)); } [Fact] public void Insert() { var array1 = ImmutableArray.Create<char>(); Assert.Throws<ArgumentOutOfRangeException>("index", () => array1.Insert(-1, 'a')); Assert.Throws<ArgumentOutOfRangeException>("index", () => array1.Insert(1, 'a')); var insertFirst = array1.Insert(0, 'c'); Assert.Equal(new[] { 'c' }, insertFirst); var insertLeft = insertFirst.Insert(0, 'a'); Assert.Equal(new[] { 'a', 'c' }, insertLeft); var insertRight = insertFirst.Insert(1, 'e'); Assert.Equal(new[] { 'c', 'e' }, insertRight); var insertBetween = insertLeft.Insert(1, 'b'); Assert.Equal(new[] { 'a', 'b', 'c' }, insertBetween); } [Fact] public void InsertDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(0, 10)); } [Fact] public void InsertRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.InsertRange(0, s_empty)); Assert.Equal(s_oneElement, s_empty.InsertRange(0, s_oneElement)); // struct overload Assert.Equal(s_oneElement, s_empty.InsertRange(0, (IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.InsertRange(0, s_empty)); } [Fact] public void InsertRangeEmpty() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(1, 10)); Assert.Equal(new int[0], s_empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(s_empty, s_empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(new[] { 1 }, s_empty.InsertRange(0, new[] { 1 })); Assert.Equal(new[] { 2, 3, 4 }, s_empty.InsertRange(0, new[] { 2, 3, 4 })); Assert.Equal(new[] { 2, 3, 4 }, s_empty.InsertRange(0, Enumerable.Range(2, 3))); Assert.Equal(s_manyElements, s_manyElements.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.InsertRange(1, s_oneElement)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.InsertRange(-1, s_oneElement)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.InsertRange(1, (IEnumerable<int>)s_oneElement)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.InsertRange(-1, (IEnumerable<int>)s_oneElement)); } [Fact] public void InsertRangeDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(-1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, new[] { 1 })); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, new[] { 2, 3, 4 })); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, Enumerable.Range(2, 3))); } /// <summary> /// Validates that a fixed bug in the inappropriate adding of the /// Empty singleton enumerator to the reusable instances bag does not regress. /// </summary> [Fact] public void EmptyEnumeratorReuseRegressionTest() { IEnumerable<int> oneElementBoxed = s_oneElement; IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyDefaultBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.RemoveRange(emptyDefaultBoxed)); Assert.Equal(oneElementBoxed, oneElementBoxed); } [Fact] public void InsertRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, s_empty)); Assert.Throws<NullReferenceException>(() => s_empty.InsertRange(0, s_emptyDefault)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, s_oneElement)); Assert.Throws<NullReferenceException>(() => s_oneElement.InsertRange(0, s_emptyDefault)); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.InsertRange(0, emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.InsertRange(0, emptyDefaultBoxed)); } [Fact] public void InsertRangeLeft() { Assert.Equal(new[] { 7, 1, 2, 3 }, s_manyElements.InsertRange(0, new[] { 7 })); Assert.Equal(new[] { 7, 8, 1, 2, 3 }, s_manyElements.InsertRange(0, new[] { 7, 8 })); } [Fact] public void InsertRangeMid() { Assert.Equal(new[] { 1, 7, 2, 3 }, s_manyElements.InsertRange(1, new[] { 7 })); Assert.Equal(new[] { 1, 7, 8, 2, 3 }, s_manyElements.InsertRange(1, new[] { 7, 8 })); } [Fact] public void InsertRangeRight() { Assert.Equal(new[] { 1, 2, 3, 7 }, s_manyElements.InsertRange(3, new[] { 7 })); Assert.Equal(new[] { 1, 2, 3, 7, 8 }, s_manyElements.InsertRange(3, new[] { 7, 8 })); } [Fact] public void InsertRangeImmutableArray() { Assert.Equal(new[] { 7, 8, 1, 2, 3 }, s_manyElements.InsertRange(0, ImmutableArray.Create(7, 8))); Assert.Equal(new[] { 1, 7, 2, 3 }, s_manyElements.InsertRange(1, ImmutableArray.Create(7))); Assert.Equal(new[] { 1, 2, 3, 7 }, s_manyElements.InsertRange(3, ImmutableArray.Create(7))); } [Fact] public void RemoveAt() { Assert.Throws<ArgumentOutOfRangeException>("length", () => s_empty.RemoveAt(0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => s_oneElement.RemoveAt(1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.RemoveAt(-1)); Assert.Equal(new int[0], s_oneElement.RemoveAt(0)); Assert.Equal(new[] { 2, 3 }, s_manyElements.RemoveAt(0)); Assert.Equal(new[] { 1, 3 }, s_manyElements.RemoveAt(1)); Assert.Equal(new[] { 1, 2 }, s_manyElements.RemoveAt(2)); } [Fact] public void Remove_NullEqualityComparer() { var modified = s_manyElements.Remove(2, null); Assert.Equal(new[] { 1, 3 }, modified); // Try again through the explicit interface implementation. IImmutableList<int> boxedCollection = s_manyElements; var modified2 = boxedCollection.Remove(2, null); Assert.Equal(new[] { 1, 3 }, modified2); } [Fact] public void Remove() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Remove(5)); Assert.False(s_empty.Remove(5).IsDefault); Assert.True(s_oneElement.Remove(1).IsEmpty); Assert.Equal(new[] { 2, 3 }, s_manyElements.Remove(1)); Assert.Equal(new[] { 1, 3 }, s_manyElements.Remove(2)); Assert.Equal(new[] { 1, 2 }, s_manyElements.Remove(3)); } [Fact] public void RemoveRange() { Assert.Equal(s_empty, s_empty.RemoveRange(0, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(0, 0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_emptyDefault.RemoveRange(-1, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(0, -1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_oneElement.RemoveRange(2, 0)); Assert.Equal(s_oneElement, s_oneElement.RemoveRange(1, 0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.RemoveRange(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>("length", () => s_oneElement.RemoveRange(0, 2)); Assert.Throws<ArgumentOutOfRangeException>("length", () => s_oneElement.RemoveRange(0, -1)); var fourElements = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(new int[0], s_oneElement.RemoveRange(0, 1)); Assert.Equal(s_oneElement.ToArray(), s_oneElement.RemoveRange(0, 0)); Assert.Equal(new[] { 3, 4 }, fourElements.RemoveRange(0, 2)); Assert.Equal(new[] { 1, 4 }, fourElements.RemoveRange(1, 2)); Assert.Equal(new[] { 1, 2 }, fourElements.RemoveRange(2, 2)); } [Fact] public void RemoveRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(s_empty)); Assert.Throws<ArgumentNullException>("items", () => s_empty.RemoveRange(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(s_oneElement)); Assert.Throws<ArgumentNullException>("items", () => s_oneElement.RemoveRange(s_emptyDefault)); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.RemoveRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.RemoveRange(emptyDefaultBoxed)); } [Fact] public void RemoveRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.RemoveRange(s_empty)); Assert.Equal(s_empty, s_empty.RemoveRange(s_oneElement)); // struct overload Assert.Equal(s_empty, s_empty.RemoveRange((IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.RemoveRange(s_empty)); } [Fact] public void RemoveAll() { Assert.Throws<ArgumentNullException>("match", () => s_oneElement.RemoveAll(null)); var array = ImmutableArray.CreateRange(Enumerable.Range(1, 10)); var removedEvens = array.RemoveAll(n => n % 2 == 0); var removedOdds = array.RemoveAll(n => n % 2 == 1); var removedAll = array.RemoveAll(n => true); var removedNone = array.RemoveAll(n => false); Assert.Equal(new[] { 1, 3, 5, 7, 9 }, removedEvens); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, removedOdds); Assert.True(removedAll.IsEmpty); Assert.Equal(Enumerable.Range(1, 10), removedNone); Assert.False(s_empty.RemoveAll(n => false).IsDefault); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveAll(n => false)); } [Fact] public void RemoveRange_EnumerableEqualityComparer_AcceptsNullEQ() { var array = ImmutableArray.Create(1, 2, 3); var removed2eq = array.RemoveRange(new[] { 2 }, null); Assert.Equal(2, removed2eq.Length); Assert.Equal(new[] { 1, 3 }, removed2eq); } [Fact] public void RemoveRangeEnumerableTest() { var list = ImmutableArray.Create(1, 2, 3); Assert.Throws<ArgumentNullException>("items", () => list.RemoveRange(null)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(new int[0]).IsDefault); Assert.False(s_empty.RemoveRange(new int[0]).IsDefault); ImmutableArray<int> removed2 = list.RemoveRange(new[] { 2 }); Assert.Equal(2, removed2.Length); Assert.Equal(new[] { 1, 3 }, removed2); ImmutableArray<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 }); Assert.Equal(1, removed13.Length); Assert.Equal(new[] { 2 }, removed13); Assert.Equal(new[] { 1, 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 2, 4, 5, 7, 10 })); Assert.Equal(new[] { 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 1, 2, 4, 5, 7, 10 })); Assert.Equal(list, list.RemoveRange(new[] { 5 })); Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray.Create<int>().RemoveRange(new[] { 1 })); var listWithDuplicates = ImmutableArray.Create(1, 2, 2, 3); Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2, 2 })); } [Fact] public void RemoveRangeImmutableArrayTest() { var list = ImmutableArray.Create(1, 2, 3); ImmutableArray<int> removed2 = list.RemoveRange(ImmutableArray.Create(2)); Assert.Equal(2, removed2.Length); Assert.Equal(new[] { 1, 3 }, removed2); ImmutableArray<int> removed13 = list.RemoveRange(ImmutableArray.Create(1, 3, 5)); Assert.Equal(1, removed13.Length); Assert.Equal(new[] { 2 }, removed13); Assert.Equal(new[] { 1, 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(ImmutableArray.Create(2, 4, 5, 7, 10))); Assert.Equal(new[] { 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(ImmutableArray.Create(1, 2, 4, 5, 7, 10))); Assert.Equal(list, list.RemoveRange(ImmutableArray.Create(5))); Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray.Create<int>().RemoveRange(ImmutableArray.Create(1))); var listWithDuplicates = ImmutableArray.Create(1, 2, 2, 3); Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(ImmutableArray.Create(2))); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(ImmutableArray.Create(2, 2))); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(ImmutableArray.Create(2, 2, 2))); Assert.Equal(new[] { 2, 3 }, list.RemoveRange(ImmutableArray.Create(42), EverythingEqual<int>.Default)); Assert.Equal(new[] { 3 }, list.RemoveRange(ImmutableArray.Create(42, 42), EverythingEqual<int>.Default)); Assert.Equal(new int[0], list.RemoveRange(ImmutableArray.Create(42, 42, 42), EverythingEqual<int>.Default)); } [Fact] public void Replace() { Assert.Equal(new[] { 5 }, s_oneElement.Replace(1, 5)); Assert.Equal(new[] { 6, 2, 3 }, s_manyElements.Replace(1, 6)); Assert.Equal(new[] { 1, 6, 3 }, s_manyElements.Replace(2, 6)); Assert.Equal(new[] { 1, 2, 6 }, s_manyElements.Replace(3, 6)); Assert.Equal(new[] { 1, 2, 3, 4 }, ImmutableArray.Create(1, 3, 3, 4).Replace(3, 2)); } [Fact] public void ReplaceWithEqualityComparerTest() { var updatedArray = s_manyElements.Replace(2, 10, null); Assert.Equal(new[] { 1, 10, 3 }, updatedArray); // Finally, try one last time using the interface implementation. IImmutableList<int> iface = s_manyElements; var updatedIFace = iface.Replace(2, 10, null); Assert.Equal(new[] { 1, 10, 3 }, updatedIFace); } [Fact] public void ReplaceMissingThrowsTest() { Assert.Throws<ArgumentException>("oldValue", () => s_empty.Replace(5, 3)); } [Fact] public void SetItem() { Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.SetItem(0, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.SetItem(0, 10)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_oneElement.SetItem(1, 10)); Assert.Throws<ArgumentOutOfRangeException>("index", () => s_empty.SetItem(-1, 10)); Assert.Equal(new[] { 12345 }, s_oneElement.SetItem(0, 12345)); Assert.Equal(new[] { 12345, 2, 3 }, s_manyElements.SetItem(0, 12345)); Assert.Equal(new[] { 1, 12345, 3 }, s_manyElements.SetItem(1, 12345)); Assert.Equal(new[] { 1, 2, 12345 }, s_manyElements.SetItem(2, 12345)); } [Fact] public void CopyToArray() { { var target = new int[s_manyElements.Length]; s_manyElements.CopyTo(target); Assert.Equal(target, s_manyElements); } { var target = new int[0]; Assert.Throws<NullReferenceException>(() => s_emptyDefault.CopyTo(target)); } } [Fact] public void CopyToArrayInt() { var source = ImmutableArray.Create(1, 2, 3); var target = new int[4]; source.CopyTo(target, 1); Assert.Equal(new[] { 0, 1, 2, 3 }, target); Assert.Throws<NullReferenceException>(() => s_emptyDefault.CopyTo(target, 0)); Assert.Throws<ArgumentNullException>("dest", () => source.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => source.CopyTo(target, -1)); Assert.Throws<ArgumentException>("", () => source.CopyTo(target, 2)); } [Fact] public void CopyToIntArrayIntInt() { var source = ImmutableArray.Create(1, 2, 3); var target = new int[4]; source.CopyTo(1, target, 3, 1); Assert.Equal(new[] { 0, 0, 0, 2 }, target); } [Fact] public void Concat() { var array1 = ImmutableArray.Create(1, 2, 3); var array2 = ImmutableArray.Create(4, 5, 6); var concat = array1.Concat(array2); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, concat); } /// <summary> /// Verifies reuse of the original array when concatenated to an empty array. /// </summary> [Fact] public void ConcatEdgeCases() { // empty arrays Assert.Equal(s_manyElements, s_manyElements.Concat(s_empty)); Assert.Equal(s_manyElements, s_empty.Concat(s_manyElements)); // default arrays s_manyElements.Concat(s_emptyDefault); Assert.Throws<InvalidOperationException>(() => s_manyElements.Concat(s_emptyDefault).Count()); Assert.Throws<InvalidOperationException>(() => s_emptyDefault.Concat(s_manyElements).Count()); } [Fact] public void IsDefault() { Assert.True(s_emptyDefault.IsDefault); Assert.False(s_empty.IsDefault); Assert.False(s_oneElement.IsDefault); } [Fact] public void IsDefaultOrEmpty() { Assert.True(s_empty.IsDefaultOrEmpty); Assert.True(s_emptyDefault.IsDefaultOrEmpty); Assert.False(s_oneElement.IsDefaultOrEmpty); } [Fact] public void IndexGetter() { Assert.Equal(1, s_oneElement[0]); Assert.Equal(1, ((IList)s_oneElement)[0]); Assert.Equal(1, ((IList<int>)s_oneElement)[0]); Assert.Equal(1, ((IReadOnlyList<int>)s_oneElement)[0]); Assert.Throws<IndexOutOfRangeException>(() => s_oneElement[1]); Assert.Throws<IndexOutOfRangeException>(() => s_oneElement[-1]); Assert.Throws<NullReferenceException>(() => s_emptyDefault[0]); Assert.Throws<InvalidOperationException>(() => ((IList)s_emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IList<int>)s_emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyList<int>)s_emptyDefault)[0]); } [Fact] public void ExplicitMethods() { IList<int> c = s_oneElement; Assert.Throws<NotSupportedException>(() => c.Add(3)); Assert.Throws<NotSupportedException>(() => c.Clear()); Assert.Throws<NotSupportedException>(() => c.Remove(3)); Assert.True(c.IsReadOnly); Assert.Throws<NotSupportedException>(() => c.Insert(0, 2)); Assert.Throws<NotSupportedException>(() => c.RemoveAt(0)); Assert.Equal(s_oneElement[0], c[0]); Assert.Throws<NotSupportedException>(() => c[0] = 8); var enumerator = c.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(s_oneElement[0], enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void Sort() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 1, 2, 3, 4 }, array.Sort()); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array unaffected. } [Fact] public void Sort_Comparison() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 4, 3, 2, 1 }, array.Sort((x, y) => y.CompareTo(x))); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array unaffected. } [Fact] public void Sort_NullComparison_Throws() { Assert.Throws<ArgumentNullException>("comparison", () => ImmutableArray.Create<int>().Sort((Comparison<int>)null)); } [Fact] public void SortNullComparer() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 1, 2, 3, 4 }, array.Sort((IComparer<int>)null)); Assert.Equal(new[] { 2, 1, 4, 3 }, array.Sort(1, 2, null)); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array unaffected. } [Fact] public void SortRange() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Throws<ArgumentOutOfRangeException>("index", () => array.Sort(-1, 2, Comparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>("count", () => array.Sort(1, -1, Comparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>("count", () => array.Sort(1, 4, Comparer<int>.Default)); Assert.Equal(new int[] { 2, 4, 1, 3 }, array.Sort(array.Length, 0, Comparer<int>.Default)); Assert.Equal(new[] { 2, 1, 4, 3 }, array.Sort(1, 2, Comparer<int>.Default)); } [Fact] public void SortComparer() { var array = ImmutableArray.Create("c", "B", "a"); Assert.Equal(new[] { "a", "B", "c" }, array.Sort(StringComparer.OrdinalIgnoreCase)); Assert.Equal(new[] { "B", "a", "c" }, array.Sort(StringComparer.Ordinal)); } [Fact] public void SortPreservesArrayWhenAlreadySorted() { var sortedArray = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(sortedArray, sortedArray.Sort()); var mostlySorted = ImmutableArray.Create(1, 2, 3, 4, 6, 5, 7, 8, 9, 10); Assert.Equal(mostlySorted, mostlySorted.Sort(0, 5, Comparer<int>.Default)); Assert.Equal(mostlySorted, mostlySorted.Sort(5, 5, Comparer<int>.Default)); Assert.Equal(Enumerable.Range(1, 10), mostlySorted.Sort(4, 2, Comparer<int>.Default)); } [Fact] public void ToBuilder() { Assert.Equal(0, s_empty.ToBuilder().Count); Assert.Throws<NullReferenceException>(() => s_emptyDefault.ToBuilder().Count); var builder = s_oneElement.ToBuilder(); Assert.Equal(s_oneElement.ToArray(), builder); builder = s_manyElements.ToBuilder(); Assert.Equal(s_manyElements.ToArray(), builder); // Make sure that changing the builder doesn't change the original immutable array. int expected = s_manyElements[0]; builder[0] = expected + 1; Assert.Equal(expected, s_manyElements[0]); Assert.Equal(expected + 1, builder[0]); } [Fact] public void StructuralEquatableEqualsDefault() { IStructuralEquatable eq = s_emptyDefault; Assert.True(eq.Equals(s_emptyDefault, EqualityComparer<int>.Default)); Assert.False(eq.Equals(s_empty, EqualityComparer<int>.Default)); Assert.False(eq.Equals(s_oneElement, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEquals() { IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var otherArray = new object[] { 1, 2, 3 }; var otherImmArray = ImmutableArray.Create(otherArray); var unequalArray = new int[] { 1, 2, 4 }; var unequalImmArray = ImmutableArray.Create(unequalArray); var unrelatedArray = new string[3]; var unrelatedImmArray = ImmutableArray.Create(unrelatedArray); var otherList = new List<int> { 1, 2, 3 }; Assert.Equal(array.Equals(otherArray, EqualityComparer<int>.Default), immArray.Equals(otherImmArray, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(otherList, EqualityComparer<int>.Default), immArray.Equals(otherList, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unrelatedArray, EverythingEqual<object>.Default), immArray.Equals(unrelatedImmArray, EverythingEqual<object>.Default)); Assert.Equal(array.Equals(new object(), EqualityComparer<int>.Default), immArray.Equals(new object(), EqualityComparer<int>.Default)); Assert.Equal(array.Equals(null, EqualityComparer<int>.Default), immArray.Equals(null, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unequalArray, EqualityComparer<int>.Default), immArray.Equals(unequalImmArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEqualsArrayInterop() { IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var unequalArray = new int[] { 1, 2, 4 }; Assert.True(immArray.Equals(array, EqualityComparer<int>.Default)); Assert.False(immArray.Equals(unequalArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCodeDefault() { IStructuralEquatable defaultImmArray = s_emptyDefault; Assert.Equal(0, defaultImmArray.GetHashCode(EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCode() { IStructuralEquatable emptyArray = new int[0]; IStructuralEquatable emptyImmArray = s_empty; IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); Assert.Equal(emptyArray.GetHashCode(EqualityComparer<int>.Default), emptyImmArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EqualityComparer<int>.Default), immArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EverythingEqual<int>.Default), immArray.GetHashCode(EverythingEqual<int>.Default)); } [Fact] public void StructuralComparableDefault() { IStructuralComparable def = s_emptyDefault; IStructuralComparable mt = s_empty; // default to default is fine, and should be seen as equal. Assert.Equal(0, def.CompareTo(s_emptyDefault, Comparer<int>.Default)); // default to empty and vice versa should throw, on the basis that // arrays compared that are of different lengths throw. Empty vs. default aren't really compatible. Assert.Throws<ArgumentException>("other", () => def.CompareTo(s_empty, Comparer<int>.Default)); Assert.Throws<ArgumentException>("other", () => mt.CompareTo(s_emptyDefault, Comparer<int>.Default)); } [Fact] public void StructuralComparable() { IStructuralComparable array = new int[3] { 1, 2, 3 }; IStructuralComparable equalArray = new int[3] { 1, 2, 3 }; IStructuralComparable immArray = ImmutableArray.Create((int[])array); IStructuralComparable equalImmArray = ImmutableArray.Create((int[])equalArray); IStructuralComparable longerArray = new int[] { 1, 2, 3, 4 }; IStructuralComparable longerImmArray = ImmutableArray.Create((int[])longerArray); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalImmArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>("other", () => array.CompareTo(longerArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>("other", () => immArray.CompareTo(longerImmArray, Comparer<int>.Default)); var list = new List<int> { 1, 2, 3 }; Assert.Throws<ArgumentException>("other", () => array.CompareTo(list, Comparer<int>.Default)); Assert.Throws<ArgumentException>("other", () => immArray.CompareTo(list, Comparer<int>.Default)); } [Fact] public void StructuralComparableArrayInterop() { IStructuralComparable array = new int[3] { 1, 2, 3 }; IStructuralComparable equalArray = new int[3] { 1, 2, 3 }; IStructuralComparable immArray = ImmutableArray.Create((int[])array); IStructuralComparable equalImmArray = ImmutableArray.Create((int[])equalArray); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalArray, Comparer<int>.Default)); } [Theory] [InlineData(new int[0], 5)] [InlineData(new int[] { 3 }, 5)] [InlineData(new int[] { 5 }, 5)] [InlineData(new int[] { 1, 2, 3 }, 1)] [InlineData(new int[] { 1, 2, 3 }, 2)] [InlineData(new int[] { 1, 2, 3 }, 3)] [InlineData(new int[] { 1, 2, 3, 4 }, 4)] public void BinarySearch(int[] array, int value) { Assert.Throws<ArgumentNullException>("array", () => ImmutableArray.BinarySearch(default(ImmutableArray<int>), value)); Assert.Equal( Array.BinarySearch(array, value), ImmutableArray.BinarySearch(ImmutableArray.Create(array), value)); Assert.Equal( Array.BinarySearch(array, value, Comparer<int>.Default), ImmutableArray.BinarySearch(ImmutableArray.Create(array), value, Comparer<int>.Default)); Assert.Equal( Array.BinarySearch(array, 0, array.Length, value), ImmutableArray.BinarySearch(ImmutableArray.Create(array), 0, array.Length, value)); if (array.Length > 0) { Assert.Equal( Array.BinarySearch(array, 1, array.Length - 1, value), ImmutableArray.BinarySearch(ImmutableArray.Create(array), 1, array.Length - 1, value)); } Assert.Equal( Array.BinarySearch(array, 0, array.Length, value, Comparer<int>.Default), ImmutableArray.BinarySearch(ImmutableArray.Create(array), 0, array.Length, value, Comparer<int>.Default)); } [Fact] public void OfType() { Assert.Equal(0, s_emptyDefault.OfType<int>().Count()); Assert.Equal(0, s_empty.OfType<int>().Count()); Assert.Equal(1, s_oneElement.OfType<int>().Count()); Assert.Equal(1, s_twoElementRefTypeWithNull.OfType<string>().Count()); } [Fact] public void Add_ThreadSafety() { // Note the point of this thread-safety test is *not* to test the thread-safety of the test itself. // This test has a known issue where the two threads will stomp on each others updates, but that's not the point. // The point is that ImmutableArray`1.Add should *never* throw. But if it reads its own T[] field more than once, // it *can* throw because the field can be replaced with an array of another length. // In fact, much worse can happen where we corrupt data if we are for example copying data out of the array // in (for example) a CopyTo method and we read from the field more than once. // Also noteworthy: this method only tests the thread-safety of the Add method. // While it proves the general point, any method that reads 'this' more than once is vulnerable. var array = ImmutableArray.Create<int>(); Action mutator = () => { for (int i = 0; i < 100; i++) { ImmutableInterlocked.InterlockedExchange(ref array, array.Add(1)); } }; Task.WaitAll(Task.Run(mutator), Task.Run(mutator)); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.Create<string>()); // verify empty DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.Create(1, 2, 3)); // verify non-empty } [Fact] public void ICollectionSyncRoot_NotSupported() { ICollection c = ImmutableArray.Create(1, 2, 3); Assert.Throws<NotSupportedException>(() => c.SyncRoot); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { return ImmutableArray.Create(contents); } /// <summary> /// A structure that takes exactly 3 bytes of memory. /// </summary> private struct ThreeByteStruct : IEquatable<ThreeByteStruct> { public ThreeByteStruct(byte first, byte second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public byte Field1; public byte Field2; public byte Field3; public bool Equals(ThreeByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is ThreeByteStruct) { return this.Equals((ThreeByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that takes exactly 9 bytes of memory. /// </summary> private struct NineByteStruct : IEquatable<NineByteStruct> { public NineByteStruct(int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth) { this.Field1 = (byte)first; this.Field2 = (byte)second; this.Field3 = (byte)third; this.Field4 = (byte)fourth; this.Field5 = (byte)fifth; this.Field6 = (byte)sixth; this.Field7 = (byte)seventh; this.Field8 = (byte)eighth; this.Field9 = (byte)ninth; } public byte Field1; public byte Field2; public byte Field3; public byte Field4; public byte Field5; public byte Field6; public byte Field7; public byte Field8; public byte Field9; public bool Equals(NineByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3 && this.Field4 == other.Field4 && this.Field5 == other.Field5 && this.Field6 == other.Field6 && this.Field7 == other.Field7 && this.Field8 == other.Field8 && this.Field9 == other.Field9; } public override bool Equals(object obj) { if (obj is NineByteStruct) { return this.Equals((NineByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that requires 9 bytes of memory but occupies 12 because of memory alignment. /// </summary> private struct TwelveByteStruct : IEquatable<TwelveByteStruct> { public TwelveByteStruct(int first, int second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public int Field1; public int Field2; public byte Field3; public bool Equals(TwelveByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is TwelveByteStruct) { return this.Equals((TwelveByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } private struct StructWithReferenceTypeField { public string foo; public StructWithReferenceTypeField(string foo) { this.foo = foo; } } } }
44.976567
157
0.589752
[ "MIT" ]
Priya91/corefx-1
src/System.Collections.Immutable/tests/ImmutableArrayTest.cs
71,018
C#
using System; namespace Tellma.Utilities.Sharding { /// <summary> /// Contains all the information needed to build a connection string to a database. /// </summary> public struct DatabaseConnectionInfo { public DatabaseConnectionInfo(string serverName, string databaseName, string userName, string password, bool isWindowsAuth) { if (string.IsNullOrWhiteSpace(serverName)) { throw new ArgumentException($"'{nameof(serverName)}' cannot be null or whitespace.", nameof(serverName)); } if (string.IsNullOrWhiteSpace(databaseName)) { throw new ArgumentException($"'{nameof(databaseName)}' cannot be null or whitespace.", nameof(databaseName)); } if (!isWindowsAuth) { if (string.IsNullOrWhiteSpace(userName)) { throw new ArgumentException($"'{nameof(userName)}' cannot be null or whitespace.", nameof(userName)); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentException($"'{nameof(password)}' cannot be null or whitespace.", nameof(password)); } } ServerName = serverName; DatabaseName = databaseName; UserName = userName; Password = password; IsWindowsAuth = isWindowsAuth; } public string ServerName { get; } public string DatabaseName { get; } public string UserName { get; set; } public string Password { get; set; } public bool IsWindowsAuth { get; set; } } }
34.857143
131
0.571429
[ "Apache-2.0" ]
lulzzz/tellma
Tellma.Utilities.Sharding/DatabaseConnectionInfo.cs
1,710
C#
#nullable enable namespace Gu.Units { using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; /// <summary> /// Provides a unified way of converting types of values to other types, as well as for accessing standard values and sub properties. /// </summary> /// <devdoc> /// <para>Provides a type converter to convert <see cref='Gu.Units.CurrentUnit'/> /// objects to and from various /// other representations.</para> /// </devdoc> public class CurrentUnitTypeConverter : TypeConverter { /// <inheritdoc /> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <inheritdoc /> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor) || destinationType == typeof(string)) { return true; } return base.CanConvertTo(context, destinationType); } /// <inheritdoc /> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var text = value as string; if (text != null) { CurrentUnit result; if (CurrentUnit.TryParse(text, out result)) { return result; } var message = $"Could not convert the string '{text}' to an instance of CurrentUnit)"; throw new NotSupportedException(message); } return base.ConvertFrom(context, culture, value); } /// <inheritdoc /> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is CurrentUnit && destinationType != null) { var unit = (CurrentUnit)value; if (destinationType == typeof(string)) { return unit.ToString(); } else if (destinationType == typeof(InstanceDescriptor)) { var parseMethod = typeof(CurrentUnit).GetMethod(nameof(CurrentUnit.Parse), new Type[] { typeof(string) }); if (parseMethod != null) { var args = new object[] { unit.Symbol }; return new InstanceDescriptor(parseMethod, args); } } } return base.ConvertTo(context, culture, value, destinationType); } } }
34.482353
137
0.549642
[ "MIT" ]
GuOrg/Gu.Units
Gu.Units/CurrentUnitTypeConverter.generated.cs
2,931
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Framework; using DocumentFormat.OpenXml.Framework.Metadata; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation.Schema; using System; using System.Collections.Generic; using System.IO.Packaging; namespace DocumentFormat.OpenXml.Bibliography { /// <summary> /// <para>Sources.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Sources.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>Source &lt;b:Source></description></item> /// </list> /// </remark> public partial class Sources : OpenXmlPartRootElement { /// <summary> /// Initializes a new instance of the Sources class. /// </summary> public Sources() : base() { } /// <summary> /// Initializes a new instance of the Sources class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Sources(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Sources class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Sources(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Sources class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Sources(string outerXml) : base(outerXml) { } /// <summary> /// <para>Selected Style</para> /// <para>Represents the following attribute in the schema: SelectedStyle</para> /// </summary> public StringValue SelectedStyle { get => GetAttribute<StringValue>(); set => SetAttribute(value); } /// <summary> /// <para>Documentation Style Name</para> /// <para>Represents the following attribute in the schema: StyleName</para> /// </summary> public StringValue StyleName { get => GetAttribute<StringValue>(); set => SetAttribute(value); } /// <summary> /// <para>Uniform Resource Identifier</para> /// <para>Represents the following attribute in the schema: URI</para> /// </summary> public StringValue Uri { get => GetAttribute<StringValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Sources"); builder.AddChild<Source>(); builder.AddElement<Sources>() .AddAttribute(0, "SelectedStyle", a => a.SelectedStyle, aBuilder => { aBuilder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); }) .AddAttribute(0, "StyleName", a => a.StyleName, aBuilder => { aBuilder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); }) .AddAttribute(0, "URI", a => a.Uri, aBuilder => { aBuilder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); }); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Source), 0, 0) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Sources>(deep); } /// <summary> /// <para>Person.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Person.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>Last &lt;b:Last></description></item> /// <item><description>First &lt;b:First></description></item> /// <item><description>Middle &lt;b:Middle></description></item> /// </list> /// </remark> public partial class Person : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Person class. /// </summary> public Person() : base() { } /// <summary> /// Initializes a new instance of the Person class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Person(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Person class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Person(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Person class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Person(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Person"); builder.AddChild<Last>(); builder.AddChild<First>(); builder.AddChild<Middle>(); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Last), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.First), 0, 0), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Middle), 0, 0) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Person>(deep); } /// <summary> /// <para>Person's Last, or Family, Name.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Last.</para> /// </summary> public partial class Last : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Last class. /// </summary> public Last() : base() { } /// <summary> /// Initializes a new instance of the Last class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Last(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Last"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Last>(deep); } /// <summary> /// <para>Person's First, or Given, Name.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:First.</para> /// </summary> public partial class First : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the First class. /// </summary> public First() : base() { } /// <summary> /// Initializes a new instance of the First class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public First(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "First"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<First>(deep); } /// <summary> /// <para>Person's Middle, or Other, Name.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Middle.</para> /// </summary> public partial class Middle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Middle class. /// </summary> public Middle() : base() { } /// <summary> /// Initializes a new instance of the Middle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Middle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Middle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Middle>(deep); } /// <summary> /// <para>Corporate Author.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Corporate.</para> /// </summary> public partial class Corporate : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Corporate class. /// </summary> public Corporate() : base() { } /// <summary> /// Initializes a new instance of the Corporate class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Corporate(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Corporate"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Corporate>(deep); } /// <summary> /// <para>Abbreviated Case Number.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:AbbreviatedCaseNumber.</para> /// </summary> public partial class AbbreviatedCaseNumber : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AbbreviatedCaseNumber class. /// </summary> public AbbreviatedCaseNumber() : base() { } /// <summary> /// Initializes a new instance of the AbbreviatedCaseNumber class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AbbreviatedCaseNumber(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "AbbreviatedCaseNumber"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AbbreviatedCaseNumber>(deep); } /// <summary> /// <para>Album Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:AlbumTitle.</para> /// </summary> public partial class AlbumTitle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the AlbumTitle class. /// </summary> public AlbumTitle() : base() { } /// <summary> /// Initializes a new instance of the AlbumTitle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public AlbumTitle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "AlbumTitle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AlbumTitle>(deep); } /// <summary> /// <para>Book Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:BookTitle.</para> /// </summary> public partial class BookTitle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the BookTitle class. /// </summary> public BookTitle() : base() { } /// <summary> /// Initializes a new instance of the BookTitle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public BookTitle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "BookTitle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<BookTitle>(deep); } /// <summary> /// <para>Broadcaster.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Broadcaster.</para> /// </summary> public partial class Broadcaster : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Broadcaster class. /// </summary> public Broadcaster() : base() { } /// <summary> /// Initializes a new instance of the Broadcaster class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Broadcaster(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Broadcaster"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Broadcaster>(deep); } /// <summary> /// <para>Broadcast Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:BroadcastTitle.</para> /// </summary> public partial class BroadcastTitle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the BroadcastTitle class. /// </summary> public BroadcastTitle() : base() { } /// <summary> /// Initializes a new instance of the BroadcastTitle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public BroadcastTitle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "BroadcastTitle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<BroadcastTitle>(deep); } /// <summary> /// <para>Case Number.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:CaseNumber.</para> /// </summary> public partial class CaseNumber : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the CaseNumber class. /// </summary> public CaseNumber() : base() { } /// <summary> /// Initializes a new instance of the CaseNumber class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public CaseNumber(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "CaseNumber"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CaseNumber>(deep); } /// <summary> /// <para>Chapter Number.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:ChapterNumber.</para> /// </summary> public partial class ChapterNumber : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ChapterNumber class. /// </summary> public ChapterNumber() : base() { } /// <summary> /// Initializes a new instance of the ChapterNumber class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ChapterNumber(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "ChapterNumber"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ChapterNumber>(deep); } /// <summary> /// <para>City.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:City.</para> /// </summary> public partial class City : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the City class. /// </summary> public City() : base() { } /// <summary> /// Initializes a new instance of the City class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public City(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "City"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<City>(deep); } /// <summary> /// <para>Comments.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Comments.</para> /// </summary> public partial class Comments : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Comments class. /// </summary> public Comments() : base() { } /// <summary> /// Initializes a new instance of the Comments class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Comments(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Comments"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Comments>(deep); } /// <summary> /// <para>Conference or Proceedings Name.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:ConferenceName.</para> /// </summary> public partial class ConferenceName : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ConferenceName class. /// </summary> public ConferenceName() : base() { } /// <summary> /// Initializes a new instance of the ConferenceName class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ConferenceName(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "ConferenceName"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ConferenceName>(deep); } /// <summary> /// <para>Country or Region.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:CountryRegion.</para> /// </summary> public partial class CountryRegion : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the CountryRegion class. /// </summary> public CountryRegion() : base() { } /// <summary> /// Initializes a new instance of the CountryRegion class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public CountryRegion(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "CountryRegion"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<CountryRegion>(deep); } /// <summary> /// <para>Court.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Court.</para> /// </summary> public partial class Court : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Court class. /// </summary> public Court() : base() { } /// <summary> /// Initializes a new instance of the Court class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Court(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Court"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Court>(deep); } /// <summary> /// <para>Day.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Day.</para> /// </summary> public partial class Day : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Day class. /// </summary> public Day() : base() { } /// <summary> /// Initializes a new instance of the Day class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Day(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Day"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Day>(deep); } /// <summary> /// <para>Day Accessed.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:DayAccessed.</para> /// </summary> public partial class DayAccessed : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the DayAccessed class. /// </summary> public DayAccessed() : base() { } /// <summary> /// Initializes a new instance of the DayAccessed class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public DayAccessed(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "DayAccessed"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DayAccessed>(deep); } /// <summary> /// <para>Department.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Department.</para> /// </summary> public partial class Department : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Department class. /// </summary> public Department() : base() { } /// <summary> /// Initializes a new instance of the Department class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Department(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Department"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Department>(deep); } /// <summary> /// <para>Distributor.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Distributor.</para> /// </summary> public partial class Distributor : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Distributor class. /// </summary> public Distributor() : base() { } /// <summary> /// Initializes a new instance of the Distributor class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Distributor(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Distributor"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Distributor>(deep); } /// <summary> /// <para>Editor.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Edition.</para> /// </summary> public partial class Edition : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Edition class. /// </summary> public Edition() : base() { } /// <summary> /// Initializes a new instance of the Edition class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Edition(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Edition"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Edition>(deep); } /// <summary> /// <para>GUID.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Guid.</para> /// </summary> public partial class GuidString : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the GuidString class. /// </summary> public GuidString() : base() { } /// <summary> /// Initializes a new instance of the GuidString class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public GuidString(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Guid"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<GuidString>(deep); } /// <summary> /// <para>Institution.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Institution.</para> /// </summary> public partial class Institution : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Institution class. /// </summary> public Institution() : base() { } /// <summary> /// Initializes a new instance of the Institution class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Institution(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Institution"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Institution>(deep); } /// <summary> /// <para>Internet Site Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:InternetSiteTitle.</para> /// </summary> public partial class InternetSiteTitle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the InternetSiteTitle class. /// </summary> public InternetSiteTitle() : base() { } /// <summary> /// Initializes a new instance of the InternetSiteTitle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public InternetSiteTitle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "InternetSiteTitle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<InternetSiteTitle>(deep); } /// <summary> /// <para>Issue.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Issue.</para> /// </summary> public partial class Issue : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Issue class. /// </summary> public Issue() : base() { } /// <summary> /// Initializes a new instance of the Issue class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Issue(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Issue"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Issue>(deep); } /// <summary> /// <para>Journal Name.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:JournalName.</para> /// </summary> public partial class JournalName : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the JournalName class. /// </summary> public JournalName() : base() { } /// <summary> /// Initializes a new instance of the JournalName class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public JournalName(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "JournalName"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<JournalName>(deep); } /// <summary> /// <para>Locale ID.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:LCID.</para> /// </summary> public partial class LcId : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the LcId class. /// </summary> public LcId() : base() { } /// <summary> /// Initializes a new instance of the LcId class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public LcId(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "LCID"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<LcId>(deep); } /// <summary> /// <para>Medium.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Medium.</para> /// </summary> public partial class Medium : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Medium class. /// </summary> public Medium() : base() { } /// <summary> /// Initializes a new instance of the Medium class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Medium(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Medium"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Medium>(deep); } /// <summary> /// <para>Month.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Month.</para> /// </summary> public partial class Month : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Month class. /// </summary> public Month() : base() { } /// <summary> /// Initializes a new instance of the Month class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Month(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Month"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Month>(deep); } /// <summary> /// <para>Month Accessed.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:MonthAccessed.</para> /// </summary> public partial class MonthAccessed : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the MonthAccessed class. /// </summary> public MonthAccessed() : base() { } /// <summary> /// Initializes a new instance of the MonthAccessed class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public MonthAccessed(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "MonthAccessed"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<MonthAccessed>(deep); } /// <summary> /// <para>Number of Volumes.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:NumberVolumes.</para> /// </summary> public partial class NumberVolumes : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the NumberVolumes class. /// </summary> public NumberVolumes() : base() { } /// <summary> /// Initializes a new instance of the NumberVolumes class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public NumberVolumes(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "NumberVolumes"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NumberVolumes>(deep); } /// <summary> /// <para>Pages.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Pages.</para> /// </summary> public partial class Pages : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Pages class. /// </summary> public Pages() : base() { } /// <summary> /// Initializes a new instance of the Pages class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Pages(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Pages"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Pages>(deep); } /// <summary> /// <para>Patent Number.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:PatentNumber.</para> /// </summary> public partial class PatentNumber : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the PatentNumber class. /// </summary> public PatentNumber() : base() { } /// <summary> /// Initializes a new instance of the PatentNumber class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public PatentNumber(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "PatentNumber"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<PatentNumber>(deep); } /// <summary> /// <para>Periodical Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:PeriodicalTitle.</para> /// </summary> public partial class PeriodicalTitle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the PeriodicalTitle class. /// </summary> public PeriodicalTitle() : base() { } /// <summary> /// Initializes a new instance of the PeriodicalTitle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public PeriodicalTitle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "PeriodicalTitle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<PeriodicalTitle>(deep); } /// <summary> /// <para>Production Company.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:ProductionCompany.</para> /// </summary> public partial class ProductionCompany : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ProductionCompany class. /// </summary> public ProductionCompany() : base() { } /// <summary> /// Initializes a new instance of the ProductionCompany class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ProductionCompany(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "ProductionCompany"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ProductionCompany>(deep); } /// <summary> /// <para>Publication Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:PublicationTitle.</para> /// </summary> public partial class PublicationTitle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the PublicationTitle class. /// </summary> public PublicationTitle() : base() { } /// <summary> /// Initializes a new instance of the PublicationTitle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public PublicationTitle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "PublicationTitle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<PublicationTitle>(deep); } /// <summary> /// <para>Publisher.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Publisher.</para> /// </summary> public partial class Publisher : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Publisher class. /// </summary> public Publisher() : base() { } /// <summary> /// Initializes a new instance of the Publisher class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Publisher(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Publisher"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Publisher>(deep); } /// <summary> /// <para>Recording Number.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:RecordingNumber.</para> /// </summary> public partial class RecordingNumber : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the RecordingNumber class. /// </summary> public RecordingNumber() : base() { } /// <summary> /// Initializes a new instance of the RecordingNumber class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public RecordingNumber(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "RecordingNumber"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<RecordingNumber>(deep); } /// <summary> /// <para>Reference Order.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:RefOrder.</para> /// </summary> public partial class ReferenceOrder : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ReferenceOrder class. /// </summary> public ReferenceOrder() : base() { } /// <summary> /// Initializes a new instance of the ReferenceOrder class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ReferenceOrder(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "RefOrder"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ReferenceOrder>(deep); } /// <summary> /// <para>Reporter.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Reporter.</para> /// </summary> public partial class Reporter : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Reporter class. /// </summary> public Reporter() : base() { } /// <summary> /// Initializes a new instance of the Reporter class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Reporter(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Reporter"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Reporter>(deep); } /// <summary> /// <para>Short Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:ShortTitle.</para> /// </summary> public partial class ShortTitle : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ShortTitle class. /// </summary> public ShortTitle() : base() { } /// <summary> /// Initializes a new instance of the ShortTitle class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ShortTitle(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "ShortTitle"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShortTitle>(deep); } /// <summary> /// <para>Standard Number.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:StandardNumber.</para> /// </summary> public partial class StandardNumber : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the StandardNumber class. /// </summary> public StandardNumber() : base() { } /// <summary> /// Initializes a new instance of the StandardNumber class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public StandardNumber(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "StandardNumber"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<StandardNumber>(deep); } /// <summary> /// <para>State or Province.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:StateProvince.</para> /// </summary> public partial class StateProvince : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the StateProvince class. /// </summary> public StateProvince() : base() { } /// <summary> /// Initializes a new instance of the StateProvince class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public StateProvince(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "StateProvince"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<StateProvince>(deep); } /// <summary> /// <para>Station.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Station.</para> /// </summary> public partial class Station : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Station class. /// </summary> public Station() : base() { } /// <summary> /// Initializes a new instance of the Station class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Station(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Station"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Station>(deep); } /// <summary> /// <para>Tag.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Tag.</para> /// </summary> public partial class Tag : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Tag class. /// </summary> public Tag() : base() { } /// <summary> /// Initializes a new instance of the Tag class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Tag(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Tag"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Tag>(deep); } /// <summary> /// <para>Theater.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Theater.</para> /// </summary> public partial class Theater : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Theater class. /// </summary> public Theater() : base() { } /// <summary> /// Initializes a new instance of the Theater class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Theater(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Theater"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Theater>(deep); } /// <summary> /// <para>Thesis Type.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:ThesisType.</para> /// </summary> public partial class ThesisType : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the ThesisType class. /// </summary> public ThesisType() : base() { } /// <summary> /// Initializes a new instance of the ThesisType class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ThesisType(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "ThesisType"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ThesisType>(deep); } /// <summary> /// <para>Title.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Title.</para> /// </summary> public partial class Title : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Title class. /// </summary> public Title() : base() { } /// <summary> /// Initializes a new instance of the Title class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Title(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Title"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Title>(deep); } /// <summary> /// <para>Type.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Type.</para> /// </summary> public partial class PatentType : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the PatentType class. /// </summary> public PatentType() : base() { } /// <summary> /// Initializes a new instance of the PatentType class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public PatentType(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Type"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<PatentType>(deep); } /// <summary> /// <para>URL.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:URL.</para> /// </summary> public partial class UrlString : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the UrlString class. /// </summary> public UrlString() : base() { } /// <summary> /// Initializes a new instance of the UrlString class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public UrlString(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "URL"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<UrlString>(deep); } /// <summary> /// <para>Version.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Version.</para> /// </summary> public partial class Version : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Version class. /// </summary> public Version() : base() { } /// <summary> /// Initializes a new instance of the Version class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Version(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Version"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Version>(deep); } /// <summary> /// <para>Volume.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Volume.</para> /// </summary> public partial class Volume : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Volume class. /// </summary> public Volume() : base() { } /// <summary> /// Initializes a new instance of the Volume class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Volume(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Volume"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Volume>(deep); } /// <summary> /// <para>Year.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Year.</para> /// </summary> public partial class Year : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the Year class. /// </summary> public Year() : base() { } /// <summary> /// Initializes a new instance of the Year class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Year(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "Year"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Year>(deep); } /// <summary> /// <para>Year Accessed.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:YearAccessed.</para> /// </summary> public partial class YearAccessed : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the YearAccessed class. /// </summary> public YearAccessed() : base() { } /// <summary> /// Initializes a new instance of the YearAccessed class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public YearAccessed(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator(new StringValidator() { MinLength = (0L), MaxLength = (255L) }); builder.SetSchema(9, "YearAccessed"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<YearAccessed>(deep); } /// <summary> /// <para>Name List.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:NameList.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>Person &lt;b:Person></description></item> /// </list> /// </remark> public partial class NameList : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NameList class. /// </summary> public NameList() : base() { } /// <summary> /// Initializes a new instance of the NameList class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NameList(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NameList class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NameList(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NameList class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NameList(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "NameList"); builder.AddChild<Person>(); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Person), 1, 0) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NameList>(deep); } /// <summary> /// <para>Artist.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Artist.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Artist : NameType { /// <summary> /// Initializes a new instance of the Artist class. /// </summary> public Artist() : base() { } /// <summary> /// Initializes a new instance of the Artist class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Artist(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Artist class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Artist(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Artist class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Artist(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Artist"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Artist>(deep); } /// <summary> /// <para>Book Author.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:BookAuthor.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class BookAuthor : NameType { /// <summary> /// Initializes a new instance of the BookAuthor class. /// </summary> public BookAuthor() : base() { } /// <summary> /// Initializes a new instance of the BookAuthor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BookAuthor(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BookAuthor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public BookAuthor(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the BookAuthor class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public BookAuthor(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "BookAuthor"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<BookAuthor>(deep); } /// <summary> /// <para>Compiler.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Compiler.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Compiler : NameType { /// <summary> /// Initializes a new instance of the Compiler class. /// </summary> public Compiler() : base() { } /// <summary> /// Initializes a new instance of the Compiler class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Compiler(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Compiler class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Compiler(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Compiler class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Compiler(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Compiler"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Compiler>(deep); } /// <summary> /// <para>Composer.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Composer.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Composer : NameType { /// <summary> /// Initializes a new instance of the Composer class. /// </summary> public Composer() : base() { } /// <summary> /// Initializes a new instance of the Composer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Composer(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Composer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Composer(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Composer class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Composer(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Composer"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Composer>(deep); } /// <summary> /// <para>Conductor.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Conductor.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Conductor : NameType { /// <summary> /// Initializes a new instance of the Conductor class. /// </summary> public Conductor() : base() { } /// <summary> /// Initializes a new instance of the Conductor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Conductor(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Conductor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Conductor(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Conductor class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Conductor(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Conductor"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Conductor>(deep); } /// <summary> /// <para>Counsel.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Counsel.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Counsel : NameType { /// <summary> /// Initializes a new instance of the Counsel class. /// </summary> public Counsel() : base() { } /// <summary> /// Initializes a new instance of the Counsel class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Counsel(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Counsel class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Counsel(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Counsel class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Counsel(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Counsel"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Counsel>(deep); } /// <summary> /// <para>Director.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Director.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Director : NameType { /// <summary> /// Initializes a new instance of the Director class. /// </summary> public Director() : base() { } /// <summary> /// Initializes a new instance of the Director class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Director(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Director class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Director(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Director class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Director(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Director"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Director>(deep); } /// <summary> /// <para>Editor.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Editor.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Editor : NameType { /// <summary> /// Initializes a new instance of the Editor class. /// </summary> public Editor() : base() { } /// <summary> /// Initializes a new instance of the Editor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Editor(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Editor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Editor(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Editor class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Editor(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Editor"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Editor>(deep); } /// <summary> /// <para>Interviewee.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Interviewee.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Interviewee : NameType { /// <summary> /// Initializes a new instance of the Interviewee class. /// </summary> public Interviewee() : base() { } /// <summary> /// Initializes a new instance of the Interviewee class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Interviewee(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Interviewee class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Interviewee(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Interviewee class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Interviewee(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Interviewee"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Interviewee>(deep); } /// <summary> /// <para>Interviewer.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Interviewer.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Interviewer : NameType { /// <summary> /// Initializes a new instance of the Interviewer class. /// </summary> public Interviewer() : base() { } /// <summary> /// Initializes a new instance of the Interviewer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Interviewer(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Interviewer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Interviewer(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Interviewer class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Interviewer(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Interviewer"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Interviewer>(deep); } /// <summary> /// <para>Inventor.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Inventor.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Inventor : NameType { /// <summary> /// Initializes a new instance of the Inventor class. /// </summary> public Inventor() : base() { } /// <summary> /// Initializes a new instance of the Inventor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Inventor(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Inventor class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Inventor(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Inventor class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Inventor(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Inventor"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Inventor>(deep); } /// <summary> /// <para>Producer Name.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:ProducerName.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class ProducerName : NameType { /// <summary> /// Initializes a new instance of the ProducerName class. /// </summary> public ProducerName() : base() { } /// <summary> /// Initializes a new instance of the ProducerName class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ProducerName(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ProducerName class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ProducerName(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ProducerName class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ProducerName(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "ProducerName"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ProducerName>(deep); } /// <summary> /// <para>Translator.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Translator.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Translator : NameType { /// <summary> /// Initializes a new instance of the Translator class. /// </summary> public Translator() : base() { } /// <summary> /// Initializes a new instance of the Translator class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Translator(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Translator class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Translator(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Translator class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Translator(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Translator"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Translator>(deep); } /// <summary> /// <para>Writer.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Writer.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public partial class Writer : NameType { /// <summary> /// Initializes a new instance of the Writer class. /// </summary> public Writer() : base() { } /// <summary> /// Initializes a new instance of the Writer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Writer(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Writer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Writer(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Writer class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Writer(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Writer"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Writer>(deep); } /// <summary> /// <para>Defines the NameType Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is :.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// </list> /// </remark> public abstract partial class NameType : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NameType class. /// </summary> protected NameType() : base() { } /// <summary> /// Initializes a new instance of the NameType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected NameType(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NameType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected NameType(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NameType class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> protected NameType(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddChild<NameList>(); } /// <summary> /// <para>Name List.</para> /// <para>Represents the following element tag in the schema: b:NameList.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public NameList NameList { get => GetElement<NameList>(); set => SetElement(value); } } /// <summary> /// <para>Author.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Author.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// <item><description>Corporate &lt;b:Corporate></description></item> /// </list> /// </remark> public partial class Author : NameOrCorporateType { /// <summary> /// Initializes a new instance of the Author class. /// </summary> public Author() : base() { } /// <summary> /// Initializes a new instance of the Author class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Author(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Author class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Author(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Author class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Author(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Author"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new CompositeParticle(ParticleType.Choice, 0, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Corporate), 1, 1) } }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Author>(deep); } /// <summary> /// <para>Performer.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Performer.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// <item><description>Corporate &lt;b:Corporate></description></item> /// </list> /// </remark> public partial class Performer : NameOrCorporateType { /// <summary> /// Initializes a new instance of the Performer class. /// </summary> public Performer() : base() { } /// <summary> /// Initializes a new instance of the Performer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Performer(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Performer class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Performer(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Performer class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Performer(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Performer"); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new CompositeParticle(ParticleType.Choice, 0, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NameList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Corporate), 1, 1) } }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Performer>(deep); } /// <summary> /// <para>Defines the NameOrCorporateType Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is :.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NameList &lt;b:NameList></description></item> /// <item><description>Corporate &lt;b:Corporate></description></item> /// </list> /// </remark> public abstract partial class NameOrCorporateType : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NameOrCorporateType class. /// </summary> protected NameOrCorporateType() : base() { } /// <summary> /// Initializes a new instance of the NameOrCorporateType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected NameOrCorporateType(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NameOrCorporateType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected NameOrCorporateType(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NameOrCorporateType class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> protected NameOrCorporateType(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddChild<NameList>(); builder.AddChild<Corporate>(); } /// <summary> /// <para>NameList.</para> /// <para>Represents the following element tag in the schema: b:NameList.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public NameList NameList { get => GetElement<NameList>(); set => SetElement(value); } /// <summary> /// <para>Corporate Author.</para> /// <para>Represents the following element tag in the schema: b:Corporate.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Corporate Corporate { get => GetElement<Corporate>(); set => SetElement(value); } } /// <summary> /// <para>Contributors List.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Author.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>Artist &lt;b:Artist></description></item> /// <item><description>Author &lt;b:Author></description></item> /// <item><description>BookAuthor &lt;b:BookAuthor></description></item> /// <item><description>Compiler &lt;b:Compiler></description></item> /// <item><description>Composer &lt;b:Composer></description></item> /// <item><description>Conductor &lt;b:Conductor></description></item> /// <item><description>Counsel &lt;b:Counsel></description></item> /// <item><description>Director &lt;b:Director></description></item> /// <item><description>Editor &lt;b:Editor></description></item> /// <item><description>Interviewee &lt;b:Interviewee></description></item> /// <item><description>Interviewer &lt;b:Interviewer></description></item> /// <item><description>Inventor &lt;b:Inventor></description></item> /// <item><description>Performer &lt;b:Performer></description></item> /// <item><description>ProducerName &lt;b:ProducerName></description></item> /// <item><description>Translator &lt;b:Translator></description></item> /// <item><description>Writer &lt;b:Writer></description></item> /// </list> /// </remark> public partial class AuthorList : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the AuthorList class. /// </summary> public AuthorList() : base() { } /// <summary> /// Initializes a new instance of the AuthorList class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AuthorList(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AuthorList class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public AuthorList(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AuthorList class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public AuthorList(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Author"); builder.AddChild<Artist>(); builder.AddChild<Author>(); builder.AddChild<BookAuthor>(); builder.AddChild<Compiler>(); builder.AddChild<Composer>(); builder.AddChild<Conductor>(); builder.AddChild<Counsel>(); builder.AddChild<Director>(); builder.AddChild<Editor>(); builder.AddChild<Interviewee>(); builder.AddChild<Interviewer>(); builder.AddChild<Inventor>(); builder.AddChild<Performer>(); builder.AddChild<ProducerName>(); builder.AddChild<Translator>(); builder.AddChild<Writer>(); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new CompositeParticle(ParticleType.Choice, 0, 0) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Artist), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Author), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.BookAuthor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Compiler), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Composer), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Conductor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Counsel), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Director), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Editor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Interviewee), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Interviewer), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Inventor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Performer), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.ProducerName), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Translator), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Writer), 1, 1) } }; } /// <summary> /// <para>Artist.</para> /// <para>Represents the following element tag in the schema: b:Artist.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Artist Artist { get => GetElement<Artist>(); set => SetElement(value); } /// <summary> /// <para>Author.</para> /// <para>Represents the following element tag in the schema: b:Author.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Author Author { get => GetElement<Author>(); set => SetElement(value); } /// <summary> /// <para>Book Author.</para> /// <para>Represents the following element tag in the schema: b:BookAuthor.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public BookAuthor BookAuthor { get => GetElement<BookAuthor>(); set => SetElement(value); } /// <summary> /// <para>Compiler.</para> /// <para>Represents the following element tag in the schema: b:Compiler.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Compiler Compiler { get => GetElement<Compiler>(); set => SetElement(value); } /// <summary> /// <para>Composer.</para> /// <para>Represents the following element tag in the schema: b:Composer.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Composer Composer { get => GetElement<Composer>(); set => SetElement(value); } /// <summary> /// <para>Conductor.</para> /// <para>Represents the following element tag in the schema: b:Conductor.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Conductor Conductor { get => GetElement<Conductor>(); set => SetElement(value); } /// <summary> /// <para>Counsel.</para> /// <para>Represents the following element tag in the schema: b:Counsel.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Counsel Counsel { get => GetElement<Counsel>(); set => SetElement(value); } /// <summary> /// <para>Director.</para> /// <para>Represents the following element tag in the schema: b:Director.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Director Director { get => GetElement<Director>(); set => SetElement(value); } /// <summary> /// <para>Editor.</para> /// <para>Represents the following element tag in the schema: b:Editor.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Editor Editor { get => GetElement<Editor>(); set => SetElement(value); } /// <summary> /// <para>Interviewee.</para> /// <para>Represents the following element tag in the schema: b:Interviewee.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Interviewee Interviewee { get => GetElement<Interviewee>(); set => SetElement(value); } /// <summary> /// <para>Interviewer.</para> /// <para>Represents the following element tag in the schema: b:Interviewer.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Interviewer Interviewer { get => GetElement<Interviewer>(); set => SetElement(value); } /// <summary> /// <para>Inventor.</para> /// <para>Represents the following element tag in the schema: b:Inventor.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Inventor Inventor { get => GetElement<Inventor>(); set => SetElement(value); } /// <summary> /// <para>Performer.</para> /// <para>Represents the following element tag in the schema: b:Performer.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Performer Performer { get => GetElement<Performer>(); set => SetElement(value); } /// <summary> /// <para>Producer Name.</para> /// <para>Represents the following element tag in the schema: b:ProducerName.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public ProducerName ProducerName { get => GetElement<ProducerName>(); set => SetElement(value); } /// <summary> /// <para>Translator.</para> /// <para>Represents the following element tag in the schema: b:Translator.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Translator Translator { get => GetElement<Translator>(); set => SetElement(value); } /// <summary> /// <para>Writer.</para> /// <para>Represents the following element tag in the schema: b:Writer.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Writer Writer { get => GetElement<Writer>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<AuthorList>(deep); } /// <summary> /// <para>Source Type.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:SourceType.</para> /// </summary> public partial class SourceType : OpenXmlLeafTextElement { /// <summary> /// Initializes a new instance of the SourceType class. /// </summary> public SourceType() : base() { } /// <summary> /// Initializes a new instance of the SourceType class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public SourceType(string text) : base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new EnumValue<DocumentFormat.OpenXml.Bibliography.DataSourceValues> { InnerText = text }; } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddValidator<EnumValue<DocumentFormat.OpenXml.Bibliography.DataSourceValues>>(EnumValidator.Instance); builder.SetSchema(9, "SourceType"); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<SourceType>(deep); } /// <summary> /// <para>Source.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is b:Source.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>AbbreviatedCaseNumber &lt;b:AbbreviatedCaseNumber></description></item> /// <item><description>AlbumTitle &lt;b:AlbumTitle></description></item> /// <item><description>AuthorList &lt;b:Author></description></item> /// <item><description>BookTitle &lt;b:BookTitle></description></item> /// <item><description>Broadcaster &lt;b:Broadcaster></description></item> /// <item><description>BroadcastTitle &lt;b:BroadcastTitle></description></item> /// <item><description>CaseNumber &lt;b:CaseNumber></description></item> /// <item><description>ChapterNumber &lt;b:ChapterNumber></description></item> /// <item><description>City &lt;b:City></description></item> /// <item><description>Comments &lt;b:Comments></description></item> /// <item><description>ConferenceName &lt;b:ConferenceName></description></item> /// <item><description>CountryRegion &lt;b:CountryRegion></description></item> /// <item><description>Court &lt;b:Court></description></item> /// <item><description>Day &lt;b:Day></description></item> /// <item><description>DayAccessed &lt;b:DayAccessed></description></item> /// <item><description>Department &lt;b:Department></description></item> /// <item><description>Distributor &lt;b:Distributor></description></item> /// <item><description>Edition &lt;b:Edition></description></item> /// <item><description>GuidString &lt;b:Guid></description></item> /// <item><description>Institution &lt;b:Institution></description></item> /// <item><description>InternetSiteTitle &lt;b:InternetSiteTitle></description></item> /// <item><description>Issue &lt;b:Issue></description></item> /// <item><description>JournalName &lt;b:JournalName></description></item> /// <item><description>LcId &lt;b:LCID></description></item> /// <item><description>Medium &lt;b:Medium></description></item> /// <item><description>Month &lt;b:Month></description></item> /// <item><description>MonthAccessed &lt;b:MonthAccessed></description></item> /// <item><description>NumberVolumes &lt;b:NumberVolumes></description></item> /// <item><description>Pages &lt;b:Pages></description></item> /// <item><description>PatentNumber &lt;b:PatentNumber></description></item> /// <item><description>PeriodicalTitle &lt;b:PeriodicalTitle></description></item> /// <item><description>ProductionCompany &lt;b:ProductionCompany></description></item> /// <item><description>PublicationTitle &lt;b:PublicationTitle></description></item> /// <item><description>Publisher &lt;b:Publisher></description></item> /// <item><description>RecordingNumber &lt;b:RecordingNumber></description></item> /// <item><description>ReferenceOrder &lt;b:RefOrder></description></item> /// <item><description>Reporter &lt;b:Reporter></description></item> /// <item><description>SourceType &lt;b:SourceType></description></item> /// <item><description>ShortTitle &lt;b:ShortTitle></description></item> /// <item><description>StandardNumber &lt;b:StandardNumber></description></item> /// <item><description>StateProvince &lt;b:StateProvince></description></item> /// <item><description>Station &lt;b:Station></description></item> /// <item><description>Tag &lt;b:Tag></description></item> /// <item><description>Theater &lt;b:Theater></description></item> /// <item><description>ThesisType &lt;b:ThesisType></description></item> /// <item><description>Title &lt;b:Title></description></item> /// <item><description>PatentType &lt;b:Type></description></item> /// <item><description>UrlString &lt;b:URL></description></item> /// <item><description>Version &lt;b:Version></description></item> /// <item><description>Volume &lt;b:Volume></description></item> /// <item><description>Year &lt;b:Year></description></item> /// <item><description>YearAccessed &lt;b:YearAccessed></description></item> /// </list> /// </remark> public partial class Source : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Source class. /// </summary> public Source() : base() { } /// <summary> /// Initializes a new instance of the Source class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Source(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Source class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Source(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Source class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Source(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(9, "Source"); builder.AddChild<AbbreviatedCaseNumber>(); builder.AddChild<AlbumTitle>(); builder.AddChild<AuthorList>(); builder.AddChild<BookTitle>(); builder.AddChild<Broadcaster>(); builder.AddChild<BroadcastTitle>(); builder.AddChild<CaseNumber>(); builder.AddChild<ChapterNumber>(); builder.AddChild<City>(); builder.AddChild<Comments>(); builder.AddChild<ConferenceName>(); builder.AddChild<CountryRegion>(); builder.AddChild<Court>(); builder.AddChild<Day>(); builder.AddChild<DayAccessed>(); builder.AddChild<Department>(); builder.AddChild<Distributor>(); builder.AddChild<Edition>(); builder.AddChild<GuidString>(); builder.AddChild<Institution>(); builder.AddChild<InternetSiteTitle>(); builder.AddChild<Issue>(); builder.AddChild<JournalName>(); builder.AddChild<LcId>(); builder.AddChild<Medium>(); builder.AddChild<Month>(); builder.AddChild<MonthAccessed>(); builder.AddChild<NumberVolumes>(); builder.AddChild<Pages>(); builder.AddChild<PatentNumber>(); builder.AddChild<PeriodicalTitle>(); builder.AddChild<ProductionCompany>(); builder.AddChild<PublicationTitle>(); builder.AddChild<Publisher>(); builder.AddChild<RecordingNumber>(); builder.AddChild<ReferenceOrder>(); builder.AddChild<Reporter>(); builder.AddChild<SourceType>(); builder.AddChild<ShortTitle>(); builder.AddChild<StandardNumber>(); builder.AddChild<StateProvince>(); builder.AddChild<Station>(); builder.AddChild<Tag>(); builder.AddChild<Theater>(); builder.AddChild<ThesisType>(); builder.AddChild<Title>(); builder.AddChild<PatentType>(); builder.AddChild<UrlString>(); builder.AddChild<Version>(); builder.AddChild<Volume>(); builder.AddChild<Year>(); builder.AddChild<YearAccessed>(); builder.Particle = new CompositeParticle(ParticleType.Sequence, 1, 1) { new CompositeParticle(ParticleType.Choice, 0, 0) { new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.AbbreviatedCaseNumber), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.AlbumTitle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.AuthorList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.BookTitle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Broadcaster), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.BroadcastTitle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.CaseNumber), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.ChapterNumber), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.City), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Comments), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.ConferenceName), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.CountryRegion), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Court), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Day), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.DayAccessed), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Department), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Distributor), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Edition), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.GuidString), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Institution), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.InternetSiteTitle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Issue), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.JournalName), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.LcId), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Medium), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Month), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.MonthAccessed), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.NumberVolumes), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Pages), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.PatentNumber), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.PeriodicalTitle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.ProductionCompany), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.PublicationTitle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Publisher), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.RecordingNumber), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.ReferenceOrder), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Reporter), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.SourceType), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.ShortTitle), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.StandardNumber), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.StateProvince), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Station), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Tag), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Theater), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.ThesisType), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Title), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.PatentType), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.UrlString), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Version), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Volume), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.Year), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Bibliography.YearAccessed), 1, 1) } }; } /// <summary> /// <para>Abbreviated Case Number.</para> /// <para>Represents the following element tag in the schema: b:AbbreviatedCaseNumber.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public AbbreviatedCaseNumber AbbreviatedCaseNumber { get => GetElement<AbbreviatedCaseNumber>(); set => SetElement(value); } /// <summary> /// <para>Album Title.</para> /// <para>Represents the following element tag in the schema: b:AlbumTitle.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public AlbumTitle AlbumTitle { get => GetElement<AlbumTitle>(); set => SetElement(value); } /// <summary> /// <para>Contributors List.</para> /// <para>Represents the following element tag in the schema: b:Author.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public AuthorList AuthorList { get => GetElement<AuthorList>(); set => SetElement(value); } /// <summary> /// <para>Book Title.</para> /// <para>Represents the following element tag in the schema: b:BookTitle.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public BookTitle BookTitle { get => GetElement<BookTitle>(); set => SetElement(value); } /// <summary> /// <para>Broadcaster.</para> /// <para>Represents the following element tag in the schema: b:Broadcaster.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Broadcaster Broadcaster { get => GetElement<Broadcaster>(); set => SetElement(value); } /// <summary> /// <para>Broadcast Title.</para> /// <para>Represents the following element tag in the schema: b:BroadcastTitle.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public BroadcastTitle BroadcastTitle { get => GetElement<BroadcastTitle>(); set => SetElement(value); } /// <summary> /// <para>Case Number.</para> /// <para>Represents the following element tag in the schema: b:CaseNumber.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public CaseNumber CaseNumber { get => GetElement<CaseNumber>(); set => SetElement(value); } /// <summary> /// <para>Chapter Number.</para> /// <para>Represents the following element tag in the schema: b:ChapterNumber.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public ChapterNumber ChapterNumber { get => GetElement<ChapterNumber>(); set => SetElement(value); } /// <summary> /// <para>City.</para> /// <para>Represents the following element tag in the schema: b:City.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public City City { get => GetElement<City>(); set => SetElement(value); } /// <summary> /// <para>Comments.</para> /// <para>Represents the following element tag in the schema: b:Comments.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Comments Comments { get => GetElement<Comments>(); set => SetElement(value); } /// <summary> /// <para>Conference or Proceedings Name.</para> /// <para>Represents the following element tag in the schema: b:ConferenceName.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public ConferenceName ConferenceName { get => GetElement<ConferenceName>(); set => SetElement(value); } /// <summary> /// <para>Country or Region.</para> /// <para>Represents the following element tag in the schema: b:CountryRegion.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public CountryRegion CountryRegion { get => GetElement<CountryRegion>(); set => SetElement(value); } /// <summary> /// <para>Court.</para> /// <para>Represents the following element tag in the schema: b:Court.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Court Court { get => GetElement<Court>(); set => SetElement(value); } /// <summary> /// <para>Day.</para> /// <para>Represents the following element tag in the schema: b:Day.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Day Day { get => GetElement<Day>(); set => SetElement(value); } /// <summary> /// <para>Day Accessed.</para> /// <para>Represents the following element tag in the schema: b:DayAccessed.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public DayAccessed DayAccessed { get => GetElement<DayAccessed>(); set => SetElement(value); } /// <summary> /// <para>Department.</para> /// <para>Represents the following element tag in the schema: b:Department.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Department Department { get => GetElement<Department>(); set => SetElement(value); } /// <summary> /// <para>Distributor.</para> /// <para>Represents the following element tag in the schema: b:Distributor.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Distributor Distributor { get => GetElement<Distributor>(); set => SetElement(value); } /// <summary> /// <para>Editor.</para> /// <para>Represents the following element tag in the schema: b:Edition.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Edition Edition { get => GetElement<Edition>(); set => SetElement(value); } /// <summary> /// <para>GUID.</para> /// <para>Represents the following element tag in the schema: b:Guid.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public GuidString GuidString { get => GetElement<GuidString>(); set => SetElement(value); } /// <summary> /// <para>Institution.</para> /// <para>Represents the following element tag in the schema: b:Institution.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Institution Institution { get => GetElement<Institution>(); set => SetElement(value); } /// <summary> /// <para>Internet Site Title.</para> /// <para>Represents the following element tag in the schema: b:InternetSiteTitle.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public InternetSiteTitle InternetSiteTitle { get => GetElement<InternetSiteTitle>(); set => SetElement(value); } /// <summary> /// <para>Issue.</para> /// <para>Represents the following element tag in the schema: b:Issue.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Issue Issue { get => GetElement<Issue>(); set => SetElement(value); } /// <summary> /// <para>Journal Name.</para> /// <para>Represents the following element tag in the schema: b:JournalName.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public JournalName JournalName { get => GetElement<JournalName>(); set => SetElement(value); } /// <summary> /// <para>Locale ID.</para> /// <para>Represents the following element tag in the schema: b:LCID.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public LcId LcId { get => GetElement<LcId>(); set => SetElement(value); } /// <summary> /// <para>Medium.</para> /// <para>Represents the following element tag in the schema: b:Medium.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Medium Medium { get => GetElement<Medium>(); set => SetElement(value); } /// <summary> /// <para>Month.</para> /// <para>Represents the following element tag in the schema: b:Month.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Month Month { get => GetElement<Month>(); set => SetElement(value); } /// <summary> /// <para>Month Accessed.</para> /// <para>Represents the following element tag in the schema: b:MonthAccessed.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public MonthAccessed MonthAccessed { get => GetElement<MonthAccessed>(); set => SetElement(value); } /// <summary> /// <para>Number of Volumes.</para> /// <para>Represents the following element tag in the schema: b:NumberVolumes.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public NumberVolumes NumberVolumes { get => GetElement<NumberVolumes>(); set => SetElement(value); } /// <summary> /// <para>Pages.</para> /// <para>Represents the following element tag in the schema: b:Pages.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Pages Pages { get => GetElement<Pages>(); set => SetElement(value); } /// <summary> /// <para>Patent Number.</para> /// <para>Represents the following element tag in the schema: b:PatentNumber.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public PatentNumber PatentNumber { get => GetElement<PatentNumber>(); set => SetElement(value); } /// <summary> /// <para>Periodical Title.</para> /// <para>Represents the following element tag in the schema: b:PeriodicalTitle.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public PeriodicalTitle PeriodicalTitle { get => GetElement<PeriodicalTitle>(); set => SetElement(value); } /// <summary> /// <para>Production Company.</para> /// <para>Represents the following element tag in the schema: b:ProductionCompany.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public ProductionCompany ProductionCompany { get => GetElement<ProductionCompany>(); set => SetElement(value); } /// <summary> /// <para>Publication Title.</para> /// <para>Represents the following element tag in the schema: b:PublicationTitle.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public PublicationTitle PublicationTitle { get => GetElement<PublicationTitle>(); set => SetElement(value); } /// <summary> /// <para>Publisher.</para> /// <para>Represents the following element tag in the schema: b:Publisher.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Publisher Publisher { get => GetElement<Publisher>(); set => SetElement(value); } /// <summary> /// <para>Recording Number.</para> /// <para>Represents the following element tag in the schema: b:RecordingNumber.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public RecordingNumber RecordingNumber { get => GetElement<RecordingNumber>(); set => SetElement(value); } /// <summary> /// <para>Reference Order.</para> /// <para>Represents the following element tag in the schema: b:RefOrder.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public ReferenceOrder ReferenceOrder { get => GetElement<ReferenceOrder>(); set => SetElement(value); } /// <summary> /// <para>Reporter.</para> /// <para>Represents the following element tag in the schema: b:Reporter.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Reporter Reporter { get => GetElement<Reporter>(); set => SetElement(value); } /// <summary> /// <para>Source Type.</para> /// <para>Represents the following element tag in the schema: b:SourceType.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public SourceType SourceType { get => GetElement<SourceType>(); set => SetElement(value); } /// <summary> /// <para>Short Title.</para> /// <para>Represents the following element tag in the schema: b:ShortTitle.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public ShortTitle ShortTitle { get => GetElement<ShortTitle>(); set => SetElement(value); } /// <summary> /// <para>Standard Number.</para> /// <para>Represents the following element tag in the schema: b:StandardNumber.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public StandardNumber StandardNumber { get => GetElement<StandardNumber>(); set => SetElement(value); } /// <summary> /// <para>State or Province.</para> /// <para>Represents the following element tag in the schema: b:StateProvince.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public StateProvince StateProvince { get => GetElement<StateProvince>(); set => SetElement(value); } /// <summary> /// <para>Station.</para> /// <para>Represents the following element tag in the schema: b:Station.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Station Station { get => GetElement<Station>(); set => SetElement(value); } /// <summary> /// <para>Tag.</para> /// <para>Represents the following element tag in the schema: b:Tag.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Tag Tag { get => GetElement<Tag>(); set => SetElement(value); } /// <summary> /// <para>Theater.</para> /// <para>Represents the following element tag in the schema: b:Theater.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Theater Theater { get => GetElement<Theater>(); set => SetElement(value); } /// <summary> /// <para>Thesis Type.</para> /// <para>Represents the following element tag in the schema: b:ThesisType.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public ThesisType ThesisType { get => GetElement<ThesisType>(); set => SetElement(value); } /// <summary> /// <para>Title.</para> /// <para>Represents the following element tag in the schema: b:Title.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Title Title { get => GetElement<Title>(); set => SetElement(value); } /// <summary> /// <para>Type.</para> /// <para>Represents the following element tag in the schema: b:Type.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public PatentType PatentType { get => GetElement<PatentType>(); set => SetElement(value); } /// <summary> /// <para>URL.</para> /// <para>Represents the following element tag in the schema: b:URL.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public UrlString UrlString { get => GetElement<UrlString>(); set => SetElement(value); } /// <summary> /// <para>Version.</para> /// <para>Represents the following element tag in the schema: b:Version.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Version Version { get => GetElement<Version>(); set => SetElement(value); } /// <summary> /// <para>Volume.</para> /// <para>Represents the following element tag in the schema: b:Volume.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Volume Volume { get => GetElement<Volume>(); set => SetElement(value); } /// <summary> /// <para>Year.</para> /// <para>Represents the following element tag in the schema: b:Year.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public Year Year { get => GetElement<Year>(); set => SetElement(value); } /// <summary> /// <para>Year Accessed.</para> /// <para>Represents the following element tag in the schema: b:YearAccessed.</para> /// </summary> /// <remark> /// xmlns:b = http://schemas.openxmlformats.org/officeDocument/2006/bibliography /// </remark> public YearAccessed YearAccessed { get => GetElement<YearAccessed>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Source>(deep); } /// <summary> /// Bibliographic Data Source Types /// </summary> public enum DataSourceValues { ///<summary> ///Article in a Periodical. ///<para>When the item is serialized out as xml, its value is "ArticleInAPeriodical".</para> ///</summary> [EnumString("ArticleInAPeriodical")] ArticleInAPeriodical, ///<summary> ///Book. ///<para>When the item is serialized out as xml, its value is "Book".</para> ///</summary> [EnumString("Book")] Book, ///<summary> ///Book Section. ///<para>When the item is serialized out as xml, its value is "BookSection".</para> ///</summary> [EnumString("BookSection")] BookSection, ///<summary> ///Journal Article. ///<para>When the item is serialized out as xml, its value is "JournalArticle".</para> ///</summary> [EnumString("JournalArticle")] JournalArticle, ///<summary> ///Conference Proceedings. ///<para>When the item is serialized out as xml, its value is "ConferenceProceedings".</para> ///</summary> [EnumString("ConferenceProceedings")] ConferenceProceedings, ///<summary> ///Reporter. ///<para>When the item is serialized out as xml, its value is "Report".</para> ///</summary> [EnumString("Report")] Report, ///<summary> ///Sound Recording. ///<para>When the item is serialized out as xml, its value is "SoundRecording".</para> ///</summary> [EnumString("SoundRecording")] SoundRecording, ///<summary> ///Performance. ///<para>When the item is serialized out as xml, its value is "Performance".</para> ///</summary> [EnumString("Performance")] Performance, ///<summary> ///Art. ///<para>When the item is serialized out as xml, its value is "Art".</para> ///</summary> [EnumString("Art")] Art, ///<summary> ///Document from Internet Site. ///<para>When the item is serialized out as xml, its value is "DocumentFromInternetSite".</para> ///</summary> [EnumString("DocumentFromInternetSite")] DocumentFromInternetSite, ///<summary> ///Internet Site. ///<para>When the item is serialized out as xml, its value is "InternetSite".</para> ///</summary> [EnumString("InternetSite")] InternetSite, ///<summary> ///Film. ///<para>When the item is serialized out as xml, its value is "Film".</para> ///</summary> [EnumString("Film")] Film, ///<summary> ///Interview. ///<para>When the item is serialized out as xml, its value is "Interview".</para> ///</summary> [EnumString("Interview")] Interview, ///<summary> ///Patent. ///<para>When the item is serialized out as xml, its value is "Patent".</para> ///</summary> [EnumString("Patent")] Patent, ///<summary> ///Electronic Source. ///<para>When the item is serialized out as xml, its value is "ElectronicSource".</para> ///</summary> [EnumString("ElectronicSource")] ElectronicSource, ///<summary> ///Case. ///<para>When the item is serialized out as xml, its value is "Case".</para> ///</summary> [EnumString("Case")] Case, ///<summary> ///Miscellaneous. ///<para>When the item is serialized out as xml, its value is "Misc".</para> ///</summary> [EnumString("Misc")] Miscellaneous, } }
37.268515
122
0.586058
[ "MIT" ]
06needhamt/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_openxmlformats_org_officeDocument_2006_bibliography.g.cs
176,133
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("IntersectionOfCircle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IntersectionOfCircle")] [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("02cded99-0a9c-48a2-8e22-fc130350031c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.189189
84
0.748054
[ "MIT" ]
stoyantodorovbg/Programming-Fundamentals
ObjectAndClassesExercise/IntersectionOfCircle/Properties/AssemblyInfo.cs
1,416
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using Microsoft.Bot.Builder.Dialogs.Declarative; using Microsoft.Bot.Builder.Dialogs.Declarative.Types; namespace Microsoft.Bot.Builder.MockLuis { public class MockLuisComponentRegistration : ComponentRegistration { public override IEnumerable<TypeRegistration> GetTypes() { // Recognizers yield return new TypeRegistration<MockLuisRecognizer>("Microsoft.LuisRecognizer") { CustomDeserializer = new MockLuisLoader(TypeFactory.Configuration) }; } } }
33.842105
165
0.74339
[ "MIT" ]
IgorVukovic753/FbBot
libraries/Microsoft.Bot.Builder.Dialogs.Adaptive/Testing/MockLuis/MockLuisComponentRegistration.cs
645
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ksmedia.h(1465,9) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct __struct_ksmedia_25 { public int Property; public uint BaseAddress; public uint RequestedBufferSize; public uint NotificationCount; } }
25.375
88
0.70936
[ "MIT" ]
riQQ/DirectN
DirectN/DirectN/Generated/__struct_ksmedia_25.cs
408
C#
namespace PaymentGateway.Api.Settings { public class AcquiringBankSettings { public string BaseUrl { get; set; } } }
18.125
44
0.627586
[ "MIT" ]
serenya/payment-service-provider
src/PaymentGateway/PaymentGateway.Api/Settings/AcquiringBankSettings.cs
147
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CASimulator { /// <summary> /// Interaction logic for CASimLauncher.xaml /// </summary> public partial class CASimLauncher : Window { private enum SimType { oned, twod, ant } private int _rows, _columns, _cellsize, _animspeed; private int _type; private bool _isToroidal; private string _rules; public CASimLauncher() { _rows = 10; _columns = 10; _cellsize = 4; _animspeed = 100; _isToroidal = true; _type = 1; _rules = "See the help for details."; InitializeComponent(); } /// <summary> /// The simulation should be 1D. /// Rules are re-evaluated for 1D. /// </summary> private void bttn1d_Checked(object sender, RoutedEventArgs e) { if (!IsLoaded) //Prevents bttnLaunch from being null. return; _type = 0; chkbxWrap.IsEnabled = true; if (CASim1D.CheckRules(txbxRules.Text)) bttnLaunch.IsEnabled = true; else bttnLaunch.IsEnabled = false; } /// <summary> /// The simulation should be 2D. /// Rules are re-evaluated for 2D. /// </summary> private void bttn2d_Checked(object sender, RoutedEventArgs e) { if (!IsLoaded) //Prevents bttnLaunch from being null. return; _type = 1; chkbxWrap.IsEnabled = true; if (CASim2D.CheckRules(txbxRules.Text)) bttnLaunch.IsEnabled = true; else bttnLaunch.IsEnabled = false; } /// <summary> /// The simulation should be 2D. /// Rules are re-evaluated for 2D. /// </summary> private void bttnant_Checked(object sender, RoutedEventArgs e) { if (!IsLoaded) //Prevents bttnLaunch from being null. return; _type = 2; chkbxWrap.IsEnabled = false; if (CASim2DAnt.CheckRules(txbxRules.Text)) bttnLaunch.IsEnabled = true; else bttnLaunch.IsEnabled = false; } /// <summary> /// The cell size is changed; non-numeric data is removed. /// </summary> private void txbxCellSize_TextChanged(object sender, TextChangedEventArgs e) { if (!IsLoaded) //Prevents null exceptions during init. return; //Text can only be numbers. txbxCellSize.Text = ApplyFilter(txbxCellSize.Text, @"\D"); //Limits text length to 2 digits. if (txbxCellSize.Text.Length == 0) return; else if (txbxCellSize.Text.Length > 2) txbxCellSize.Text = txbxCellSize.Text.Substring(0, 2); //Limits data range to 1 and 50 inclusive. int value = Int32.Parse(txbxCellSize.Text); if (value < 1) txbxCellSize.Text = "1"; else if (value > 50) txbxCellSize.Text = "50"; //Sets cell size and reparses text if it changed. _cellsize = Int32.Parse(txbxCellSize.Text); } /// <summary> /// The cell rows are changed; non-numeric data is removed. /// </summary> private void txbxCellRows_TextChanged(object sender, TextChangedEventArgs e) { if (!IsLoaded) //Prevents null exceptions during init. return; //Text can only be numbers. txbxCellRows.Text = ApplyFilter(txbxCellRows.Text, @"\D"); //Limits text length to 4 digits. if (txbxCellRows.Text.Length == 0) return; else if (txbxCellRows.Text.Length > 4) txbxCellRows.Text = txbxCellRows.Text.Substring(0, 4); //Limits data range to 2 and 2000 inclusive. int value = Int32.Parse(txbxCellRows.Text); if (value < 2) txbxCellRows.Text = "2"; else if (value > 2000) txbxCellRows.Text = "2000"; //Sets cell rows and reparses text if it changed. _rows = Int32.Parse(txbxCellRows.Text); } /// <summary> /// The cell cols are changed; non-numeric data is removed. /// This is disabled as long as 1D is enabled. /// </summary> private void txbxCellCols_TextChanged(object sender, TextChangedEventArgs e) { if (!IsLoaded) //Prevents null exceptions during init. return; //Text can only be numbers. txbxCellCols.Text = ApplyFilter(txbxCellCols.Text, @"\D"); //Limits text length to 4 digits. if (txbxCellCols.Text.Length == 0) return; else if (txbxCellCols.Text.Length > 4) txbxCellCols.Text = txbxCellCols.Text.Substring(0, 4); //Limits data range to 2 and 2000 inclusive. int value = Int32.Parse(txbxCellCols.Text); if (value < 2) txbxCellCols.Text = "2"; else if (value > 2000) txbxCellCols.Text = "2000"; //Sets cell columns and reparses text if it changed. _columns = Int32.Parse(txbxCellCols.Text); } /// <summary> /// Toggles whether the grid wraps around or not. /// This is disabled as long as Langston's ants are enabled. /// </summary> private void chkbxWrap_Checked(object sender, RoutedEventArgs e) { if (!IsLoaded) //prevents null exceptions during init. return; //Returns false if IsChecked is null. _isToroidal = (chkbxWrap.IsChecked ?? false); } /// <summary> /// The update speed is changed; non-numeric data is removed. /// Update speeds are restricted to values > 4 and less than 10000. /// Update speeds are rounded to integers. /// </summary> private void txbxUpdateSpeed_TextChanged(object sender, TextChangedEventArgs e) { if (!IsLoaded) //Prevents null exceptions during init. return; //Text can only be numbers. txbxUpdateSpeed.Text = ApplyFilter(txbxUpdateSpeed.Text, @"\D"); //Limits text length to 5 digits. if (txbxUpdateSpeed.Text.Length == 0) return; else if (txbxUpdateSpeed.Text.Length > 5) txbxUpdateSpeed.Text = txbxUpdateSpeed.Text.Substring(0, 5); //Limits data range to 5 and 10000 inclusive. int value = Int32.Parse(txbxUpdateSpeed.Text); if (value < 5) txbxUpdateSpeed.Text = "5"; else if (value > 10000) txbxUpdateSpeed.Text = "10000"; //Sets cell columns and reparses text if it changed. _animspeed = Int32.Parse(txbxUpdateSpeed.Text); } /// <summary> /// The rules are changed. /// The launch button is disabled if rules are invalid. /// </summary> private void txbxRules_TextChanged(object sender, TextChangedEventArgs e) { if (!IsLoaded) //Prevents null exceptions during init. return; switch (_type) { case 0: if (CASim1D.CheckRules(txbxRules.Text)) bttnLaunch.IsEnabled = true; else bttnLaunch.IsEnabled = false; break; case 1: if (CASim2D.CheckRules(txbxRules.Text)) bttnLaunch.IsEnabled = true; else bttnLaunch.IsEnabled = false; break; case 2: if (CASim2DAnt.CheckRules(txbxRules.Text)) bttnLaunch.IsEnabled = true; else bttnLaunch.IsEnabled = false; break; } _rules = txbxRules.Text; } /// <summary> /// Launches an automaton simulation window with the given settings. /// The launch button is disabled if rules are invalid. /// </summary> private void bttnLaunch_Click(object sender, RoutedEventArgs e) { switch (_type) { case 0: CASim1DGui simDialog2 = new CASim1DGui(_columns, _cellsize, _isToroidal, _rules, new TimeSpan(0, 0, 0, 0, _animspeed)); simDialog2.cellColors = CAPresets.ColorsBinary; simDialog2.Show(); simDialog2.UpdateGui(); break; case 1: CASim2DGui simDialog1 = new CASim2DGui(_rows, _columns, _cellsize, _isToroidal, _rules, new TimeSpan(0, 0, 0, 0, _animspeed)); simDialog1.cellColors = CAPresets.ColorsBinary; simDialog1.Show(); simDialog1.UpdateGui(true); break; case 2: CASim2DAntGui simDialog3 = new CASim2DAntGui(new CAAnt2D[0], _rows, _columns, _cellsize, _rules, new TimeSpan(0, 0, 0, 0, _animspeed)); simDialog3.cellColors = CAPresets.ColorsRainbow; simDialog3.antColors = CAPresets.ColorsGrayscale8; simDialog3.Show(); simDialog3.UpdateGui(true); break; } } /// <summary> /// Removes all matches of the given regex. /// This is used for filtering textboxes on TextChanged events. /// </summary> private string ApplyFilter(string text, string filter) { if (filter != "" && filter != null && text != "" && text != null) { MatchCollection matches = Regex.Matches(text, filter); foreach (Match match in matches) { text = text.Replace(match.Value, ""); } } return text; } /// <summary> /// Displays a simple dialog with helpful information about formatting. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void bttnHelp_Click(object sender, RoutedEventArgs e) { CASimAbout aboutDlg = new CASimAbout(); aboutDlg.Show(); } } }
33.747059
87
0.517082
[ "MIT" ]
JoshuaLamusga/CA-Sim
CASim/CASimLauncher.xaml.cs
11,476
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; namespace Aliyun.Acs.Slb.Model.V20140515 { public class SetRuleResponse : AcsResponse { } }
35.692308
63
0.751078
[ "Apache-2.0" ]
VAllens/aliyun-openapi-sdk-net-core
src/aliyun-net-sdk-slb/Model/V20140515/SetRuleResponse.cs
928
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. /*============================================================ ** ** ** ** Purpose: Attributes for debugger ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; namespace System.Diagnostics { // DebuggerBrowsableState states are defined as follows: // Never never show this element // Expanded expansion of the class is done, so that all visible internal members are shown // Collapsed expansion of the class is not performed. Internal visible members are hidden // RootHidden The target element itself should not be shown, but should instead be // automatically expanded to have its members displayed. // Default value is collapsed // Please also change the code which validates DebuggerBrowsableState variable (in this file) // if you change this enum. [ComVisible(true)] public enum DebuggerBrowsableState { Never = 0, //Expanded is not supported in this release //Expanded = 1, Collapsed = 2, RootHidden = 3 } // the one currently supported with the csee.dat // (mcee.dat, autoexp.dat) file. [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] [ComVisible(true)] public sealed class DebuggerBrowsableAttribute : Attribute { private readonly DebuggerBrowsableState _state; public DebuggerBrowsableAttribute(DebuggerBrowsableState state) { if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden) throw new ArgumentOutOfRangeException(nameof(state)); _state = state; } public DebuggerBrowsableState State { get { return _state; } } } // DebuggerTypeProxyAttribute [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] [ComVisible(true)] public sealed class DebuggerTypeProxyAttribute : Attribute { private readonly string _typeName; private string _targetName; private Type _target; public DebuggerTypeProxyAttribute(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } _typeName = type.AssemblyQualifiedName; } public DebuggerTypeProxyAttribute(string typeName) { _typeName = typeName; } public string ProxyTypeName { get { return _typeName; } } public Type Target { set { if (value == null) throw new ArgumentNullException(nameof(value)); _targetName = value.AssemblyQualifiedName; _target = value; } get { return _target; } } public string TargetTypeName { get { return _targetName; } set { _targetName = value; } } } // This attribute is used to control what is displayed for the given class or field // in the data windows in the debugger. The single argument to this attribute is // the string that will be displayed in the value column for instances of the type. // This string can include text between { and } which can be either a field, // property or method (as will be documented in mscorlib). In the C# case, // a general expression will be allowed which only has implicit access to the this pointer // for the current instance of the target type. The expression will be limited, // however: there is no access to aliases, locals, or pointers. // In addition, attributes on properties referenced in the expression are not processed. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)] [ComVisible(true)] public sealed class DebuggerDisplayAttribute : Attribute { private string _name; private readonly string _value; private string _type; private string _targetName; private Type _target; public DebuggerDisplayAttribute(string value) { if (value == null) { _value = ""; } else { _value = value; } _name = ""; _type = ""; } public string Value { get { return _value; } } public string Name { get { return _name; } set { _name = value; } } public string Type { get { return _type; } set { _type = value; } } public Type Target { set { if (value == null) throw new ArgumentNullException(nameof(value)); _targetName = value.AssemblyQualifiedName; _target = value; } get { return _target; } } public string TargetTypeName { get { return _targetName; } set { _targetName = value; } } } }
30.913043
225
0.581048
[ "Apache-2.0" ]
WindowsCE/NETStandard.WindowsCE
src/NETStandard.WindowsCE/Diagnostics/DebuggerAttributes.cs
5,690
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 cloudfront-2016-11-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// The returned result of the corresponding request. /// </summary> public partial class CreateStreamingDistributionResponse : AmazonWebServiceResponse { private string _eTag; private string _location; private StreamingDistribution _streamingDistribution; /// <summary> /// Gets and sets the property ETag. /// <para> /// The current version of the streaming distribution created. /// </para> /// </summary> public string ETag { get { return this._eTag; } set { this._eTag = value; } } // Check to see if ETag property is set internal bool IsSetETag() { return this._eTag != null; } /// <summary> /// Gets and sets the property Location. /// <para> /// The fully qualified URI of the new streaming distribution resource just created. For /// example: <code>https://cloudfront.amazonaws.com/2010-11-01/streaming-distribution/EGTXBD79H29TRA8</code>. /// </para> /// </summary> public string Location { get { return this._location; } set { this._location = value; } } // Check to see if Location property is set internal bool IsSetLocation() { return this._location != null; } /// <summary> /// Gets and sets the property StreamingDistribution. /// <para> /// The streaming distribution's information. /// </para> /// </summary> public StreamingDistribution StreamingDistribution { get { return this._streamingDistribution; } set { this._streamingDistribution = value; } } // Check to see if StreamingDistribution property is set internal bool IsSetStreamingDistribution() { return this._streamingDistribution != null; } } }
30.884211
117
0.618609
[ "Apache-2.0" ]
miltador-forks/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/CreateStreamingDistributionResponse.cs
2,934
C#
namespace Xilium.CefGlue.Interop { using System; using System.Runtime.InteropServices; using System.Security; #if !DEBUG [SuppressUnmanagedCodeSecurity] #endif internal static unsafe partial class libcef { internal const string DllName = "libcef"; internal const int ALIGN = 0; internal const CallingConvention CEF_CALL = CallingConvention.Cdecl; // Windows: CallingConvention.StdCall // Unix: CallingConvention.Cdecl // FIXME: CEF#598 (http://code.google.com/p/chromiumembedded/issues/detail?id=598) internal const CallingConvention CEF_CALLBACK = CallingConvention.Winapi; #region cef_version.h [DllImport(libcef.DllName, EntryPoint = "cef_build_revision", CallingConvention = libcef.CEF_CALL)] public static extern int build_revision(); [DllImport(libcef.DllName, EntryPoint = "cef_version_info", CallingConvention = libcef.CEF_CALL)] public static extern int version_info(int entry); [DllImport(libcef.DllName, EntryPoint = "cef_api_hash", CallingConvention = libcef.CEF_CALL)] public static extern sbyte* api_hash(int entry); #endregion } }
32.621622
107
0.700911
[ "MIT" ]
git-thinh/Xilium.CefGlue-lvcef-39.0
xilium.cefglue/CefGlue/Interop/libcef.cs
1,207
C#
using System.Collections.Generic; using MediatR; namespace Rehborn.AspNetAutoFacExample.Application.Values.Queries { public class GetAllValuesQuery : IRequest<IEnumerable<ValueDto>> { public bool AddAdditional { get; set; } = true; } }
25.7
68
0.735409
[ "MIT" ]
julre/Rehborn.AspNetAutoFacExample
Rehborn.AspNetAutoFacExample/Application/Values/Queries/GetAllValuesQuery.cs
259
C#
using System; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Collections.Generic; using Python.Runtime.Platform; namespace Python.Runtime { /// <summary> /// Encapsulates the low-level Python C API. Note that it is /// the responsibility of the caller to have acquired the GIL /// before calling any of these methods. /// </summary> public class Runtime { // C# compiler copies constants to the assemblies that references this library. // We needs to replace all public constants to static readonly fields to allow // binary substitution of different Python.Runtime.dll builds in a target application. public static int UCS => _UCS; #if UCS4 internal const int _UCS = 4; /// <summary> /// EntryPoint to be used in DllImport to map to correct Unicode /// methods prior to PEP393. Only used for PY27. /// </summary> private const string PyUnicodeEntryPoint = "PyUnicodeUCS4_"; #elif UCS2 internal const int _UCS = 2; /// <summary> /// EntryPoint to be used in DllImport to map to correct Unicode /// methods prior to PEP393. Only used for PY27. /// </summary> private const string PyUnicodeEntryPoint = "PyUnicodeUCS2_"; #else #error You must define either UCS2 or UCS4! #endif // C# compiler copies constants to the assemblies that references this library. // We needs to replace all public constants to static readonly fields to allow // binary substitution of different Python.Runtime.dll builds in a target application. public static string pyversion => _pyversion; public static string pyver => _pyver; #if PYTHON27 internal const string _pyversion = "2.7"; internal const string _pyver = "27"; #elif PYTHON34 internal const string _pyversion = "3.4"; internal const string _pyver = "34"; #elif PYTHON35 internal const string _pyversion = "3.5"; internal const string _pyver = "35"; #elif PYTHON36 internal const string _pyversion = "3.6"; internal const string _pyver = "36"; #elif PYTHON37 internal const string _pyversion = "3.7"; internal const string _pyver = "37"; #else #error You must define one of PYTHON34 to PYTHON37 or PYTHON27 #endif #if MONO_LINUX || MONO_OSX // Linux/macOS use dotted version string internal const string dllBase = "python" + _pyversion; #else // Windows internal const string dllBase = "python" + _pyver; #endif #if PYTHON_WITH_PYDEBUG internal const string dllWithPyDebug = "d"; #else internal const string dllWithPyDebug = ""; #endif #if PYTHON_WITH_PYMALLOC internal const string dllWithPyMalloc = "m"; #else internal const string dllWithPyMalloc = ""; #endif // C# compiler copies constants to the assemblies that references this library. // We needs to replace all public constants to static readonly fields to allow // binary substitution of different Python.Runtime.dll builds in a target application. public static readonly string PythonDLL = _PythonDll; #if PYTHON_WITHOUT_ENABLE_SHARED && !NETSTANDARD internal const string _PythonDll = "__Internal"; #else internal const string _PythonDll = dllBase + dllWithPyDebug + dllWithPyMalloc; #endif public static readonly int pyversionnumber = Convert.ToInt32(_pyver); // set to true when python is finalizing internal static object IsFinalizingLock = new object(); internal static bool IsFinalizing; internal static bool Is32Bit = IntPtr.Size == 4; // .NET core: System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows) internal static bool IsWindows = Environment.OSVersion.Platform == PlatformID.Win32NT; static readonly Dictionary<string, OperatingSystemType> OperatingSystemTypeMapping = new Dictionary<string, OperatingSystemType>() { { "Windows", OperatingSystemType.Windows }, { "Darwin", OperatingSystemType.Darwin }, { "Linux", OperatingSystemType.Linux }, }; /// <summary> /// Gets the operating system as reported by python's platform.system(). /// </summary> public static OperatingSystemType OperatingSystem { get; private set; } /// <summary> /// Gets the operating system as reported by python's platform.system(). /// </summary> public static string OperatingSystemName { get; private set; } /// <summary> /// Map lower-case version of the python machine name to the processor /// type. There are aliases, e.g. x86_64 and amd64 are two names for /// the same thing. Make sure to lower-case the search string, because /// capitalization can differ. /// </summary> static readonly Dictionary<string, MachineType> MachineTypeMapping = new Dictionary<string, MachineType>() { ["i386"] = MachineType.i386, ["i686"] = MachineType.i386, ["x86"] = MachineType.i386, ["x86_64"] = MachineType.x86_64, ["amd64"] = MachineType.x86_64, ["x64"] = MachineType.x86_64, ["em64t"] = MachineType.x86_64, ["armv7l"] = MachineType.armv7l, ["armv8"] = MachineType.armv8, }; /// <summary> /// Gets the machine architecture as reported by python's platform.machine(). /// </summary> public static MachineType Machine { get; private set; }/* set in Initialize using python's platform.machine */ /// <summary> /// Gets the machine architecture as reported by python's platform.machine(). /// </summary> public static string MachineName { get; private set; } internal static bool IsPython2 = pyversionnumber < 30; internal static bool IsPython3 = pyversionnumber >= 30; public static int MainManagedThreadId { get; private set; } /// <summary> /// Encoding to use to convert Unicode to/from Managed to Native /// </summary> internal static readonly Encoding PyEncoding = _UCS == 2 ? Encoding.Unicode : Encoding.UTF32; /// <summary> /// Initialize the runtime... /// </summary> internal static void Initialize(bool initSigs = false) { if (Py_IsInitialized() == 0) { Py_InitializeEx(initSigs ? 1 : 0); MainManagedThreadId = Thread.CurrentThread.ManagedThreadId; } if (PyEval_ThreadsInitialized() == 0) { PyEval_InitThreads(); } IsFinalizing = false; CLRModule.Reset(); GenericUtil.Reset(); PyScopeManager.Reset(); ClassManager.Reset(); ClassDerivedObject.Reset(); TypeManager.Reset(); IntPtr op; IntPtr dict; if (IsPython3) { op = PyImport_ImportModule("builtins"); dict = PyObject_GetAttrString(op, "__dict__"); } else // Python2 { dict = PyImport_GetModuleDict(); op = PyDict_GetItemString(dict, "__builtin__"); } PyNotImplemented = PyObject_GetAttrString(op, "NotImplemented"); PyBaseObjectType = PyObject_GetAttrString(op, "object"); PyNone = PyObject_GetAttrString(op, "None"); PyTrue = PyObject_GetAttrString(op, "True"); PyFalse = PyObject_GetAttrString(op, "False"); PyBoolType = PyObject_Type(PyTrue); PyNoneType = PyObject_Type(PyNone); PyTypeType = PyObject_Type(PyNoneType); op = PyObject_GetAttrString(dict, "keys"); PyMethodType = PyObject_Type(op); XDecref(op); // For some arcane reason, builtins.__dict__.__setitem__ is *not* // a wrapper_descriptor, even though dict.__setitem__ is. // // object.__init__ seems safe, though. op = PyObject_GetAttrString(PyBaseObjectType, "__init__"); PyWrapperDescriptorType = PyObject_Type(op); XDecref(op); #if PYTHON3 XDecref(dict); #endif op = PyString_FromString("string"); PyStringType = PyObject_Type(op); XDecref(op); op = PyUnicode_FromString("unicode"); PyUnicodeType = PyObject_Type(op); XDecref(op); #if PYTHON3 op = PyBytes_FromString("bytes"); PyBytesType = PyObject_Type(op); XDecref(op); #endif op = PyTuple_New(0); PyTupleType = PyObject_Type(op); XDecref(op); op = PyList_New(0); PyListType = PyObject_Type(op); XDecref(op); op = PyDict_New(); PyDictType = PyObject_Type(op); XDecref(op); op = PyInt_FromInt32(0); PyIntType = PyObject_Type(op); XDecref(op); op = PyLong_FromLong(0); PyLongType = PyObject_Type(op); XDecref(op); op = PyFloat_FromDouble(0); PyFloatType = PyObject_Type(op); XDecref(op); #if PYTHON3 PyClassType = IntPtr.Zero; PyInstanceType = IntPtr.Zero; #elif PYTHON2 IntPtr s = PyString_FromString("_temp"); IntPtr d = PyDict_New(); IntPtr c = PyClass_New(IntPtr.Zero, d, s); PyClassType = PyObject_Type(c); IntPtr i = PyInstance_New(c, IntPtr.Zero, IntPtr.Zero); PyInstanceType = PyObject_Type(i); XDecref(s); XDecref(i); XDecref(c); XDecref(d); #endif Error = new IntPtr(-1); // Initialize data about the platform we're running on. We need // this for the type manager and potentially other details. Must // happen after caching the python types, above. InitializePlatformData(); IntPtr dllLocal = IntPtr.Zero; var loader = LibraryLoader.Get(OperatingSystem); if (_PythonDll != "__Internal") { dllLocal = loader.Load(_PythonDll); } _PyObject_NextNotImplemented = loader.GetFunction(dllLocal, "_PyObject_NextNotImplemented"); PyModuleType = loader.GetFunction(dllLocal, "PyModule_Type"); if (dllLocal != IntPtr.Zero) { loader.Free(dllLocal); } // Initialize modules that depend on the runtime class. AssemblyManager.Initialize(); PyCLRMetaType = MetaType.Initialize(); Exceptions.Initialize(); ImportHook.Initialize(); // Need to add the runtime directory to sys.path so that we // can find built-in assemblies like System.Data, et. al. string rtdir = RuntimeEnvironment.GetRuntimeDirectory(); IntPtr path = PySys_GetObject("path"); IntPtr item = PyString_FromString(rtdir); PyList_Append(path, item); XDecref(item); AssemblyManager.UpdatePath(); } /// <summary> /// Initializes the data about platforms. /// /// This must be the last step when initializing the runtime: /// GetManagedString needs to have the cached values for types. /// But it must run before initializing anything outside the runtime /// because those rely on the platform data. /// </summary> private static void InitializePlatformData() { IntPtr op; IntPtr fn; IntPtr platformModule = PyImport_ImportModule("platform"); IntPtr emptyTuple = PyTuple_New(0); fn = PyObject_GetAttrString(platformModule, "system"); op = PyObject_Call(fn, emptyTuple, IntPtr.Zero); OperatingSystemName = GetManagedString(op); XDecref(op); XDecref(fn); fn = PyObject_GetAttrString(platformModule, "machine"); op = PyObject_Call(fn, emptyTuple, IntPtr.Zero); MachineName = GetManagedString(op); XDecref(op); XDecref(fn); XDecref(emptyTuple); XDecref(platformModule); // Now convert the strings into enum values so we can do switch // statements rather than constant parsing. OperatingSystemType OSType; if (!OperatingSystemTypeMapping.TryGetValue(OperatingSystemName, out OSType)) { OSType = OperatingSystemType.Other; } OperatingSystem = OSType; MachineType MType; if (!MachineTypeMapping.TryGetValue(MachineName.ToLower(), out MType)) { MType = MachineType.Other; } Machine = MType; } internal static void Shutdown() { AssemblyManager.Shutdown(); Exceptions.Shutdown(); ImportHook.Shutdown(); Finalizer.Shutdown(); Py_Finalize(); } // called *without* the GIL acquired by clr._AtExit internal static int AtExit() { lock (IsFinalizingLock) { IsFinalizing = true; } return 0; } internal static IntPtr Py_single_input = (IntPtr)256; internal static IntPtr Py_file_input = (IntPtr)257; internal static IntPtr Py_eval_input = (IntPtr)258; internal static IntPtr PyBaseObjectType; internal static IntPtr PyModuleType; internal static IntPtr PyClassType; internal static IntPtr PyInstanceType; internal static IntPtr PyCLRMetaType; internal static IntPtr PyMethodType; internal static IntPtr PyWrapperDescriptorType; internal static IntPtr PyUnicodeType; internal static IntPtr PyStringType; internal static IntPtr PyTupleType; internal static IntPtr PyListType; internal static IntPtr PyDictType; internal static IntPtr PyIntType; internal static IntPtr PyLongType; internal static IntPtr PyFloatType; internal static IntPtr PyBoolType; internal static IntPtr PyNoneType; internal static IntPtr PyTypeType; #if PYTHON3 internal static IntPtr PyBytesType; #endif internal static IntPtr _PyObject_NextNotImplemented; internal static IntPtr PyNotImplemented; internal const int Py_LT = 0; internal const int Py_LE = 1; internal const int Py_EQ = 2; internal const int Py_NE = 3; internal const int Py_GT = 4; internal const int Py_GE = 5; internal static IntPtr PyTrue; internal static IntPtr PyFalse; internal static IntPtr PyNone; internal static IntPtr Error; /// <summary> /// Check if any Python Exceptions occurred. /// If any exist throw new PythonException. /// </summary> /// <remarks> /// Can be used instead of `obj == IntPtr.Zero` for example. /// </remarks> internal static void CheckExceptionOccurred() { if (PyErr_Occurred() != IntPtr.Zero) { throw new PythonException(); } } internal static IntPtr ExtendTuple(IntPtr t, params IntPtr[] args) { var size = PyTuple_Size(t); int add = args.Length; IntPtr item; IntPtr items = PyTuple_New(size + add); for (var i = 0; i < size; i++) { item = PyTuple_GetItem(t, i); XIncref(item); PyTuple_SetItem(items, i, item); } for (var n = 0; n < add; n++) { item = args[n]; XIncref(item); PyTuple_SetItem(items, size + n, item); } return items; } internal static Type[] PythonArgsToTypeArray(IntPtr arg) { return PythonArgsToTypeArray(arg, false); } internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) { // Given a PyObject * that is either a single type object or a // tuple of (managed or unmanaged) type objects, return a Type[] // containing the CLR Type objects that map to those types. IntPtr args = arg; var free = false; if (!PyTuple_Check(arg)) { args = PyTuple_New(1); XIncref(arg); PyTuple_SetItem(args, 0, arg); free = true; } var n = PyTuple_Size(args); var types = new Type[n]; Type t = null; for (var i = 0; i < n; i++) { IntPtr op = PyTuple_GetItem(args, i); if (mangleObjects && (!PyType_Check(op))) { op = PyObject_TYPE(op); } ManagedType mt = ManagedType.GetManagedObject(op); if (mt is ClassBase) { t = ((ClassBase)mt).type; } else if (mt is CLRObject) { object inst = ((CLRObject)mt).inst; if (inst is Type) { t = inst as Type; } } else { t = Converter.GetTypeByAlias(op); } if (t == null) { types = null; break; } types[i] = t; } if (free) { XDecref(args); } return types; } /// <summary> /// Managed exports of the Python C API. Where appropriate, we do /// some optimization to avoid managed &lt;--&gt; unmanaged transitions /// (mostly for heavily used methods). /// </summary> internal static unsafe void XIncref(IntPtr op) { #if PYTHON_WITH_PYDEBUG || NETSTANDARD Py_IncRef(op); return; #else var p = (void*)op; if ((void*)0 != p) { if (Is32Bit) { (*(int*)p)++; } else { (*(long*)p)++; } } #endif } internal static unsafe void XDecref(IntPtr op) { #if PYTHON_WITH_PYDEBUG || NETSTANDARD Py_DecRef(op); return; #else var p = (void*)op; if ((void*)0 != p) { if (Is32Bit) { --(*(int*)p); } else { --(*(long*)p); } if ((*(int*)p) == 0) { // PyObject_HEAD: struct _typeobject *ob_type void* t = Is32Bit ? (void*)(*((uint*)p + 1)) : (void*)(*((ulong*)p + 1)); // PyTypeObject: destructor tp_dealloc void* f = Is32Bit ? (void*)(*((uint*)t + 6)) : (void*)(*((ulong*)t + 6)); if ((void*)0 == f) { return; } NativeCall.Impl.Void_Call_1(new IntPtr(f), op); } } #endif } internal static unsafe long Refcount(IntPtr op) { var p = (void*)op; if ((void*)0 == p) { return 0; } return Is32Bit ? (*(int*)p) : (*(long*)p); } /// <summary> /// Export of Macro Py_XIncRef. Use XIncref instead. /// Limit this function usage for Testing and Py_Debug builds /// </summary> /// <param name="ob">PyObject Ptr</param> [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_IncRef(IntPtr ob); /// <summary> /// Export of Macro Py_XDecRef. Use XDecref instead. /// Limit this function usage for Testing and Py_Debug builds /// </summary> /// <param name="ob">PyObject Ptr</param> [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_DecRef(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_Initialize(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_InitializeEx(int initsigs); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int Py_IsInitialized(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_Finalize(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_NewInterpreter(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_EndInterpreter(IntPtr threadState); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyThreadState_New(IntPtr istate); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyThreadState_Get(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyThread_get_key_value(IntPtr key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyThread_get_thread_ident(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyThread_set_key_value(IntPtr key, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyThreadState_Swap(IntPtr key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyGILState_Ensure(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyGILState_Release(IntPtr gs); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyGILState_GetThisThreadState(); #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] public static extern int Py_Main( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv ); #elif PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] public static extern int Py_Main(int argc, string[] argv); #endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyEval_InitThreads(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyEval_ThreadsInitialized(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyEval_AcquireLock(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyEval_ReleaseLock(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyEval_AcquireThread(IntPtr tstate); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyEval_ReleaseThread(IntPtr tstate); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyEval_SaveThread(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyEval_RestoreThread(IntPtr tstate); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyEval_GetBuiltins(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyEval_GetGlobals(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyEval_GetLocals(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetProgramName(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_SetProgramName(IntPtr name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetPythonHome(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_SetPythonHome(IntPtr home); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetPath(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void Py_SetPath(IntPtr home); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetVersion(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetPlatform(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetCopyright(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetCompiler(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_GetBuildInfo(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyRun_SimpleString(string code); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyEval_EvalCode(IntPtr co, IntPtr globals, IntPtr locals); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Py_CompileString(string code, string file, IntPtr tok); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw); #if PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name); #endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls); //==================================================================== // Python abstract object API //==================================================================== /// <summary> /// A macro-like method to get the type of a Python object. This is /// designed to be lean and mean in IL &amp; avoid managed &lt;-&gt; unmanaged /// transitions. Note that this does not incref the type object. /// </summary> internal static unsafe IntPtr PyObject_TYPE(IntPtr op) { var p = (void*)op; if ((void*)0 == p) { return IntPtr.Zero; } #if PYTHON_WITH_PYDEBUG var n = 3; #else var n = 1; #endif return Is32Bit ? new IntPtr((void*)(*((uint*)p + n))) : new IntPtr((void*)(*((ulong*)p + n))); } /// <summary> /// Managed version of the standard Python C API PyObject_Type call. /// This version avoids a managed &lt;-&gt; unmanaged transition. /// This one does incref the returned type object. /// </summary> internal static IntPtr PyObject_Type(IntPtr op) { IntPtr tp = PyObject_TYPE(op); XIncref(tp); return tp; } internal static string PyObject_GetTypeName(IntPtr op) { IntPtr pyType = Marshal.ReadIntPtr(op, ObjectOffset.ob_type); IntPtr ppName = Marshal.ReadIntPtr(pyType, TypeOffset.tp_name); return Marshal.PtrToStringAnsi(ppName); } /// <summary> /// Test whether the Python object is an iterable. /// </summary> internal static bool PyObject_IsIterable(IntPtr pointer) { var ob_type = Marshal.ReadIntPtr(pointer, ObjectOffset.ob_type); #if PYTHON2 long tp_flags = Util.ReadCLong(ob_type, TypeOffset.tp_flags); if ((tp_flags & TypeFlags.HaveIter) == 0) return false; #endif IntPtr tp_iter = Marshal.ReadIntPtr(ob_type, TypeOffset.tp_iter); return tp_iter != IntPtr.Zero; } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_HasAttrString(IntPtr pointer, string name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_DelItem(IntPtr pointer, IntPtr key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_GetIter(IntPtr op); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args); #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid); internal static int PyObject_Compare(IntPtr value1, IntPtr value2) { int res; res = PyObject_RichCompareBool(value1, value2, Py_LT); if (-1 == res) return -1; else if (1 == res) return -1; res = PyObject_RichCompareBool(value1, value2, Py_EQ); if (-1 == res) return -1; else if (1 == res) return 0; res = PyObject_RichCompareBool(value1, value2, Py_GT); if (-1 == res) return -1; else if (1 == res) return 1; Exceptions.SetError(Exceptions.SystemError, "Error comparing objects"); return -1; } #elif PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_Compare(IntPtr value1, IntPtr value2); #endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_IsInstance(IntPtr ob, IntPtr type); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyCallable_Check(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_IsTrue(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_Not(IntPtr pointer); internal static long PyObject_Size(IntPtr pointer) { return (long) _PyObject_Size(pointer); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyObject_Size")] private static extern IntPtr _PyObject_Size(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Hash(IntPtr op); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Repr(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Str(IntPtr pointer); #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyObject_Str")] internal static extern IntPtr PyObject_Unicode(IntPtr pointer); #elif PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Unicode(IntPtr pointer); #endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_Dir(IntPtr pointer); //==================================================================== // Python number API //==================================================================== #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyNumber_Long")] internal static extern IntPtr PyNumber_Int(IntPtr ob); #elif PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Int(IntPtr ob); #endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Long(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Float(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern bool PyNumber_Check(IntPtr ob); internal static bool PyInt_Check(IntPtr ob) { return PyObject_TypeCheck(ob, PyIntType); } internal static bool PyBool_Check(IntPtr ob) { return PyObject_TypeCheck(ob, PyBoolType); } internal static IntPtr PyInt_FromInt32(int value) { var v = new IntPtr(value); return PyInt_FromLong(v); } internal static IntPtr PyInt_FromInt64(long value) { var v = new IntPtr(value); return PyInt_FromLong(v); } #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromLong")] private static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_AsLong")] internal static extern int PyInt_AsLong(IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromString")] internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); #elif PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyInt_FromLong(IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyInt_AsLong(IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyInt_GetMax(); #endif internal static bool PyLong_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyLongType; } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyLong_FromLong(long value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromUnsignedLong")] internal static extern IntPtr PyLong_FromUnsignedLong32(uint value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_FromUnsignedLong")] internal static extern IntPtr PyLong_FromUnsignedLong64(ulong value); internal static IntPtr PyLong_FromUnsignedLong(object value) { if(Is32Bit || IsWindows) return PyLong_FromUnsignedLong32(Convert.ToUInt32(value)); else return PyLong_FromUnsignedLong64(Convert.ToUInt64(value)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyLong_FromDouble(double value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyLong_FromLongLong(long value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyLong_FromUnsignedLongLong(ulong value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyLong_AsLong(IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_AsUnsignedLong")] internal static extern uint PyLong_AsUnsignedLong32(IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyLong_AsUnsignedLong")] internal static extern ulong PyLong_AsUnsignedLong64(IntPtr value); internal static object PyLong_AsUnsignedLong(IntPtr value) { if (Is32Bit || IsWindows) return PyLong_AsUnsignedLong32(value); else return PyLong_AsUnsignedLong64(value); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern long PyLong_AsLongLong(IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern ulong PyLong_AsUnsignedLongLong(IntPtr value); internal static bool PyFloat_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyFloatType; } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyFloat_FromDouble(double value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern double PyFloat_AsDouble(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_TrueDivide(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceTrueDivide(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Negative(IntPtr o1); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Positive(IntPtr o1); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyNumber_Invert(IntPtr o1); //==================================================================== // Python sequence API //==================================================================== [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern bool PySequence_Check(IntPtr pointer); internal static IntPtr PySequence_GetItem(IntPtr pointer, long index) { return PySequence_GetItem(pointer, new IntPtr(index)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PySequence_GetItem(IntPtr pointer, IntPtr index); internal static int PySequence_SetItem(IntPtr pointer, long index, IntPtr value) { return PySequence_SetItem(pointer, new IntPtr(index), value); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PySequence_SetItem(IntPtr pointer, IntPtr index, IntPtr value); internal static int PySequence_DelItem(IntPtr pointer, long index) { return PySequence_DelItem(pointer, new IntPtr(index)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PySequence_DelItem(IntPtr pointer, IntPtr index); internal static IntPtr PySequence_GetSlice(IntPtr pointer, long i1, long i2) { return PySequence_GetSlice(pointer, new IntPtr(i1), new IntPtr(i2)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PySequence_GetSlice(IntPtr pointer, IntPtr i1, IntPtr i2); internal static int PySequence_SetSlice(IntPtr pointer, long i1, long i2, IntPtr v) { return PySequence_SetSlice(pointer, new IntPtr(i1), new IntPtr(i2), v); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PySequence_SetSlice(IntPtr pointer, IntPtr i1, IntPtr i2, IntPtr v); internal static int PySequence_DelSlice(IntPtr pointer, long i1, long i2) { return PySequence_DelSlice(pointer, new IntPtr(i1), new IntPtr(i2)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PySequence_DelSlice(IntPtr pointer, IntPtr i1, IntPtr i2); internal static long PySequence_Size(IntPtr pointer) { return (long) _PySequence_Size(pointer); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PySequence_Size")] private static extern IntPtr _PySequence_Size(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PySequence_Contains(IntPtr pointer, IntPtr item); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other); internal static IntPtr PySequence_Repeat(IntPtr pointer, long count) { return PySequence_Repeat(pointer, new IntPtr(count)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PySequence_Repeat(IntPtr pointer, IntPtr count); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PySequence_Index(IntPtr pointer, IntPtr item); internal static long PySequence_Count(IntPtr pointer, IntPtr value) { return (long) _PySequence_Count(pointer, value); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PySequence_Count")] private static extern IntPtr _PySequence_Count(IntPtr pointer, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PySequence_Tuple(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PySequence_List(IntPtr pointer); //==================================================================== // Python string API //==================================================================== internal static bool IsStringType(IntPtr op) { IntPtr t = PyObject_TYPE(op); return (t == PyStringType) || (t == PyUnicodeType); } internal static bool PyString_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyStringType; } internal static IntPtr PyString_FromString(string value) { #if PYTHON3 return PyUnicode_FromKindAndData(_UCS, value, value.Length); #elif PYTHON2 return PyString_FromStringAndSize(value, value.Length); #endif } #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyBytes_FromString(string op); internal static long PyBytes_Size(IntPtr op) { return (long) _PyBytes_Size(op); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyBytes_Size")] private static extern IntPtr _PyBytes_Size(IntPtr op); internal static IntPtr PyBytes_AS_STRING(IntPtr ob) { return ob + BytesOffset.ob_sval; } internal static IntPtr PyString_FromStringAndSize(string value, long size) { return _PyString_FromStringAndSize(value, new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicode_FromStringAndSize")] internal static extern IntPtr _PyString_FromStringAndSize( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8Marshaler))] string value, IntPtr size ); internal static IntPtr PyUnicode_FromStringAndSize(IntPtr value, long size) { return PyUnicode_FromStringAndSize(value, new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, IntPtr size); #elif PYTHON2 internal static IntPtr PyString_FromStringAndSize(string value, long size) { return PyString_FromStringAndSize(value, new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyString_FromStringAndSize(string value, IntPtr size); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyString_AsString(IntPtr op); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyString_Size(IntPtr pointer); #endif internal static bool PyUnicode_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyUnicodeType; } #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); internal static IntPtr PyUnicode_FromKindAndData(int kind, string s, long size) { return PyUnicode_FromKindAndData(kind, s, new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyUnicode_FromKindAndData( int kind, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UcsMarshaler))] string s, IntPtr size ); internal static IntPtr PyUnicode_FromUnicode(string s, long size) { return PyUnicode_FromKindAndData(_UCS, s, size); } internal static long PyUnicode_GetSize(IntPtr ob) { return (long)_PyUnicode_GetSize(ob); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyUnicode_GetSize")] private static extern IntPtr _PyUnicode_GetSize(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyUnicode_FromOrdinal(int c); #elif PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = PyUnicodeEntryPoint + "FromObject")] internal static extern IntPtr PyUnicode_FromObject(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = PyUnicodeEntryPoint + "FromEncodedObject")] internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err); internal static IntPtr PyUnicode_FromUnicode(string s, long size) { return PyUnicode_FromUnicode(s, new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = PyUnicodeEntryPoint + "FromUnicode")] private static extern IntPtr PyUnicode_FromUnicode( [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UcsMarshaler))] string s, IntPtr size ); internal static long PyUnicode_GetSize(IntPtr ob) { return (long) _PyUnicode_GetSize(ob); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = PyUnicodeEntryPoint + "GetSize")] internal static extern IntPtr _PyUnicode_GetSize(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = PyUnicodeEntryPoint + "AsUnicode")] internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = PyUnicodeEntryPoint + "FromOrdinal")] internal static extern IntPtr PyUnicode_FromOrdinal(int c); #endif internal static IntPtr PyUnicode_FromString(string s) { return PyUnicode_FromUnicode(s, s.Length); } /// <summary> /// Function to access the internal PyUnicode/PyString object and /// convert it to a managed string with the correct encoding. /// </summary> /// <remarks> /// We can't easily do this through through the CustomMarshaler's on /// the returns because will have access to the IntPtr but not size. /// <para /> /// For PyUnicodeType, we can't convert with Marshal.PtrToStringUni /// since it only works for UCS2. /// </remarks> /// <param name="op">PyStringType or PyUnicodeType object to convert</param> /// <returns>Managed String</returns> internal static string GetManagedString(IntPtr op) { IntPtr type = PyObject_TYPE(op); #if PYTHON2 // Python 3 strings are all Unicode if (type == PyStringType) { return Marshal.PtrToStringAnsi(PyString_AsString(op), PyString_Size(op)); } #endif if (type == PyUnicodeType) { IntPtr p = PyUnicode_AsUnicode(op); int length = (int)PyUnicode_GetSize(op); int size = length * _UCS; var buffer = new byte[size]; Marshal.Copy(p, buffer, 0, size); return PyEncoding.GetString(buffer, 0, size); } return null; } //==================================================================== // Python dictionary API //==================================================================== internal static bool PyDict_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyDictType; } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDict_New(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDictProxy_New(IntPtr dict); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyDict_DelItem(IntPtr pointer, IntPtr key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyDict_DelItemString(IntPtr pointer, string key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDict_Keys(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDict_Values(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDict_Items(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyDict_Copy(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyDict_Update(IntPtr pointer, IntPtr other); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyDict_Clear(IntPtr pointer); internal static long PyDict_Size(IntPtr pointer) { return (long) _PyDict_Size(pointer); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyDict_Size")] internal static extern IntPtr _PyDict_Size(IntPtr pointer); //==================================================================== // Python list API //==================================================================== internal static bool PyList_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyListType; } internal static IntPtr PyList_New(long size) { return PyList_New(new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyList_New(IntPtr size); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyList_AsTuple(IntPtr pointer); internal static IntPtr PyList_GetItem(IntPtr pointer, long index) { return PyList_GetItem(pointer, new IntPtr(index)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyList_GetItem(IntPtr pointer, IntPtr index); internal static int PyList_SetItem(IntPtr pointer, long index, IntPtr value) { return PyList_SetItem(pointer, new IntPtr(index), value); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PyList_SetItem(IntPtr pointer, IntPtr index, IntPtr value); internal static int PyList_Insert(IntPtr pointer, long index, IntPtr value) { return PyList_Insert(pointer, new IntPtr(index), value); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PyList_Insert(IntPtr pointer, IntPtr index, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyList_Append(IntPtr pointer, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyList_Reverse(IntPtr pointer); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyList_Sort(IntPtr pointer); internal static IntPtr PyList_GetSlice(IntPtr pointer, long start, long end) { return PyList_GetSlice(pointer, new IntPtr(start), new IntPtr(end)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyList_GetSlice(IntPtr pointer, IntPtr start, IntPtr end); internal static int PyList_SetSlice(IntPtr pointer, long start, long end, IntPtr value) { return PyList_SetSlice(pointer, new IntPtr(start), new IntPtr(end), value); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PyList_SetSlice(IntPtr pointer, IntPtr start, IntPtr end, IntPtr value); internal static long PyList_Size(IntPtr pointer) { return (long) _PyList_Size(pointer); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyList_Size")] private static extern IntPtr _PyList_Size(IntPtr pointer); //==================================================================== // Python tuple API //==================================================================== internal static bool PyTuple_Check(IntPtr ob) { return PyObject_TYPE(ob) == PyTupleType; } internal static IntPtr PyTuple_New(long size) { return PyTuple_New(new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyTuple_New(IntPtr size); internal static IntPtr PyTuple_GetItem(IntPtr pointer, long index) { return PyTuple_GetItem(pointer, new IntPtr(index)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyTuple_GetItem(IntPtr pointer, IntPtr index); internal static int PyTuple_SetItem(IntPtr pointer, long index, IntPtr value) { return PyTuple_SetItem(pointer, new IntPtr(index), value); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern int PyTuple_SetItem(IntPtr pointer, IntPtr index, IntPtr value); internal static IntPtr PyTuple_GetSlice(IntPtr pointer, long start, long end) { return PyTuple_GetSlice(pointer, new IntPtr(start), new IntPtr(end)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyTuple_GetSlice(IntPtr pointer, IntPtr start, IntPtr end); internal static long PyTuple_Size(IntPtr pointer) { return (long) _PyTuple_Size(pointer); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "PyTuple_Size")] private static extern IntPtr _PyTuple_Size(IntPtr pointer); //==================================================================== // Python iterator API //==================================================================== internal static bool PyIter_Check(IntPtr pointer) { var ob_type = Marshal.ReadIntPtr(pointer, ObjectOffset.ob_type); #if PYTHON2 long tp_flags = Util.ReadCLong(ob_type, TypeOffset.tp_flags); if ((tp_flags & TypeFlags.HaveIter) == 0) return false; #endif IntPtr tp_iternext = Marshal.ReadIntPtr(ob_type, TypeOffset.tp_iternext); return tp_iternext != IntPtr.Zero && tp_iternext != _PyObject_NextNotImplemented; } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyIter_Next(IntPtr pointer); //==================================================================== // Python module API //==================================================================== [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyModule_New(string name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern string PyModule_GetName(IntPtr module); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyModule_GetDict(IntPtr module); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern string PyModule_GetFilename(IntPtr module); #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyModule_Create2(IntPtr module, int apiver); #endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_Import(IntPtr name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_ImportModule(string name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_ReloadModule(IntPtr module); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_AddModule(string name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyImport_GetModuleDict(); #if PYTHON3 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PySys_SetArgvEx( int argc, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv, int updatepath ); #elif PYTHON2 [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PySys_SetArgvEx( int argc, string[] argv, int updatepath ); #endif [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PySys_GetObject(string name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PySys_SetObject(string name, IntPtr ob); //==================================================================== // Python type object API //==================================================================== internal static bool PyType_Check(IntPtr ob) { return PyObject_TypeCheck(ob, PyTypeType); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyType_Modified(IntPtr type); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2); internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) { IntPtr t = PyObject_TYPE(ob); return (t == tp) || PyType_IsSubtype(t, tp); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw); internal static IntPtr PyType_GenericAlloc(IntPtr type, long n) { return PyType_GenericAlloc(type, new IntPtr(n)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyType_GenericAlloc(IntPtr type, IntPtr n); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyType_Ready(IntPtr type); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr _PyObject_GetDictPtr(IntPtr obj); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyObject_GC_New(IntPtr tp); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyObject_GC_Del(IntPtr tp); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyObject_GC_Track(IntPtr tp); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyObject_GC_UnTrack(IntPtr tp); //==================================================================== // Python memory API //==================================================================== internal static IntPtr PyMem_Malloc(long size) { return PyMem_Malloc(new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyMem_Malloc(IntPtr size); internal static IntPtr PyMem_Realloc(IntPtr ptr, long size) { return PyMem_Realloc(ptr, new IntPtr(size)); } [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr PyMem_Realloc(IntPtr ptr, IntPtr size); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyMem_Free(IntPtr ptr); //==================================================================== // Python exception API //==================================================================== [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_SetString(IntPtr ob, string message); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_SetObject(IntPtr ob, IntPtr message); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyErr_SetFromErrno(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_SetNone(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyErr_ExceptionMatches(IntPtr exception); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyErr_Occurred(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_Clear(); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern void PyErr_Print(); //==================================================================== // Miscellaneous //==================================================================== [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyMethod_Self(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr PyMethod_Function(IntPtr ob); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int Py_AddPendingCall(IntPtr func, IntPtr arg); [DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)] internal static extern int Py_MakePendingCalls(); } }
40.15352
138
0.638167
[ "MIT" ]
SnGmng/pythonnet
src/runtime/runtime.cs
75,850
C#
using Microsoft.Extensions.Logging; using NLog; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NLogSampleDI { public class Runner { private readonly ILogger<Runner> _logger; public Runner(ILogger<Runner> logger) { _logger = logger; } public void DoAction(string name) { _logger.LogInformation(20, "Doing hard work! {Action}", name); _logger.LogTrace("trace"); _logger.LogDebug("debug"); _logger.LogError("error"); } } }
20.419355
74
0.609795
[ "MIT" ]
yohskeey/CSConsoleLoggerExample
NLogSampleDI/Runner.cs
635
C#
using Terraria; using Terraria.ModLoader; namespace ExampleMod.Dusts { public class Negative : ModDust { public override void OnSpawn(Dust dust) { dust.noGravity = true; } } }
15.5
43
0.725806
[ "MIT" ]
13784884462/tML1.4
ExampleMod/Old/Dusts/Negative.cs
186
C#
#region Apapche License 2.0 // <copyright file="IXmlClassMap.cs" company="Edgerunner.org"> // Copyright 2015 Thaddeus Ryker // 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. // </copyright> #endregion using System; namespace Org.Edgerunner.DotSerialize.Mapping { public interface IXmlClassMap<T> { XmlClassMap<T> Named(string name); XmlClassMap<T> WithNamespace(string @namespace); } }
35.884615
76
0.724544
[ "Apache-2.0" ]
wiredwiz/DotSerialize
Mapping/IXmlClassMap.cs
933
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Logging.StructuredLogger; using Microsoft.Language.Xml; using StructuredLogViewer.Core.ProjectGraph; namespace StructuredLogViewer.Controls { public partial class BuildControl : UserControl { public Build Build { get; set; } public TreeViewItem SelectedTreeViewItem { get; private set; } public string LogFilePath => Build?.LogFilePath; private ScrollViewer scrollViewer; private SourceFileResolver sourceFileResolver; private ArchiveFileResolver archiveFile => sourceFileResolver.ArchiveFile; private PreprocessedFileManager preprocessedFileManager; private NavigationHelper navigationHelper; private MenuItem copyItem; private MenuItem copySubtreeItem; private MenuItem viewSubtreeTextItem; private MenuItem searchInSubtreeItem; private MenuItem excludeSubtreeFromSearchItem; private MenuItem goToTimeLineItem; private MenuItem copyChildrenItem; private MenuItem sortChildrenItem; private MenuItem copyNameItem; private MenuItem copyValueItem; private MenuItem viewSourceItem; private MenuItem viewFullTextItem; private MenuItem openFileItem; private MenuItem copyFilePathItem; private MenuItem preprocessItem; private MenuItem runItem; private MenuItem debugItem; private MenuItem hideItem; private MenuItem copyAllItem; private MenuItem showTimeItem; private ContextMenu sharedTreeContextMenu; private ContextMenu filesTreeContextMenu; public TreeView ActiveTreeView; private PropertiesAndItemsSearch propertiesAndItemsSearch; public BuildControl(Build build, string logFilePath) { InitializeComponent(); UpdateWatermark(); searchLogControl.ExecuteSearch = (searchText, maxResults, cancellationToken) => { var search = new Search( new[] { Build }, Build.StringTable.Instances, maxResults, SettingsService.MarkResultsInTree //, Build.StringTable // disable validation in production ); var results = search.FindNodes(searchText, cancellationToken); return results; }; searchLogControl.ResultsTreeBuilder = BuildResultTree; searchLogControl.WatermarkDisplayed += () => { Search.ClearSearchResults(Build, SettingsService.MarkResultsInTree); UpdateWatermark(); }; propertiesAndItemsSearch = new PropertiesAndItemsSearch(); propertiesAndItemsControl.ExecuteSearch = (searchText, maxResults, cancellationToken) => { var context = GetProjectContext() as TimedNode; if (context == null) { return null; } var results = propertiesAndItemsSearch.Search( context, searchText, maxResults, SettingsService.MarkResultsInTree, cancellationToken); return results; }; propertiesAndItemsControl.ResultsTreeBuilder = BuildResultTree; UpdatePropertiesAndItemsWatermark(); propertiesAndItemsControl.WatermarkDisplayed += () => { UpdatePropertiesAndItemsWatermark(); }; propertiesAndItemsControl.RecentItemsCategory = "PropertiesAndItems"; SetProjectContext(null); VirtualizingPanel.SetIsVirtualizing(treeView, SettingsService.EnableTreeViewVirtualization); DataContext = build; Build = build; if (build.SourceFilesArchive != null) { // first try to see if the source archive was embedded in the log sourceFileResolver = new SourceFileResolver(build.SourceFiles.Values); } else { // otherwise try to read from the .zip file on disk if present sourceFileResolver = new SourceFileResolver(logFilePath); } if (Build.Statistics.TimedNodeCount > 1000) { projectGraphTab.Visibility = Visibility.Collapsed; } sharedTreeContextMenu = new ContextMenu(); copyAllItem = new MenuItem() { Header = "Copy All" }; copyAllItem.Click += (s, a) => CopyAll(); sharedTreeContextMenu.Items.Add(copyAllItem); filesTreeContextMenu = new ContextMenu(); var filesCopyAll = new MenuItem { Header = "Copy All" }; filesCopyAll.Click += (s, a) => CopyAll(filesTree.ResultsList); var filesCopyPaths = new MenuItem { Header = "Copy file paths" }; filesCopyPaths.Click += (s, a) => CopyPaths(filesTree.ResultsList); filesTreeContextMenu.Items.Add(filesCopyAll); filesTreeContextMenu.Items.Add(filesCopyPaths); var contextMenu = new ContextMenu(); contextMenu.Opened += ContextMenu_Opened; copyItem = new MenuItem() { Header = "Copy" }; copySubtreeItem = new MenuItem() { Header = "Copy subtree" }; viewSubtreeTextItem = new MenuItem() { Header = "View subtree text" }; searchInSubtreeItem = new MenuItem() { Header = "Search in subtree" }; excludeSubtreeFromSearchItem = new MenuItem() { Header = "Exclude subtree from search" }; goToTimeLineItem = new MenuItem() { Header = "Go to timeline" }; copyChildrenItem = new MenuItem() { Header = "Copy children" }; sortChildrenItem = new MenuItem() { Header = "Sort children" }; copyNameItem = new MenuItem() { Header = "Copy name" }; copyValueItem = new MenuItem() { Header = "Copy value" }; viewSourceItem = new MenuItem() { Header = "View source" }; viewFullTextItem = new MenuItem { Header = "View full text" }; showTimeItem = new MenuItem() { Header = "Show time and duration" }; openFileItem = new MenuItem() { Header = "Open File" }; copyFilePathItem = new MenuItem() { Header = "Copy file path" }; preprocessItem = new MenuItem() { Header = "Preprocess" }; hideItem = new MenuItem() { Header = "Hide" }; runItem = new MenuItem() { Header = "Run" }; debugItem = new MenuItem() { Header = "Debug" }; copyItem.Click += (s, a) => Copy(); copySubtreeItem.Click += (s, a) => CopySubtree(); viewSubtreeTextItem.Click += (s, a) => ViewSubtreeText(); searchInSubtreeItem.Click += (s, a) => SearchInSubtree(); excludeSubtreeFromSearchItem.Click += (s, a) => ExcludeSubtreeFromSearch(); goToTimeLineItem.Click += (s, a) => GoToTimeLine(); copyChildrenItem.Click += (s, a) => CopyChildren(); sortChildrenItem.Click += (s, a) => SortChildren(); copyNameItem.Click += (s, a) => CopyName(); copyValueItem.Click += (s, a) => CopyValue(); viewSourceItem.Click += (s, a) => Invoke(treeView.SelectedItem as BaseNode); viewFullTextItem.Click += (s, a) => ViewFullText(treeView.SelectedItem as BaseNode); showTimeItem.Click += (s, a) => ShowTimeAndDuration(); openFileItem.Click += (s, a) => OpenFile(); copyFilePathItem.Click += (s, a) => CopyFilePath(); preprocessItem.Click += (s, a) => Preprocess(treeView.SelectedItem as IPreprocessable); runItem.Click += (s, a) => Run(treeView.SelectedItem as Task, debug: false); debugItem.Click += (s, a) => Run(treeView.SelectedItem as Task, debug: true); hideItem.Click += (s, a) => Delete(); contextMenu.Items.Add(runItem); contextMenu.Items.Add(debugItem); contextMenu.Items.Add(viewSourceItem); contextMenu.Items.Add(viewFullTextItem); contextMenu.Items.Add(openFileItem); contextMenu.Items.Add(preprocessItem); contextMenu.Items.Add(searchInSubtreeItem); contextMenu.Items.Add(excludeSubtreeFromSearchItem); contextMenu.Items.Add(goToTimeLineItem); contextMenu.Items.Add(copyItem); contextMenu.Items.Add(copySubtreeItem); contextMenu.Items.Add(copyFilePathItem); contextMenu.Items.Add(viewSubtreeTextItem); contextMenu.Items.Add(copyChildrenItem); contextMenu.Items.Add(sortChildrenItem); contextMenu.Items.Add(copyNameItem); contextMenu.Items.Add(copyValueItem); contextMenu.Items.Add(showTimeItem); contextMenu.Items.Add(hideItem); var existingTreeViewItemStyle = (Style)Application.Current.Resources[typeof(TreeViewItem)]; var treeViewItemStyle = new Style(typeof(TreeViewItem), existingTreeViewItemStyle); treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.IsExpandedProperty, new Binding("IsExpanded") { Mode = BindingMode.TwoWay })); treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.IsSelectedProperty, new Binding("IsSelected") { Mode = BindingMode.TwoWay })); treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.VisibilityProperty, new Binding("IsVisible") { Mode = BindingMode.TwoWay, Converter = new BooleanToVisibilityConverter() })); treeViewItemStyle.Setters.Add(new EventSetter(MouseDoubleClickEvent, (MouseButtonEventHandler)OnItemDoubleClick)); treeViewItemStyle.Setters.Add(new EventSetter(PreviewMouseRightButtonDownEvent, (MouseButtonEventHandler)OnPreviewMouseRightButtonDown)); treeViewItemStyle.Setters.Add(new EventSetter(RequestBringIntoViewEvent, (RequestBringIntoViewEventHandler)TreeViewItem_RequestBringIntoView)); treeViewItemStyle.Setters.Add(new EventSetter(KeyDownEvent, (KeyEventHandler)OnItemKeyDown)); treeView.ContextMenu = contextMenu; treeView.ItemContainerStyle = treeViewItemStyle; treeView.KeyDown += TreeView_KeyDown; treeView.SelectedItemChanged += TreeView_SelectedItemChanged; treeView.GotFocus += (s, a) => ActiveTreeView = treeView; ActiveTreeView = treeView; searchLogControl.ResultsList.ItemContainerStyle = treeViewItemStyle; searchLogControl.ResultsList.SelectedItemChanged += ResultsList_SelectionChanged; searchLogControl.ResultsList.GotFocus += (s, a) => ActiveTreeView = searchLogControl.ResultsList; searchLogControl.ResultsList.ContextMenu = sharedTreeContextMenu; propertiesAndItemsControl.ResultsList.ItemContainerStyle = treeViewItemStyle; propertiesAndItemsControl.ResultsList.SelectedItemChanged += ResultsList_SelectionChanged; propertiesAndItemsControl.ResultsList.GotFocus += (s, a) => ActiveTreeView = propertiesAndItemsControl.ResultsList; propertiesAndItemsControl.ResultsList.ContextMenu = sharedTreeContextMenu; if (archiveFile != null) { findInFilesControl.ExecuteSearch = FindInFiles; findInFilesControl.ResultsTreeBuilder = BuildFindResults; findInFilesControl.GotFocus += (s, a) => ActiveTreeView = findInFilesControl.ResultsList; findInFilesControl.ResultsList.ItemContainerStyle = treeViewItemStyle; findInFilesControl.ResultsList.GotFocus += (s, a) => ActiveTreeView = findInFilesControl.ResultsList; findInFilesControl.ResultsList.ContextMenu = sharedTreeContextMenu; filesTab.Visibility = Visibility.Visible; findInFilesTab.Visibility = Visibility.Visible; PopulateFilesTab(); filesTree.ResultsList.ItemContainerStyle = treeViewItemStyle; filesTree.TextChanged += FilesTree_SearchTextChanged; var text = @"This log contains the full text of projects and imported files used during the build. You can use the 'Files' tab in the bottom left to view these files and the 'Find in Files' tab for full-text search. For many nodes in the tree (Targets, Tasks, Errors, Projects, etc) pressing SPACE or ENTER or double-clicking on the node will navigate to the corresponding source code associated with the node. More functionality is available from the right-click context menu for each node. Right-clicking a project node may show the 'Preprocess' option if the version of MSBuild was at least 15.3."; build.Unseal(); #if DEBUG text = build.StringTable.Intern(text); #endif build.AddChild(new Note { Text = text }); build.Seal(); } breadCrumb.SelectionChanged += BreadCrumb_SelectionChanged; Loaded += BuildControl_Loaded; preprocessedFileManager = new PreprocessedFileManager(this.Build, sourceFileResolver); preprocessedFileManager.DisplayFile += filePath => DisplayFile(filePath); navigationHelper = new NavigationHelper(Build, sourceFileResolver); navigationHelper.OpenFileRequested += filePath => DisplayFile(filePath); centralTabControl.SelectionChanged += CentralTabControl_SelectionChanged; } private void CentralTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selectedItem = centralTabControl.SelectedItem as TabItem; if (selectedItem == null) { return; } else if (selectedItem.Name == nameof(timelineTab)) { PopulateTimeline(); } else if (selectedItem.Name == nameof(projectGraphTab)) { PopulateProjectGraph(); } else if (selectedItem.Name == nameof(tracingTab)) { PopulateTrace(); } } private void FilesTree_SearchTextChanged(string text) { var list = filesTree.ResultsList.ItemsSource as IEnumerable<object>; if (list != null) { UpdateFileVisibility(list.OfType<NamedNode>(), text); } } private bool UpdateFileVisibility(IEnumerable<NamedNode> items, string text) { bool visible = false; if (items == null) { return false; } foreach (var item in items) { if (item is Folder folder) { var subItems = folder.Children.OfType<NamedNode>(); var folderVisibility = UpdateFileVisibility(subItems, text); folder.IsVisible = folderVisibility; visible |= folderVisibility; } else if (item is SourceFile file) { if (string.IsNullOrEmpty(text) || file.SourceFilePath.IndexOf(text, StringComparison.OrdinalIgnoreCase) > -1) { visible = true; file.IsVisible = true; } else { file.IsVisible = false; } var subItems = file.Children.OfType<NamedNode>(); var fileVisibility = UpdateFileVisibility(subItems, text); file.IsVisible |= fileVisibility; visible |= fileVisibility; } else if (item is Target || item is Task) { if (string.IsNullOrEmpty(text) || item.Name.IndexOf(text, StringComparison.OrdinalIgnoreCase) > -1 || (text == "$target" && item is Target) || (text == "$task" && item is Task)) { visible = true; item.IsVisible = true; } else { item.IsVisible = false; } } } return visible; } public void SelectTree() { centralTabControl.SelectedIndex = 0; } private void PopulateTimeline() { if (this.timeline.Timeline == null) { var timeline = new Timeline(Build); this.timeline.BuildControl = this; this.timeline.SetTimeline(timeline, Build.StartTime.Ticks); this.timelineWatermark.Visibility = Visibility.Hidden; this.timeline.Visibility = Visibility.Visible; } } private void PopulateTrace() { if (this.tracing.Timeline == null) { var timeline = new Timeline(Build); this.tracing.BuildControl = this; this.tracing.SetTimeline(timeline, Build.StartTime.Ticks, Build.EndTime.Ticks); this.tracingWatermark.Visibility = Visibility.Hidden; this.tracing.Visibility = Visibility.Visible; } } private Microsoft.Msagl.Drawing.Graph graph; private void PopulateProjectGraph() { if (graph != null) { return; } graph = new MsaglProjectGraphConstructor().FromBuild(Build); projectGraphControl.BuildControl = this; if (graph.NodeCount > 1000 || graph.EdgeCount > 10000) { centralTabControl.SelectedIndex = 0; projectGraphTab.Visibility = Visibility.Collapsed; return; } projectGraphControl.SetGraph(graph); projectGraphControl.Visibility = Visibility.Visible; projectGraphWatermark.Visibility = Visibility.Collapsed; } private static string[] searchExamples = new[] { "Copying file from ", "Resolved file path is ", "There was a conflict", "Encountered conflict between", "Building target completely ", "is newer than output ", "Property reassignment: $(", "out-of-date", "csc $task", "ResolveAssemblyReference $task", "$task $time", "$message CompilerServer failed", }; private static string[] nodeKinds = new[] { "$project", "$projectevaluation", "$target", "$task", "$error", "$warning", "$message", "$property", "$item", "$additem", "$removeitem", "$metadata", "$copytask", "$csc", "$rar", "$import", "$noimport" }; private static Inline MakeLink(string query, SearchAndResultsControl searchControl, string before = " \u2022 ", string after = "\r\n") { var hyperlink = new Hyperlink(new Run(query.Trim())); hyperlink.Click += (s, e) => searchControl.SearchText = query; var span = new System.Windows.Documents.Span(); if (before != null) { span.Inlines.Add(new Run(before)); } span.Inlines.Add(hyperlink); if (after != null) { if (after == "\r\n") { span.Inlines.Add(new LineBreak()); } else { span.Inlines.Add(new Run(after)); } } return span; } private void UpdateWatermark() { string watermarkText1 = @"Type in the search box to search. Press Ctrl+F to focus the search box. Results (up to 1000) will display here. Search for multiple words separated by space (space means AND). Enclose multiple words in double-quotes """" to search for the exact phrase. A single word in quotes means exact match (turns off substring search). Use syntax like '$property Prop' to narrow results down by item kind. Supported kinds: "; string watermarkText2 = @"Use the under(FILTER) clause to only include results where any of the nodes in the parent chain matches the FILTER. Use project(...) to filter by parent project. Examples: • $task csc under($project Core) • Copying file project(ProjectA) Append [[$time]], [[$start]] and/or [[$end]] to show times and/or durations and sort the results by start time or duration descending (for tasks, targets and projects). Examples: "; var watermark = new TextBlock(); watermark.Inlines.Add(watermarkText1); bool isFirst = true; foreach (var nodeKind in nodeKinds) { if (!isFirst) { watermark.Inlines.Add(", "); } isFirst = false; watermark.Inlines.Add(MakeLink(nodeKind + " ", searchLogControl, before: null, after: null)); } watermark.Inlines.Add(new LineBreak()); watermark.Inlines.Add(new LineBreak()); AddTextWithHyperlinks(watermarkText2, watermark.Inlines, searchLogControl); foreach (var example in searchExamples) { watermark.Inlines.Add(MakeLink(example, searchLogControl)); } var recentSearches = SettingsService.GetRecentSearchStrings(); if (recentSearches.Any()) { watermark.Inlines.Add(@" Recent: "); foreach (var recentSearch in recentSearches.Where(s => !searchExamples.Contains(s) && !nodeKinds.Contains(s))) { watermark.Inlines.Add(MakeLink(recentSearch, searchLogControl)); } } searchLogControl.WatermarkContent = watermark; } private void UpdatePropertiesAndItemsWatermark() { string watermarkText1 = $@"Look up properties or items for the selected project " + "or a node under a project or evaluation. " + "Properties and items might not be available for some projects.\n\n" + "Surround the search term in quotes to find an exact match " + "(turns off substring search). Prefix the search term with " + "[[name=]] or [[value=]] to only search property and metadata names " + "or values. Add [[$property ]], [[$item ]] or [[$metadata ]] to limit search " + "to a specific node type."; var watermark = new TextBlock(); AddTextWithHyperlinks(watermarkText1, watermark.Inlines, propertiesAndItemsControl); watermark.Inlines.Add(new LineBreak()); watermark.Inlines.Add(new LineBreak()); var recentSearches = SettingsService.GetRecentSearchStrings("PropertiesAndItems"); if (recentSearches.Any()) { watermark.Inlines.Add(@" Recent: "); foreach (var recentSearch in recentSearches) { watermark.Inlines.Add(MakeLink(recentSearch, propertiesAndItemsControl)); } } propertiesAndItemsControl.WatermarkContent = watermark; } public void AddTextWithHyperlinks(string text, InlineCollection result, SearchAndResultsControl searchControl) { const string openParen = "[["; const string closeParen = "]]"; var chunks = TextUtilities.SplitIntoParenthesizedSpans(text, openParen, closeParen); foreach (var chunk in chunks) { if (chunk.StartsWith(openParen) && chunk.EndsWith(closeParen)) { var link = chunk.Substring(openParen.Length, chunk.Length - openParen.Length - closeParen.Length); result.Add(MakeLink(link, searchControl, before: null, after: null)); } else { result.Add(chunk); } } } private void Preprocess(IPreprocessable project) => preprocessedFileManager.ShowPreprocessed(project); private void Run(Task task, bool debug = false) { var logFilePath = Build.LogFilePath; if (!File.Exists(logFilePath)) { MessageBox.Show($"The log file {logFilePath} doesn't exist on disk. Please save the log to disk and reopen it from disk."); return; } try { var directory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); var arguments = $"{logFilePath.QuoteIfNeeded()} {task.Index} pause{(debug ? " debug" : "")}"; if (task.GetTargetFrameworkIdentifier() == ".NETFramework") { var taskRunnerExe = Path.Combine(directory, "TaskRunner.exe"); Process.Start(taskRunnerExe.QuoteIfNeeded(), arguments); } else { var taskRunnerDll = Path.Combine(directory, "TaskRunner.dll"); Process.Start("dotnet", $"{taskRunnerDll.QuoteIfNeeded()} {arguments}"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void ContextMenu_Opened(object sender, RoutedEventArgs e) { var node = treeView.SelectedItem as BaseNode; var visibility = node is NameValueNode ? Visibility.Visible : Visibility.Collapsed; copyNameItem.Visibility = visibility; copyValueItem.Visibility = visibility; viewSourceItem.Visibility = CanView(node) ? Visibility.Visible : Visibility.Collapsed; viewFullTextItem.Visibility = HasFullText(node) ? Visibility.Visible : Visibility.Collapsed; openFileItem.Visibility = CanOpenFile(node) ? Visibility.Visible : Visibility.Collapsed; copyFilePathItem.Visibility = node is Import || (node is IHasSourceFile file && !string.IsNullOrEmpty(file.SourceFilePath)) ? Visibility.Visible : Visibility.Collapsed; var hasChildren = node is TreeNode t && t.HasChildren; copySubtreeItem.Visibility = hasChildren ? Visibility.Visible : Visibility.Collapsed; viewSubtreeTextItem.Visibility = copySubtreeItem.Visibility; showTimeItem.Visibility = node is TimedNode ? Visibility.Visible : Visibility.Collapsed; searchInSubtreeItem.Visibility = hasChildren && node is TimedNode ? Visibility.Visible : Visibility.Collapsed; excludeSubtreeFromSearchItem.Visibility = hasChildren && node is TimedNode ? Visibility.Visible : Visibility.Collapsed; goToTimeLineItem.Visibility = node is TimedNode ? Visibility.Visible : Visibility.Collapsed; copyChildrenItem.Visibility = copySubtreeItem.Visibility; sortChildrenItem.Visibility = copySubtreeItem.Visibility; preprocessItem.Visibility = node is IPreprocessable p && preprocessedFileManager.CanPreprocess(p) ? Visibility.Visible : Visibility.Collapsed; Visibility canRun = Build?.LogFilePath != null && node is Task ? Visibility.Visible : Visibility.Collapsed; runItem.Visibility = canRun; debugItem.Visibility = canRun; hideItem.Visibility = node is TreeNode ? Visibility.Visible : Visibility.Collapsed; } private object FindInFiles(string searchText, int maxResults, CancellationToken cancellationToken) { var results = new List<(string, IEnumerable<(int, string)>)>(); foreach (var file in archiveFile.Files) { if (cancellationToken.IsCancellationRequested) { return null; } var haystack = file.Value; var resultsInFile = haystack.Find(searchText); if (resultsInFile.Count > 0) { results.Add((file.Key, resultsInFile.Select(lineNumber => (lineNumber, haystack.GetLineText(lineNumber))))); } } return results; } private IEnumerable BuildFindResults(object resultsObject, bool moreAvailable = false) { if (resultsObject == null) { return null; } var results = resultsObject as IEnumerable<(string, IEnumerable<(int, string)>)>; var root = new Folder(); // root.Children.Add(new Message { Text = "Elapsed " + Elapsed.ToString() }); if (results != null) { foreach (var file in results) { var folder = new SourceFile() { Name = Path.GetFileName(file.Item1), SourceFilePath = file.Item1, IsExpanded = true }; root.AddChild(folder); foreach (var line in file.Item2) { var sourceFileLine = new SourceFileLine() { LineNumber = line.Item1 + 1, LineText = line.Item2 }; folder.AddChild(sourceFileLine); } } } if (!root.HasChildren && !string.IsNullOrEmpty(findInFilesControl.SearchText)) { root.Children.Add(new Message { Text = "No results found." }); } return root.Children; } private string filePathSeparator; private void PopulateFilesTab() { var root = new Folder(); foreach (var file in archiveFile.Files.OrderBy(kvp => kvp.Key, StringComparer.OrdinalIgnoreCase)) { AddSourceFile(root, file.Key); } foreach (var taskAssembly in Build.TaskAssemblies) { var filePath = ArchiveFile.CalculateArchivePath(taskAssembly.Key); var sourceFile = AddSourceFile(root, filePath); foreach (var taskName in taskAssembly.Value.OrderBy(s => s)) { var task = new Task { Name = taskName }; sourceFile.AddChild(task); } sourceFile.SortChildren(); } foreach (var subFolder in root.Children.OfType<Folder>()) { CompressTree(subFolder); } filesTree.DisplayItems(root.Children); filesTree.GotFocus += (s, a) => ActiveTreeView = filesTree.ResultsList; filesTree.ContextMenu = filesTreeContextMenu; } private SourceFile AddSourceFile(Folder folder, string filePath) { if (filePathSeparator == null) { if (filePath.Contains(":") || (!filePath.StartsWith("\\") && !filePath.StartsWith("/"))) { filePathSeparator = "\\"; } else { filePathSeparator = "/"; } } var parts = filePath.Split('\\', '/'); return AddSourceFile(folder, filePath, parts, 0); } private void CompressTree(Folder parent) { if (parent.Children.Count == 1 && parent.Children[0] is Folder subfolder) { parent.Children.Clear(); var grandchildren = subfolder.Children.ToArray(); subfolder.Children.Clear(); foreach (var grandChild in grandchildren) { parent.Children.Add(grandChild); } if (filePathSeparator == null) { filePathSeparator = "\\"; } parent.Name = parent.Name + filePathSeparator + subfolder.Name; CompressTree(parent); } else { foreach (var subFolder in parent.Children.OfType<Folder>()) { CompressTree(subFolder); } } } private SourceFile AddSourceFile(Folder folder, string filePath, string[] parts, int index) { if (index == parts.Length - 1) { var file = new SourceFile { SourceFilePath = filePath, Name = parts[index] }; foreach (var target in GetTargets(filePath)) { file.AddChild(new Target { Name = target, SourceFilePath = filePath }); } file.SortChildren(); folder.AddChild(file); return file; } else { var folderName = parts[index]; // root of the Mac file system if (string.IsNullOrEmpty(folderName) && index == 0) { folderName = "/"; } var subfolder = folder.GetOrCreateNodeWithName<Folder>(folderName); subfolder.IsExpanded = true; return AddSourceFile(subfolder, filePath, parts, index + 1); } } private IEnumerable<string> GetTargets(string file) { if (file.EndsWith(".sln", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { yield break; } var content = sourceFileResolver.GetSourceFileText(file); if (content == null) { yield break; } var contentText = content.Text; if (!Utilities.LooksLikeXml(contentText)) { yield break; } var doc = new XmlDocument(); try { doc.LoadXml(contentText); } catch (Exception) { yield break; } if (doc.DocumentElement == null) { yield break; } var nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("x", doc.DocumentElement.NamespaceURI); var xmlNodeList = doc.SelectNodes(@"//x:Project/x:Target[@Name]", nsmgr); if (xmlNodeList == null) { yield break; } foreach (XmlNode selectNode in xmlNodeList) { yield return selectNode.Attributes["Name"].Value; } } /// <summary> /// This is needed as a workaround for a weird bug. When the breadcrumb spans multiple lines /// and we click on an item on the first line, it truncates the breadcrumb up to that item. /// The fact that the breadcrumb moves down while the Mouse is captured results in a MouseMove /// in the ListBox, which triggers moving selection to top and selecting the first item. /// Without this "reentrancy" guard the event would be handled twice, with just the root /// of the chain left in the breadcrumb at the end. /// </summary> private bool isProcessingBreadcrumbClick = false; internal static TimeSpan Elapsed; private void BreadCrumb_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (isProcessingBreadcrumbClick) { return; } isProcessingBreadcrumbClick = true; var node = breadCrumb.SelectedItem as TreeNode; if (node != null) { SelectItem(node); treeView.Focus(); e.Handled = true; } // turn it off only after the storm of layouts caused by the mouse click has subsided Dispatcher.InvokeAsync(() => { isProcessingBreadcrumbClick = false; }, DispatcherPriority.Background); } private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var item = treeView.SelectedItem; if (item != null) { UpdateBreadcrumb(item); UpdateProjectContext(item); } } private void ResultsList_SelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var treeView = sender as TreeView; if (treeView != null && treeView.SelectedItem is ProxyNode proxy) { var item = proxy.Original; if (item != null) { SelectItem(item); } } } public void UpdateProjectContext(object item) { if (item is not BaseNode node) { return; } var project = node.GetNearestParentOrSelf<Project>(); if (project != null) { //projectEvaluation = Build.FindEvaluation(project.EvaluationId); //if (projectEvaluation != null && (projectEvaluation.FindChild<Folder>(Strings.Items) != null || projectEvaluation.FindChild<Folder>(Strings.Properties) != null)) //{ // SetProjectContext(projectEvaluation); // return; //} //if (project.FindChild<Folder>(Strings.Items) != null || project.FindChild<Folder>(Strings.Properties) != null) //{ // SetProjectContext(project); // return; //} SetProjectContext(project); return; } var projectEvaluation = node.GetNearestParentOrSelf<ProjectEvaluation>(); if (projectEvaluation != null && (projectEvaluation.FindChild<Folder>(Strings.Items) != null || projectEvaluation.FindChild<Folder>(Strings.Properties) != null)) { SetProjectContext(projectEvaluation); return; } SetProjectContext(null); } private object projectContext; public void SetProjectContext(object contents) { projectContext = contents; propertiesAndItemsContext.Content = contents; var visibility = contents != null ? Visibility.Visible : Visibility.Collapsed; projectContextBorder.Visibility = visibility; propertiesAndItemsControl.TopPanel.Visibility = visibility; } public IProjectOrEvaluation GetProjectContext() { return projectContext as IProjectOrEvaluation; } public void UpdateBreadcrumb(object item) { var node = item as BaseNode; IEnumerable<object> chain = node?.GetParentChainIncludingThis(); if (chain == null || !chain.Any()) { chain = new[] { item }; } else { chain = IntersperseWithSeparators(chain).ToArray(); } breadCrumb.ItemsSource = chain; breadCrumb.SelectedIndex = -1; } private IEnumerable<object> IntersperseWithSeparators(IEnumerable<object> list) { bool first = true; foreach (var item in list) { if (first) { first = false; } else { yield return new Separator(); } yield return item; } } private void BuildControl_Loaded(object sender, RoutedEventArgs e) { scrollViewer = treeView.Template.FindName("_tv_scrollviewer_", treeView) as ScrollViewer; if (!Build.Succeeded) { var firstError = Build.FindFirstInSubtreeIncludingSelf<Error>(); if (firstError != null) { SelectItem(firstError); treeView.Focus(); } if (InitialSearchText == null) { InitialSearchText = "$error"; } } if (InitialSearchText != null) { searchLogControl.SearchText = InitialSearchText; } } public string InitialSearchText { get; set; } public void SelectItem(BaseNode item) { var parentChain = item.GetParentChainIncludingThis(); if (!parentChain.Any()) { return; } SelectTree(); treeView.SelectContainerFromItem<object>(parentChain); } private void TreeView_KeyDown(object sender, KeyEventArgs args) { if (args.Key == Key.Delete) { Delete(); args.Handled = true; } else if (args.Key == Key.C && args.KeyboardDevice.Modifiers == ModifierKeys.Control) { CopySubtree(); args.Handled = true; } else if (args.Key >= Key.A && args.Key <= Key.Z && args.KeyboardDevice.Modifiers == ModifierKeys.None) { SelectItemByKey((char)('A' + args.Key - Key.A)); args.Handled = true; } } private int characterMatchPrefixLength = 0; private void SelectItemByKey(char ch) { ch = char.ToLowerInvariant(ch); var selectedItem = treeView.SelectedItem as BaseNode; if (selectedItem == null) { return; } var parent = selectedItem.Parent; if (parent == null) { return; } var selectedText = GetText(selectedItem); var prefix = selectedText.Substring(0, Math.Min(characterMatchPrefixLength, selectedText.Length)); var items = selectedItem.EnumerateSiblingsCycle(); search: foreach (var item in items) { var text = GetText(item); if (characterMatchPrefixLength < text.Length && text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { var character = text[characterMatchPrefixLength]; if (char.ToLowerInvariant(character) == ch) { characterMatchPrefixLength++; SelectItem(item); return; } } } if (characterMatchPrefixLength > 0) { characterMatchPrefixLength = 0; prefix = ""; items = items.Skip(1).Concat(items.Take(1)); goto search; } string GetText(BaseNode node) { if (node is IHasTitle hasTitle) { return hasTitle.Title; } else { return node.ToString(); } } } public void FocusSearch() { if (leftPaneTabControl.SelectedItem == searchLogTab) { searchLogControl.searchTextBox.Focus(); } else if (leftPaneTabControl.SelectedItem == findInFilesTab) { findInFilesControl.searchTextBox.Focus(); } else if (leftPaneTabControl.SelectedItem == propertiesAndItemsTab) { propertiesAndItemsControl.searchTextBox.Focus(); } } public void SelectSearchTab() { leftPaneTabControl.SelectedItem = searchLogTab; } public void Delete() { var node = treeView.SelectedItem as TreeNode; if (node != null) { MoveSelectionOut(node); node.IsVisible = false; } } public void Copy() { var treeNode = treeView.SelectedItem; if (treeNode != null) { var text = treeNode.ToString(); CopyToClipboard(text); } } public void CopySubtree() { if (treeView.SelectedItem is BaseNode treeNode) { var text = Microsoft.Build.Logging.StructuredLogger.StringWriter.GetString(treeNode); CopyToClipboard(text); } } public void ViewSubtreeText() { if (treeView.SelectedItem is BaseNode treeNode) { var text = Microsoft.Build.Logging.StructuredLogger.StringWriter.GetString(treeNode); DisplayText(text, treeNode.ToString()); } } public void ShowTimeAndDuration() { if (treeView.SelectedItem is TimedNode timedNode) { var text = timedNode.GetTimeAndDurationText(fullPrecision: true); DisplayText(text, timedNode.ToString()); } } public void OpenFile() { if (treeView.SelectedItem is Import import) { DisplayFile(import.ImportedProjectFilePath, evaluation: import.GetNearestParent<ProjectEvaluation>()); } } public void CopyFilePath() { string toCopy = null; if (treeView.SelectedItem is Import import) { toCopy = import.ImportedProjectFilePath; } else if (treeView.SelectedItem is IHasSourceFile file) { toCopy = file.SourceFilePath; } if (toCopy != null) { CopyToClipboard(toCopy); } } public void SearchInSubtree() { if (treeView.SelectedItem is TimedNode treeNode) { searchLogControl.SearchText += $" under(${treeNode.Index})"; SelectSearchTab(); } } public void ExcludeSubtreeFromSearch() { if (treeView.SelectedItem is TimedNode treeNode) { searchLogControl.SearchText += $" notunder(${treeNode.Index})"; SelectSearchTab(); } } public void GoToTimeLine() { var treeNode = treeView.SelectedItem as TimedNode; if (treeNode != null) { centralTabControl.SelectedIndex = 1; this.timeline.GoToTimedNode(treeNode); } } public void CopyChildren() { if (treeView.SelectedItem is TreeNode node && node.HasChildren) { // the texts have \n for line breaks, expand to \r\n var children = node.Children.Select(c => c.ToString().Replace("\n", "\r\n")); var text = string.Join(Environment.NewLine, children); CopyToClipboard(text); } } public void SortChildren() { var selectedItem = treeView.SelectedItem; if (selectedItem is TreeNode treeNode) { treeNode.SortChildren(); } } private void CopyAll(TreeView tree = null) { tree = tree ?? ActiveTreeView; if (tree == null) { return; } var sb = new StringBuilder(); foreach (var item in tree.Items.OfType<BaseNode>()) { var text = Microsoft.Build.Logging.StructuredLogger.StringWriter.GetString(item); sb.Append(text); if (!text.Contains("\n")) { sb.AppendLine(); } } CopyToClipboard(sb.ToString()); } private void CopyPaths(TreeView tree = null) { tree = tree ?? ActiveTreeView; if (tree == null) { return; } var sb = new StringBuilder(); foreach (var item in tree.Items.OfType<TreeNode>()) { item.VisitAllChildren<BaseNode>(s => { if (s is SourceFile file && !string.IsNullOrEmpty(file.SourceFilePath)) { sb.AppendLine(file.SourceFilePath); } }); } CopyToClipboard(sb.ToString()); } private static void CopyToClipboard(string text) { try { text = text.Replace("\0", ""); Clipboard.SetText(text); } catch (Exception) { // clipboard API is notoriously flaky } } public void CopyName() { var nameValueNode = treeView.SelectedItem as NameValueNode; if (nameValueNode != null) { CopyToClipboard(nameValueNode.Name); } } public void CopyValue() { var nameValueNode = treeView.SelectedItem as NameValueNode; if (nameValueNode != null) { CopyToClipboard(nameValueNode.Value); } } private void MoveSelectionOut(BaseNode node) { var parent = node.Parent; if (parent == null) { return; } var next = parent.FindNextChild<BaseNode>(node); if (next != null) { node.IsSelected = false; next.IsSelected = true; return; } var previous = parent.FindPreviousChild<BaseNode>(node); if (previous != null) { node.IsSelected = false; previous.IsSelected = true; } else { node.IsSelected = false; parent.IsSelected = true; } } private void OnItemKeyDown(object sender, KeyEventArgs args) { if (args.Key == Key.Space || args.Key == Key.Return) { var treeNode = GetNode(args); if (treeNode != null) { args.Handled = Invoke(treeNode) || ViewFullText(treeNode); } } if (args.Key == Key.Escape) { if (documentWell.IsVisible) { documentWell.Hide(); } } } private void OnItemDoubleClick(object sender, MouseButtonEventArgs args) { // workaround for http://stackoverflow.com/a/36244243/37899 var treeViewItem = sender as TreeViewItem; if (!treeViewItem.IsSelected) { return; } var node = GetNode(args); if (node != null) { args.Handled = Invoke(node) || ViewFullText(node); } } private void OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs args) { if (sender is TreeViewItem treeViewItem) { treeViewItem.IsSelected = true; } } private bool CanView(BaseNode node) { return node is AbstractDiagnostic || node is Project || (node is Target t && t.SourceFilePath != null && sourceFileResolver.HasFile(t.SourceFilePath)) || (node is Task task && task.Parent is Target parentTarget && sourceFileResolver.HasFile(parentTarget.SourceFilePath)) || (node is IHasSourceFile ihsf && ihsf.SourceFilePath != null && sourceFileResolver.HasFile(ihsf.SourceFilePath)); } private bool HasFullText(BaseNode node) { return (node is NameValueNode nvn && nvn.IsValueShortened) || (node is TextNode tn && tn.IsTextShortened); } private bool CanOpenFile(BaseNode node) { return node is Import i && sourceFileResolver.HasFile(i.ImportedProjectFilePath); } private bool ViewFullText(BaseNode treeNode) { if (treeNode == null) { return false; } switch (treeNode) { case NameValueNode nameValueNode when nameValueNode.IsValueShortened: return DisplayText(nameValueNode.Value, nameValueNode.Name); case TextNode textNode when textNode.IsTextShortened: return DisplayText(textNode.Text, textNode.Name ?? textNode.GetType().Name); default: return false; } } private bool Invoke(BaseNode treeNode) { if (treeNode == null) { return false; } try { switch (treeNode) { case AbstractDiagnostic diagnostic: var path = diagnostic.File; if (!DisplayFile(path, diagnostic.LineNumber) && path != null && !Path.IsPathRooted(path) && diagnostic.ProjectFile != null) { // path must be relative, try to normalize: path = Path.Combine(Path.GetDirectoryName(diagnostic.ProjectFile), path); return DisplayFile(path, diagnostic.LineNumber, diagnostic.ColumnNumber); } break; case Target target: return DisplayTarget(target.SourceFilePath, target.Name); case Task task: return DisplayTask(task); case AddItem addItem: return DisplayAddRemoveItem(addItem.Parent, addItem.LineNumber ?? 0); case RemoveItem removeItem: return DisplayAddRemoveItem(removeItem.Parent, removeItem.LineNumber ?? 0); case IHasSourceFile hasSourceFile when hasSourceFile.SourceFilePath != null: int line = 0; var hasLine = hasSourceFile as IHasLineNumber; if (hasLine != null) { line = hasLine.LineNumber ?? 0; } ProjectEvaluation evaluation = null; if (hasSourceFile is TreeNode node) { // TODO: https://github.com/KirillOsenkov/MSBuildStructuredLog/issues/392 evaluation = node.GetNearestParentOrSelf<ProjectEvaluation>(); } return DisplayFile(hasSourceFile.SourceFilePath, line, evaluation: evaluation); case SourceFileLine sourceFileLine when sourceFileLine.Parent is SourceFile sourceFile && sourceFile.SourceFilePath != null: return DisplayFile(sourceFile.SourceFilePath, sourceFileLine.LineNumber); default: return false; } } catch { // in case our guessing of file path goes awry } return false; } public bool DisplayFile(string sourceFilePath, int lineNumber = 0, int column = 0, ProjectEvaluation evaluation = null) { var text = sourceFileResolver.GetSourceFileText(sourceFilePath); if (text == null) { return false; } string preprocessableFilePath = Utilities.InsertMissingDriveSeparator(sourceFilePath); Action preprocess = null; if (evaluation != null) { preprocess = preprocessedFileManager.GetPreprocessAction(preprocessableFilePath, PreprocessedFileManager.GetEvaluationKey(evaluation)); } documentWell.DisplaySource(preprocessableFilePath, text.Text, lineNumber, column, preprocess, navigationHelper); return true; } public bool DisplayText(string text, string caption = null) { caption = TextUtilities.SanitizeFileName(caption); documentWell.DisplaySource(caption ?? "Text", text, displayPath: false); return true; } private bool DisplayAddRemoveItem(TreeNode parent, int line) { if (parent is not Target target) { return false; } string sourceFilePath = target.SourceFilePath; return DisplayFile(sourceFilePath, line); } private bool DisplayTask(Task task) { var sourceFilePath = task.SourceFilePath; var parent = task.Parent; var name = task.Name; if (parent is not Target target) { return DisplayFile(sourceFilePath); } if (task.LineNumber.HasValue && task.LineNumber.Value > 0) { return DisplayFile(sourceFilePath, task.LineNumber.Value); } return DisplayTarget(sourceFilePath, target.Name, name); } public bool DisplayTarget(string sourceFilePath, string targetName, string taskName = null) { var text = sourceFileResolver.GetSourceFileText(sourceFilePath); if (text == null) { return false; } var xml = text.XmlRoot.Root; IXmlElement root = xml; int startPosition = 0; int line = 0; // work around a bug in Xml Parser where a virtual parent is created around the root element // when the root element is preceded by trivia (comment) if (root.Name == null && root.Elements.FirstOrDefault() is IXmlElement firstElement && firstElement.Name == "Project") { root = firstElement; } foreach (var element in root.Elements) { if (element.Name == "Target" && element.Attributes != null) { var nameAttribute = element.AsSyntaxElement.Attributes.FirstOrDefault(a => a.Name == "Name" && a.Value == targetName); if (nameAttribute != null) { startPosition = nameAttribute.ValueNode.Start; if (taskName != null) { var tasks = element.Elements.Where(e => e.Name == taskName).ToArray(); if (tasks.Length == 1) { startPosition = tasks[0].AsSyntaxElement.NameNode.Start; } } break; } } } if (startPosition > 0) { line = text.GetLineNumberFromPosition(startPosition); } return DisplayFile(sourceFilePath, line + 1); } private static BaseNode GetNode(RoutedEventArgs args) { var treeViewItem = args.Source as TreeViewItem; var node = treeViewItem?.DataContext as BaseNode; return node; } public IEnumerable BuildResultTree(object resultsObject, bool moreAvailable = false) { var folder = ResultTree.BuildResultTree(resultsObject, moreAvailable, Elapsed); if (moreAvailable) { var showAllButton = new ButtonNode { Text = $"Showing first {folder.Children.Count} results. Show all results instead (slow)." }; showAllButton.OnClick = () => { showAllButton.IsEnabled = false; searchLogControl.TriggerSearch(searchLogControl.SearchText, int.MaxValue); }; folder.AddChildAtBeginning(showAllButton); } return folder.Children; } private void TreeViewItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { if (scrollViewer == null) { return; } var treeViewItem = (TreeViewItem)sender; var treeView = (TreeView)typeof(TreeViewItem).GetProperty("ParentTreeView", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(treeViewItem); if (PresentationSource.FromDependencyObject(treeViewItem) == null) { // the item might have disconnected by the time we run this return; } Point topLeftInTreeViewCoordinates = treeViewItem.TransformToAncestor(treeView).Transform(new Point(0, 0)); var treeViewItemTop = topLeftInTreeViewCoordinates.Y; if (treeViewItemTop < 0 || treeViewItemTop + treeViewItem.ActualHeight > scrollViewer.ViewportHeight || treeViewItem.ActualHeight > scrollViewer.ViewportHeight) { // if the item is not visible or too "tall", don't do anything; let them scroll it into view return; } // if the item is already fully within the viewport vertically, disallow horizontal scrolling e.Handled = true; } private void TreeViewItem_Selected(object sender, RoutedEventArgs e) { SelectedTreeViewItem = e.OriginalSource as TreeViewItem; } public void DisplayStats() { if (!File.Exists(LogFilePath)) { return; } var statsRoot = Build.FindChild<Folder>(f => f.Name.StartsWith(Strings.Statistics)); if (statsRoot != null) { return; } var recordStats = BinlogStats.Calculate(this.LogFilePath); var records = recordStats.CategorizedRecords; Build.Unseal(); statsRoot = DisplayRecordStats(records, Build); var treeStats = Build.Statistics; DisplayTreeStats(statsRoot, treeStats, recordStats); //var histogram = GetHistogram(recordStats.StringSizes); //var histogramNode = new CustomContentNode { Content = histogram }; //statsRoot.AddChild(histogramNode); statsRoot.AddChild(new Property { Name = "BinlogFileFormatVersion", Value = Build.FileFormatVersion.ToString() }); statsRoot.AddChild(new Property { Name = "FileSize", Value = recordStats.FileSize.ToString("N0") }); statsRoot.AddChild(new Property { Name = "UncompressedStreamSize", Value = recordStats.UncompressedStreamSize.ToString("N0") }); statsRoot.AddChild(new Property { Name = "RecordCount", Value = recordStats.RecordCount.ToString("N0") }); // This is interesting. Technically WPF needs the Build.Children collection to be observable // to properly refresh the list when we add a new node. However it suffices to replace the Children // collection with something else (and I assume it gets a new collection view and that is // equivalent to a Reset. // We could literally just do children = children.ToArray() and that would be sufficient here. // Note that there's no need to actually change it to observable collection this late. // Since the children have already mutated by the time we're setting this. Ideally we should be // setting this at the beginning. // It also doesn't seem like raising PropertyChanged for Children is necessary. // See https://github.com/KirillOsenkov/MSBuildStructuredLog/issues/487 for details. Build.MakeChildrenObservable(); } private UIElement GetHistogram(List<int> values) { double width = 800; double height = 200; var fill = Brushes.AliceBlue; var border = Brushes.LightBlue; var canvas = new Canvas() { Width = width, Height = height, Background = Brushes.Azure }; double max = values.Max(); int count = values.Count; for (double x = 0; x < width; x++) { int startIndex = (int)(x / width * count); int endIndex = (int)((x + 1) / width * count); if (startIndex < 0) { startIndex = 0; } if (endIndex >= count) { endIndex = count; } if (startIndex >= endIndex) { continue; } int sum = 0; int maxInBucket = 0; for (int i = startIndex; i < endIndex; i++) { int value = values[i]; sum += value; if (maxInBucket < value) { maxInBucket = value; } } if (sum == 0) { continue; } double y = height * maxInBucket / max; if (y < height / 2) { y += 5; } var rect = new System.Windows.Shapes.Rectangle { Width = 1, Height = y, Fill = fill, Stroke = border }; Canvas.SetLeft(rect, x); Canvas.SetTop(rect, height - y); canvas.Children.Add(rect); } return canvas; } private void DisplayTreeStats(Folder statsRoot, BuildStatistics treeStats, BinlogStats recordStats) { var buildMessageNode = statsRoot.FindChild<Folder>(n => n.Name.StartsWith("BuildMessage", StringComparison.Ordinal)); var taskInputsNode = buildMessageNode.FindChild<Folder>(n => n.Name.StartsWith("Task Input", StringComparison.Ordinal)); var taskOutputsNode = buildMessageNode.FindChild<Folder>(n => n.Name.StartsWith("Task Output", StringComparison.Ordinal)); AddTopTasks(treeStats.TaskParameterMessagesByTask, taskInputsNode); AddTopTasks(treeStats.OutputItemMessagesByTask, taskOutputsNode); if (recordStats.StringTotalSize > 0) { var strings = new Item { Text = BinlogStats.GetString("Strings", recordStats.StringTotalSize, recordStats.StringCount, recordStats.StringLargest) }; var allStringText = string.Join("\n", recordStats.AllStrings); var allStrings = new Message { Text = allStringText }; statsRoot.AddChild(strings); strings.AddChild(allStrings); } if (recordStats.NameValueListTotalSize > 0) { statsRoot.AddChild(new Message { Text = BinlogStats.GetString( "NameValueLists", recordStats.NameValueListTotalSize, recordStats.NameValueListCount, recordStats.NameValueListLargest) }); } if (recordStats.BlobTotalSize > 0) { statsRoot.AddChild(new Message { Text = BinlogStats.GetString("Blobs", recordStats.BlobTotalSize, recordStats.BlobCount, recordStats.BlobLargest) }); } } private static void AddTopTasks(Dictionary<string, List<string>> messagesByTask, Folder node) { var topTaskParameters = messagesByTask .Select(kvp => (taskName: kvp.Key, count: kvp.Value.Count, totalSize: kvp.Value.Sum(s => s.Length * 2), largest: kvp.Value.Max(s => s.Length) * 2)) .OrderByDescending(kvp => kvp.totalSize) .Take(20); foreach (var task in topTaskParameters) { var name = BinlogStats.GetString(task.taskName, task.totalSize, task.count, task.largest); node.AddChild(new Folder { Name = name }); } } private Folder DisplayRecordStats(BinlogStats.RecordsByType stats, TreeNode parent, string titlePrefix = "") { var node = parent.GetOrCreateNodeWithName<Folder>(titlePrefix + stats.ToString()); foreach (var records in stats.CategorizedRecords) { DisplayRecordStats(records, node); } var top = stats.Records.Take(300).ToArray(); foreach (var item in top) { if (item.Args is BuildMessageEventArgs buildMessage) { node.AddChild(new Message { Text = buildMessage.Message }); } } return node; } public override string ToString() { return Build?.ToString(); } } }
38.235507
213
0.521274
[ "MIT" ]
G-arj/MSBuildStructuredLog
src/StructuredLogViewer/Controls/BuildControl.xaml.cs
73,875
C#
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Domain { /// <summary> /// AlipayEcoMycarCarmodelModifyModel Data Structure. /// </summary> public class AlipayEcoMycarCarmodelModifyModel : AlipayObject { /// <summary> /// 支付宝车型库品牌背景图片,尺寸750 x 448(modify_type参数的值为brand时此参数必填)图片url可以通过【通用图片上传接口】alipay.eco.mycar.image.upload 上传完成后获取, 图片url需要进行URLencode进行转码 /// </summary> [JsonPropertyName("background_url")] public string BackgroundUrl { get; set; } /// <summary> /// 支付宝车型库品牌编号(系统唯一),品牌编号可以通过调用【批量查询车型信息接口】alipay.eco.mycar.carmodel.batchquery 获取。(modify_type参数的值为brand时此参数必填) /// </summary> [JsonPropertyName("brand_id")] public string BrandId { get; set; } /// <summary> /// 支付宝车型库品牌图片,尺寸220 x 147 (modify_type参数的值为brand时此参数必填)品牌图片url可以通过【通用图片上传接口】alipay.eco.mycar.image.upload上传完成后获取, 图片url需要进行URLencode进行转码 /// </summary> [JsonPropertyName("brand_logo")] public string BrandLogo { get; set; } /// <summary> /// 支付宝车型库品牌名称(add_type参数的值为brand时此参数必填)开发者自行配置,保证系统唯一 /// </summary> [JsonPropertyName("brand_name")] public string BrandName { get; set; } /// <summary> /// 支付宝车型库排量(modify_type参数的值为model时此参数必填) /// </summary> [JsonPropertyName("cc")] public string Cc { get; set; } /// <summary> /// 支付宝车型库厂商编号(系统唯一),厂商编号可以通过调用【批量查询车型信息接口】alipay.eco.mycar.carmodel.batchquery 获取。(modify_type参数的值为company时此参数必填) /// </summary> [JsonPropertyName("company_id")] public string CompanyId { get; set; } /// <summary> /// 支付宝车型库厂商名称(modify_type参数的值为company时此参数必填) /// </summary> [JsonPropertyName("company_name")] public string CompanyName { get; set; } /// <summary> /// 支付宝车型库发动机型号(modify_type参数的值为model时此参数必填) /// </summary> [JsonPropertyName("engine")] public string Engine { get; set; } /// <summary> /// 支付宝车型库车型编号(系统唯一),可以通过调用【批量查询车型信息接口】alipay.eco.mycar.carmodel.batchquery 获取。(modify_type参数的值为model时此参数必填) /// </summary> [JsonPropertyName("model_id")] public string ModelId { get; set; } /// <summary> /// 支付宝车型库车型名称(modify_type参数的值为model时此参数必填) /// </summary> [JsonPropertyName("model_name")] public string ModelName { get; set; } /// <summary> /// 修改类型,接口通过此参数判断本次请求是修改品牌信息还是车型信息等,brand(品牌),company(厂商),serie(车系),model(车型) /// </summary> [JsonPropertyName("modify_type")] public string ModifyType { get; set; } /// <summary> /// 支付宝车型库生产年份(modify_type参数的值为model时此参数必填) /// </summary> [JsonPropertyName("prod_year")] public string ProdYear { get; set; } /// <summary> /// 支付宝车型库车系组名称(add_type":"serie状态时必填) /// </summary> [JsonPropertyName("serie_group")] public string SerieGroup { get; set; } /// <summary> /// 支付宝车型库车系编号(系统唯一),车系编号可以通过调用【批量查询车型信息接口】alipay.eco.mycar.carmodel.batchquery 获取。(modify_type参数的值为serie时此参数必填) /// </summary> [JsonPropertyName("serie_id")] public string SerieId { get; set; } /// <summary> /// 支付宝车型库车系名称(modify_type参数的值为serie时此参数必填) /// </summary> [JsonPropertyName("serie_name")] public string SerieName { get; set; } /// <summary> /// 支付宝车型库车系logo图片链接地址,尺寸220 x 147 (modify_type参数的值为serie时此参数必填)图片url可以通过【通用图片上传接口】alipay.eco.mycar.image.upload 上传完成后获取,图片url需要进行URLencode进行转码 /// </summary> [JsonPropertyName("serie_photo")] public string SeriePhoto { get; set; } /// <summary> /// 支付宝车型库年款(modify_type参数的值为model时此参数必填) /// </summary> [JsonPropertyName("style")] public string Style { get; set; } } }
35.185841
151
0.611419
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Domain/AlipayEcoMycarCarmodelModifyModel.cs
5,310
C#
using Anvil.API; using NUnit.Framework; using NWN.Native.API; namespace Anvil.Tests.API { [TestFixture(Category = "API.EngineStructure")] public sealed class EffectTests { [Test(Description = "Creating an effect and disposing the effect explicitly frees the associated memory.")] public void CreateAndDisposeEffectValidPropertyUpdated() { Effect effect = Effect.CutsceneParalyze(); Assert.IsTrue(effect.IsValid, "Effect was not valid after creation."); effect.Dispose(); Assert.IsFalse(effect.IsValid, "Effect was still valid after disposing."); } [Test(Description = "A soft effect reference created from a native object does not cause the original effect to be deleted.")] public void CreateSoftEffectReferencAndDisposeDoesNotFreeMemory() { Effect effect = Effect.Blindness(); Assert.IsTrue(effect.IsValid, "Effect was not valid after creation."); CGameEffect gameEffect = effect; Assert.IsNotNull(gameEffect, "Native effect was not valid after implicit cast."); Effect softReference = gameEffect.ToEffect(false); softReference.Dispose(); Assert.IsTrue(softReference.IsValid, "The soft reference disposed the memory of the original effect."); } } }
37.088235
130
0.725615
[ "MIT" ]
milliorn/NWN.Managed
NWN.Anvil.Tests/src/main/API/EngineStructure/EffectTests.cs
1,261
C#