content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Orang.FileSystem
{
internal enum PathOrigin
{
Argument = 0,
File = 1,
RedirectedInput = 2,
CurrentDirectory = 3,
}
}
| 25.615385 | 160 | 0.654655 |
[
"Apache-2.0"
] |
Rynaret/Orang
|
src/CommandLine/FileSystem/PathOrigin.cs
| 335 |
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 Xunit;
namespace System.Numerics.Tests
{
public class powTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunPowPositive()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Pow Method - 0^(1)
VerifyPowString(BigInteger.One.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
// Pow Method - 0^(0)
VerifyPowString(BigInteger.Zero.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
// Pow Method - Two Small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomByteArray(s_random, 2);
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
}
// Pow Method - One large and one small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomByteArray(s_random);
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
}
// Pow Method - One large BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
tempByteArray2 = new byte[] { 0 };
VerifyPowString(Print(tempByteArray2) + Print(tempByteArray1) + "bPow");
}
// Pow Method - One small BigIntegers and zero
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 2);
tempByteArray2 = new byte[] { 0 };
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
VerifyPowString(Print(tempByteArray2) + Print(tempByteArray1) + "bPow");
}
}
[Fact]
public static void RunPowAxiomXPow1()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X^1 = X
VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " bPow", Int32.MaxValue.ToString());
VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " bPow", Int64.MaxValue.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(BigInteger.One + " " + randBigInt + "bPow", randBigInt.Substring(0, randBigInt.Length - 1));
}
}
[Fact]
public static void RunPowAxiomXPow0()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: X^0 = 1
VerifyIdentityString(BigInteger.Zero + " " + Int32.MaxValue + " bPow", BigInteger.One.ToString());
VerifyIdentityString(BigInteger.Zero + " " + Int64.MaxValue + " bPow", BigInteger.One.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomByteArray(s_random));
VerifyIdentityString(BigInteger.Zero + " " + randBigInt + "bPow", BigInteger.One.ToString());
}
}
[Fact]
public static void RunPowAxiom0PowX()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: 0^X = 0
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bPow", BigInteger.Zero.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomPosByteArray(s_random, 4));
VerifyIdentityString(randBigInt + BigInteger.Zero + " bPow", BigInteger.Zero.ToString());
}
}
[Fact]
public static void RunPowAxiom1PowX()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Axiom: 1^X = 1
VerifyIdentityString(Int32.MaxValue + " " + BigInteger.One + " bPow", BigInteger.One.ToString());
for (int i = 0; i < s_samples; i++)
{
String randBigInt = Print(GetRandomPosByteArray(s_random, 4));
VerifyIdentityString(randBigInt + BigInteger.One + " bPow", BigInteger.One.ToString());
}
}
[Fact]
public static void RunPowBoundary()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Check interesting cases for boundary conditions
// You'll either be shifting a 0 or 1 across the boundary
// 32 bit boundary n2=0
VerifyPowString("2 " + Math.Pow(2, 32) + " bPow");
// 32 bit boundary n1=0 n2=1
VerifyPowString("2 " + Math.Pow(2, 33) + " bPow");
}
[Fact]
public static void RunPowNegative()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
// Pow Method - 1^(-1)
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(BigInteger.MinusOne.ToString() + " " + BigInteger.One.ToString() + " bPow");
});
// Pow Method - 0^(-1)
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(BigInteger.MinusOne.ToString() + " " + BigInteger.Zero.ToString() + " bPow");
});
// Pow Method - Negative Exponent
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomNegByteArray(s_random, 2);
tempByteArray2 = GetRandomByteArray(s_random, 2);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
VerifyPowString(Print(tempByteArray1) + Print(tempByteArray2) + "bPow");
});
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Mono)]
public static void RunOverflow()
{
var bytes = new byte[1000];
bytes[bytes.Length - 1] = 1;
Assert.Throws<OverflowException>(() =>
BigInteger.Pow(new BigInteger(bytes), int.MaxValue));
}
private static void VerifyPowString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 10));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static Byte[] GetRandomPosByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] &= 0x7F;
return value;
}
private static Byte[] GetRandomNegByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] |= 0x80;
return value;
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
}
}
| 35.40873 | 129 | 0.530315 |
[
"MIT"
] |
BrzVlad/corefx
|
src/System.Runtime.Numerics/tests/BigInteger/pow.cs
| 8,923 |
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-2014-10-21.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.CloudFront.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.CloudFront.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateDistribution operation
/// </summary>
public class CreateDistributionResponseUnmarshaller : XmlResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
CreateDistributionResponse response = new CreateDistributionResponse();
UnmarshallResult(context,response);
if (context.ResponseData.IsHeaderPresent("ETag"))
response.ETag = context.ResponseData.GetHeaderValue("ETag");
if (context.ResponseData.IsHeaderPresent("Location"))
response.Location = context.ResponseData.GetHeaderValue("Location");
return response;
}
private static void UnmarshallResult(XmlUnmarshallerContext context, CreateDistributionResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("Distribution", targetDepth))
{
var unmarshaller = DistributionUnmarshaller.Instance;
response.Distribution = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return;
}
}
return;
}
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDenied"))
{
return new AccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("CNAMEAlreadyExists"))
{
return new CNAMEAlreadyExistsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("DistributionAlreadyExists"))
{
return new DistributionAlreadyExistsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InconsistentQuantities"))
{
return new InconsistentQuantitiesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidArgument"))
{
return new InvalidArgumentException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidDefaultRootObject"))
{
return new InvalidDefaultRootObjectException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidErrorCode"))
{
return new InvalidErrorCodeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidForwardCookies"))
{
return new InvalidForwardCookiesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidGeoRestrictionParameter"))
{
return new InvalidGeoRestrictionParameterException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidHeadersForS3Origin"))
{
return new InvalidHeadersForS3OriginException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidLocationCode"))
{
return new InvalidLocationCodeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidOriginAccessIdentity"))
{
return new InvalidOriginAccessIdentityException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidOrigin"))
{
return new InvalidOriginException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidProtocolSettings"))
{
return new InvalidProtocolSettingsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRelativePath"))
{
return new InvalidRelativePathException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequiredProtocol"))
{
return new InvalidRequiredProtocolException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidResponseCode"))
{
return new InvalidResponseCodeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidViewerCertificate"))
{
return new InvalidViewerCertificateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("MissingBody"))
{
return new MissingBodyException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchOrigin"))
{
return new NoSuchOriginException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyCacheBehaviors"))
{
return new TooManyCacheBehaviorsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyCertificates"))
{
return new TooManyCertificatesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyCookieNamesInWhiteList"))
{
return new TooManyCookieNamesInWhiteListException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyDistributionCNAMEs"))
{
return new TooManyDistributionCNAMEsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyDistributions"))
{
return new TooManyDistributionsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyHeadersInForwardedValues"))
{
return new TooManyHeadersInForwardedValuesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyOrigins"))
{
return new TooManyOriginsException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyTrustedSigners"))
{
return new TooManyTrustedSignersException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TrustedSignerDoesNotExist"))
{
return new TrustedSignerDoesNotExistException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonCloudFrontException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static CreateDistributionResponseUnmarshaller _instance = new CreateDistributionResponseUnmarshaller();
internal static CreateDistributionResponseUnmarshaller GetInstance()
{
return _instance;
}
public static CreateDistributionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 57.534884 | 184 | 0.67502 |
[
"Apache-2.0"
] |
ermshiperete/aws-sdk-net
|
AWSSDK_DotNet35/Amazon.CloudFront/Model/Internal/MarshallTransformations/CreateDistributionResponseUnmarshaller.cs
| 12,370 |
C#
|
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using Silk.NET.Core.Attributes;
#pragma warning disable 1591
namespace Silk.NET.Direct3D12
{
[NativeName("Name", "D3D12_LIFETIME_STATE")]
public enum LifetimeState : int
{
[NativeName("Name", "D3D12_LIFETIME_STATE_IN_USE")]
LifetimeStateInUse = 0x0,
[NativeName("Name", "D3D12_LIFETIME_STATE_NOT_IN_USE")]
LifetimeStateNotInUse = 0x1,
}
}
| 24.26087 | 63 | 0.695341 |
[
"MIT"
] |
ThomasMiz/Silk.NET
|
src/Microsoft/Silk.NET.Direct3D12/Enums/LifetimeState.gen.cs
| 558 |
C#
|
using System;
/*
* $Id: ColorDetails.cs,v 1.3 2008/05/13 11:25:17 psoares33 Exp $
*
*
* Copyright 2001, 2002 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
namespace RazorPDF.Legacy.Text.Pdf {
/** Each spotcolor in the document will have an instance of this class
*
* @author Phillip Pan ([email protected])
*/
public class ColorDetails {
/** The indirect reference to this color
*/
PdfIndirectReference indirectReference;
/** The color name that appears in the document body stream
*/
PdfName colorName;
/** The color
*/
PdfSpotColor spotcolor;
/** Each spot color used in a document has an instance of this class.
* @param colorName the color name
* @param indirectReference the indirect reference to the font
* @param scolor the <CODE>PDfSpotColor</CODE>
*/
internal ColorDetails(PdfName colorName, PdfIndirectReference indirectReference, PdfSpotColor scolor) {
this.colorName = colorName;
this.indirectReference = indirectReference;
this.spotcolor = scolor;
}
/** Gets the indirect reference to this color.
* @return the indirect reference to this color
*/
internal PdfIndirectReference IndirectReference {
get {
return indirectReference;
}
}
/** Gets the color name as it appears in the document body.
* @return the color name
*/
internal PdfName ColorName {
get {
return colorName;
}
}
/** Gets the <CODE>SpotColor</CODE> object.
* @return the <CODE>PdfSpotColor</CODE>
*/
internal PdfObject GetSpotColor(PdfWriter writer) {
return spotcolor.GetSpotObject(writer);
}
}
}
| 40 | 111 | 0.681542 |
[
"Apache-2.0"
] |
DesignLiquido/RazorPDF2
|
RazorPDF.Legacy/Text/Pdf/ColorDetails.cs
| 4,280 |
C#
|
using System;
namespace SmartStore.Web.Framework.UI
{
public enum BadgeStyle
{
Default,
Primary,
Success,
Info,
Warning,
Danger
}
public enum BootstrapVersion
{
V2 = 2,
V4 = 4
}
}
| 10.761905 | 38 | 0.59292 |
[
"MIT"
] |
jenmcquade/csharp-snippets
|
SmartStoreNET-3.x/src/Presentation/SmartStore.Web.Framework/UI/Components/Enums.cs
| 228 |
C#
|
namespace ReadInLargeCollection
{
using System;
public class Product : IComparable<Product>
{
public Product(string name, decimal price)
{
this.Name = name;
this.Price = price;
}
public string Name { get; set; }
public decimal Price { get; set; }
public int CompareTo(Product other)
{
return this.Price.CompareTo(other.Price);
}
public override string ToString()
{
return this.Name + " -> " + this.Price;
}
}
}
| 20.321429 | 53 | 0.525483 |
[
"MIT"
] |
GeorgiPetrovGH/TelerikAcademy
|
12.Data-Structures-and-Algorithms/05. Advanced-Data-Structures/Advanced-Data-Structures/ReadInLargeCollection/Product.cs
| 571 |
C#
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
/// <summary>
/// CA1054: Uri parameters should not be strings
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class UriParametersShouldNotBeStringsAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1054";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.UriParametersShouldNotBeStringsTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.UriParametersShouldNotBeStringsMessage), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.UriParametersShouldNotBeStringsDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessage,
DiagnosticCategory.Design,
RuleLevel.Disabled,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
// this is stateless analyzer, can run concurrently
context.EnableConcurrentExecution();
// this has no meaning on running on generated code which user can't control
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(c =>
{
var @string = c.Compilation.GetSpecialType(SpecialType.System_String);
var uri = c.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemUri);
var attribute = c.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
if (@string == null || uri == null || attribute == null)
{
// we don't have required types
return;
}
var analyzer = new PerCompilationAnalyzer(@string, uri, attribute);
c.RegisterSymbolAction(analyzer.Analyze, SymbolKind.Method);
});
}
private class PerCompilationAnalyzer
{
private readonly INamedTypeSymbol _string;
private readonly INamedTypeSymbol _uri;
private readonly INamedTypeSymbol _attribute;
public PerCompilationAnalyzer(INamedTypeSymbol @string, INamedTypeSymbol uri, INamedTypeSymbol attribute)
{
_string = @string;
_uri = uri;
_attribute = attribute;
}
public void Analyze(SymbolAnalysisContext context)
{
var method = (IMethodSymbol)context.Symbol;
// check basic stuff that FxCop checks.
if (method.IsOverride || method.IsFromMscorlib(context.Compilation))
{
// Methods defined within mscorlib are excluded from this rule,
// since mscorlib cannot depend on System.Uri, which is defined
// in System.dll
return;
}
if (!context.Options.MatchesConfiguredVisibility(Rule, method, context.Compilation, context.CancellationToken))
{
// only apply to methods that are exposed outside by default
return;
}
var stringParameters = method.Parameters.GetParametersOfType(_string);
if (!stringParameters.Any())
{
// no string parameter. not interested.
return;
}
// now do cheap string check whether those string parameter contains uri word list we are looking for.
if (!stringParameters.ParameterNamesContainUriWordSubstring(context.CancellationToken))
{
// no string parameter that contains what we are looking for.
return;
}
if (method.ContainingType.DerivesFrom(_attribute, baseTypesOnly: true))
{
// Attributes cannot accept System.Uri objects as positional or optional attributes
return;
}
// now we do more expensive word parsing to find exact parameter that contains url in parameter name
var indices = method.GetParameterIndices(stringParameters.GetParametersThatContainUriWords(context.CancellationToken), context.CancellationToken);
var overloads = method.ContainingType.GetMembers(method.Name).OfType<IMethodSymbol>();
foreach (var index in indices)
{
var overload = method.GetMatchingOverload(overloads, index, _uri, context.CancellationToken);
if (overload == null)
{
var parameter = method.Parameters[index];
context.ReportDiagnostic(parameter.CreateDiagnostic(Rule, parameter.Name, method.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
}
}
}
}
| 52.796875 | 302 | 0.605949 |
[
"Apache-2.0"
] |
AndrewZu1337/roslyn-analyzers
|
src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UriParametersShouldNotBeStrings.cs
| 6,758 |
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: This Class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
namespace System.Globalization
{
public partial class TextInfo : ICloneable, IDeserializationCallback
{
private enum Tristate : byte
{
NotInitialized,
True,
False,
}
private string _listSeparator;
private bool _isReadOnly = false;
/* _cultureName is the name of the creating culture.
_cultureData is the data that backs this class.
_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
In the desktop, when we call the sorting dll, it doesn't
know how to resolve custom locle names to sort ids so we have to have already resolved this.
*/
private readonly string _cultureName; // Name of the culture that created this text info
private readonly CultureData _cultureData; // Data record for the culture that made us, not for this textinfo
private readonly string _textInfoName; // Name of the text info we're using (ie: _cultureData.STEXTINFO)
private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized;
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
private readonly bool _invariantMode = GlobalizationMode.Invariant;
// Invariant text info
internal static TextInfo Invariant
{
get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
return s_Invariant;
}
}
internal volatile static TextInfo s_Invariant;
//////////////////////////////////////////////////////////////////////////
////
//// TextInfo Constructors
////
//// Implements CultureInfo.TextInfo.
////
//////////////////////////////////////////////////////////////////////////
internal TextInfo(CultureData cultureData)
{
// This is our primary data source, we don't need most of the rest of this
_cultureData = cultureData;
_cultureName = _cultureData.CultureName;
_textInfoName = _cultureData.STEXTINFO;
FinishInitialization();
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
throw new PlatformNotSupportedException();
}
public virtual int ANSICodePage => _cultureData.IDEFAULTANSICODEPAGE;
public virtual int OEMCodePage => _cultureData.IDEFAULTOEMCODEPAGE;
public virtual int MacCodePage => _cultureData.IDEFAULTMACCODEPAGE;
public virtual int EBCDICCodePage => _cultureData.IDEFAULTEBCDICCODEPAGE;
// Just use the LCID from our text info name
public int LCID => CultureInfo.GetCultureInfo(_textInfoName).LCID;
public string CultureName => _textInfoName;
public bool IsReadOnly => _isReadOnly;
//////////////////////////////////////////////////////////////////////////
////
//// Clone
////
//// Is the implementation of ICloneable.
////
//////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((TextInfo)o).SetReadOnlyState(false);
return o;
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
if (textInfo.IsReadOnly) { return textInfo; }
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
return clonedTextInfo;
}
private void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
////////////////////////////////////////////////////////////////////////
//
// ListSeparator
//
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
public virtual string ListSeparator
{
get
{
if (_listSeparator == null)
{
_listSeparator = _cultureData.SLIST;
}
return _listSeparator;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
VerifyWritable();
_listSeparator = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// ToLower
//
// Converts the character or string to lower case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToLower(char c)
{
if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToLowerAsciiInvariant(c);
}
return ChangeCase(c, toUpper: false);
}
public unsafe virtual string ToLower(string str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
if (_invariantMode)
{
return ToLowerAsciiInvariant(str);
}
return ChangeCase(str, toUpper: false);
}
private unsafe char ChangeCase(char c, bool toUpper)
{
Debug.Assert(!_invariantMode);
char dst = default;
ChangeCase(&c, 1, &dst, 1, toUpper);
return dst;
}
private unsafe string ChangeCase(string source, bool toUpper)
{
Debug.Assert(!_invariantMode);
Debug.Assert(source != null);
// If the string is empty, we're done.
if (source.Length == 0)
{
return string.Empty;
}
int sourcePos = 0;
string result = null;
// If this culture's casing for ASCII is the same as invariant, try to take
// a fast path that'll work in managed code and ASCII rather than calling out
// to the OS for culture-aware casing.
if (IsAsciiCasingSameAsInvariant)
{
if (toUpper)
{
// Loop through each character.
for (sourcePos = 0; sourcePos < source.Length; sourcePos++)
{
// If the character is lower-case, we're going to need to allocate a string.
char c = source[sourcePos];
if ((uint)(c - 'a') <= 'z' - 'a')
{
// Allocate the result string.
result = string.FastAllocateString(source.Length);
fixed (char* pResult = result)
{
// Store all of characters examined thus far.
if (sourcePos > 0)
{
source.AsSpan(0, sourcePos).CopyTo(new Span<char>(pResult, sourcePos));
}
// And store the current character, upper-cased.
char* d = pResult + sourcePos;
*d++ = (char)(c & ~0x20);
sourcePos++;
// Then continue looping through the remainder of the characters. If we hit
// a non-ASCII character, bail to fall back to culture-aware casing.
for (; sourcePos < source.Length; sourcePos++)
{
c = source[sourcePos];
if ((uint)(c - 'a') <= 'z' - 'a')
{
*d++ = (char)(c & ~0x20);
}
else if (!IsAscii(c))
{
break;
}
else
{
*d++ = c;
}
}
}
break;
}
else if (!IsAscii(c))
{
// The character isn't ASCII; bail to fall back to a culture-aware casing.
break;
}
}
}
else // toUpper == false
{
// Loop through each character.
for (sourcePos = 0; sourcePos < source.Length; sourcePos++)
{
// If the character is upper-case, we're going to need to allocate a string.
char c = source[sourcePos];
if ((uint)(c - 'A') <= 'Z' - 'A')
{
// Allocate the result string.
result = string.FastAllocateString(source.Length);
fixed (char* pResult = result)
{
// Store all of characters examined thus far.
if (sourcePos > 0)
{
source.AsSpan(0, sourcePos).CopyTo(new Span<char>(pResult, sourcePos));
}
// And store the current character, upper-cased.
char* d = pResult + sourcePos;
*d++ = (char)(c | 0x20);
sourcePos++;
// Then continue looping through the remainder of the characters. If we hit
// a non-ASCII character, bail to fall back to culture-aware casing.
for (; sourcePos < source.Length; sourcePos++)
{
c = source[sourcePos];
if ((uint)(c - 'A') <= 'Z' - 'A')
{
*d++ = (char)(c | 0x20);
}
else if (!IsAscii(c))
{
break;
}
else
{
*d++ = c;
}
}
}
break;
}
else if (!IsAscii(c))
{
// The character isn't ASCII; bail to fall back to a culture-aware casing.
break;
}
}
}
// If we successfully iterated through all of the characters, we didn't need to fall back
// to culture-aware casing. In that case, if we allocated a result string, use it, otherwise
// just return the original string, as no modifications were necessary.
if (sourcePos == source.Length)
{
return result ?? source;
}
}
// Falling back to culture-aware casing. Make sure we have a result string to write into.
// If we need to allocate the result string, we'll also need to copy over to it any
// characters already examined.
if (result == null)
{
result = string.FastAllocateString(source.Length);
if (sourcePos > 0)
{
fixed (char* pResult = result)
{
source.AsSpan(0, sourcePos).CopyTo(new Span<char>(pResult, sourcePos));
}
}
}
// Do the casing operation on everything after what we already processed.
fixed (char* pSource = source)
{
fixed (char* pResult = result)
{
ChangeCase(pSource + sourcePos, source.Length - sourcePos, pResult + sourcePos, result.Length - sourcePos, toUpper);
}
}
return result;
}
internal unsafe void ChangeCase(ReadOnlySpan<char> source, Span<char> destination, bool toUpper)
{
Debug.Assert(!_invariantMode);
Debug.Assert(destination.Length >= source.Length);
if (source.IsEmpty)
{
return;
}
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pResult = &MemoryMarshal.GetReference(destination))
{
if (IsAsciiCasingSameAsInvariant)
{
int length = 0;
char* a = pSource, b = pResult;
if (toUpper)
{
while (length < source.Length && *a < 0x80)
{
*b++ = ToUpperAsciiInvariant(*a++);
length++;
}
}
else
{
while (length < source.Length && *a < 0x80)
{
*b++ = ToLowerAsciiInvariant(*a++);
length++;
}
}
if (length != source.Length)
{
ChangeCase(a, source.Length - length, b, destination.Length - length, toUpper);
}
}
else
{
ChangeCase(pSource, source.Length, pResult, destination.Length, toUpper);
}
}
}
private static unsafe string ToLowerAsciiInvariant(string s)
{
if (s.Length == 0)
{
return string.Empty;
}
fixed (char* pSource = s)
{
int i = 0;
while (i < s.Length)
{
if ((uint)(pSource[i] - 'A') <= (uint)('Z' - 'A'))
{
break;
}
i++;
}
if (i >= s.Length)
{
return s;
}
string result = string.FastAllocateString(s.Length);
fixed (char* pResult = result)
{
for (int j = 0; j < i; j++)
{
pResult[j] = pSource[j];
}
pResult[i] = (char)(pSource[i] | 0x20);
i++;
while (i < s.Length)
{
pResult[i] = ToLowerAsciiInvariant(pSource[i]);
i++;
}
}
return result;
}
}
internal static void ToLowerAsciiInvariant(ReadOnlySpan<char> source, Span<char> destination)
{
Debug.Assert(destination.Length >= source.Length);
for (int i = 0; i < source.Length; i++)
{
destination[i] = ToLowerAsciiInvariant(source[i]);
}
}
private static unsafe string ToUpperAsciiInvariant(string s)
{
if (s.Length == 0)
{
return string.Empty;
}
fixed (char* pSource = s)
{
int i = 0;
while (i < s.Length)
{
if ((uint)(pSource[i] - 'a') <= (uint)('z' - 'a'))
{
break;
}
i++;
}
if (i >= s.Length)
{
return s;
}
string result = string.FastAllocateString(s.Length);
fixed (char* pResult = result)
{
for (int j = 0; j < i; j++)
{
pResult[j] = pSource[j];
}
pResult[i] = (char)(pSource[i] & ~0x20);
i++;
while (i < s.Length)
{
pResult[i] = ToUpperAsciiInvariant(pSource[i]);
i++;
}
}
return result;
}
}
internal static void ToUpperAsciiInvariant(ReadOnlySpan<char> source, Span<char> destination)
{
Debug.Assert(destination.Length >= source.Length);
for (int i = 0; i < source.Length; i++)
{
destination[i] = ToUpperAsciiInvariant(source[i]);
}
}
private static char ToLowerAsciiInvariant(char c)
{
if ((uint)(c - 'A') <= (uint)('Z' - 'A'))
{
c = (char)(c | 0x20);
}
return c;
}
////////////////////////////////////////////////////////////////////////
//
// ToUpper
//
// Converts the character or string to upper case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToUpper(char c)
{
if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToUpperAsciiInvariant(c);
}
return ChangeCase(c, toUpper: true);
}
public unsafe virtual string ToUpper(string str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
if (_invariantMode)
{
return ToUpperAsciiInvariant(str);
}
return ChangeCase(str, toUpper: true);
}
internal static char ToUpperAsciiInvariant(char c)
{
if ((uint)(c - 'a') <= (uint)('z' - 'a'))
{
c = (char)(c & ~0x20);
}
return c;
}
private static bool IsAscii(char c)
{
return c < 0x80;
}
private bool IsAsciiCasingSameAsInvariant
{
get
{
if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized)
{
_isAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0 ? Tristate.True : Tristate.False;
}
return _isAsciiCasingSameAsInvariant == Tristate.True;
}
}
// IsRightToLeft
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
public bool IsRightToLeft => _cultureData.IsRightToLeft;
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
if (that != null)
{
return CultureName.Equals(that.CultureName);
}
return false;
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return CultureName.GetHashCode();
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
public override string ToString()
{
return "TextInfo - " + _cultureData.CultureName;
}
//
// Titlecasing:
// -----------
// Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter
// and the rest of the letters are lowercase. The choice of which words to titlecase in headings
// and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor"
// is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased.
// In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von"
// are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor."
//
// Moreover, the determination of what actually constitutes a word is language dependent, and this can
// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example
// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
//
public unsafe string ToTitleCase(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (str.Length == 0)
{
return str;
}
StringBuilder result = new StringBuilder();
string lowercaseData = null;
// Store if the current culture is Dutch (special case)
bool isDutchCulture = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase);
for (int i = 0; i < str.Length; i++)
{
UnicodeCategory charType;
int charLen;
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (char.CheckLetter(charType))
{
// Special case to check for Dutch specific titlecasing with "IJ" characters
// at the beginning of a word
if (isDutchCulture && i < str.Length - 1 && (str[i] == 'i' || str[i] == 'I') && (str[i+1] == 'j' || str[i+1] == 'J'))
{
result.Append("IJ");
i += 2;
}
else
{
// Do the titlecasing for the first character of the word.
i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
}
//
// Convert the characters until the end of the this word
// to lowercase.
//
int lowercaseStart = i;
//
// Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc)
// This is in line with Word 2000 behavior of titlecasing.
//
bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
// Use a loop to find all of the other letters following this letter.
while (i < str.Length)
{
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (IsLetterCategory(charType))
{
if (charType == UnicodeCategory.LowercaseLetter)
{
hasLowerCase = true;
}
i += charLen;
}
else if (str[i] == '\'')
{
i++;
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
}
else
{
result.Append(str, lowercaseStart, i - lowercaseStart);
}
lowercaseStart = i;
hasLowerCase = true;
}
else if (!IsWordSeparator(charType))
{
// This category is considered to be part of the word.
// This is any category that is marked as false in wordSeprator array.
i+= charLen;
}
else
{
// A word separator. Break out of the loop.
break;
}
}
int count = i - lowercaseStart;
if (count > 0)
{
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, count);
}
else
{
result.Append(str, lowercaseStart, count);
}
}
if (i < str.Length)
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
else
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
return result.ToString();
}
private static int AddNonLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
result.Append(input[inputIndex++]);
result.Append(input[inputIndex]);
}
else
{
result.Append(input[inputIndex]);
}
return inputIndex;
}
private int AddTitlecaseLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// for surrogate pairs do a ToUpper operation on the substring
ReadOnlySpan<char> src = input.AsSpan(inputIndex, 2);
if (_invariantMode)
{
result.Append(src); // surrogate pair in invariant mode, so changing case is a nop
}
else
{
Span<char> dst = stackalloc char[2];
ChangeCase(src, dst, toUpper: true);
result.Append(dst);
}
inputIndex++;
}
else
{
switch (input[inputIndex])
{
//
// For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
case (char) 0x01C4: // DZ with Caron -> Dz with Caron
case (char) 0x01C5: // Dz with Caron -> Dz with Caron
case (char) 0x01C6: // dz with Caron -> Dz with Caron
result.Append((char) 0x01C5);
break;
case (char) 0x01C7: // LJ -> Lj
case (char) 0x01C8: // Lj -> Lj
case (char) 0x01C9: // lj -> Lj
result.Append((char) 0x01C8);
break;
case (char) 0x01CA: // NJ -> Nj
case (char) 0x01CB: // Nj -> Nj
case (char) 0x01CC: // nj -> Nj
result.Append((char) 0x01CB);
break;
case (char) 0x01F1: // DZ -> Dz
case (char) 0x01F2: // Dz -> Dz
case (char) 0x01F3: // dz -> Dz
result.Append((char) 0x01F2);
break;
default:
result.Append(ToUpper(input[inputIndex]));
break;
}
}
return inputIndex;
}
//
// Used in ToTitleCase():
// When we find a starting letter, the following array decides if a category should be
// considered as word seprator or not.
//
private const int c_wordSeparatorMask =
/* false */ (0 << 0) | // UppercaseLetter = 0,
/* false */ (0 << 1) | // LowercaseLetter = 1,
/* false */ (0 << 2) | // TitlecaseLetter = 2,
/* false */ (0 << 3) | // ModifierLetter = 3,
/* false */ (0 << 4) | // OtherLetter = 4,
/* false */ (0 << 5) | // NonSpacingMark = 5,
/* false */ (0 << 6) | // SpacingCombiningMark = 6,
/* false */ (0 << 7) | // EnclosingMark = 7,
/* false */ (0 << 8) | // DecimalDigitNumber = 8,
/* false */ (0 << 9) | // LetterNumber = 9,
/* false */ (0 << 10) | // OtherNumber = 10,
/* true */ (1 << 11) | // SpaceSeparator = 11,
/* true */ (1 << 12) | // LineSeparator = 12,
/* true */ (1 << 13) | // ParagraphSeparator = 13,
/* true */ (1 << 14) | // Control = 14,
/* true */ (1 << 15) | // Format = 15,
/* false */ (0 << 16) | // Surrogate = 16,
/* false */ (0 << 17) | // PrivateUse = 17,
/* true */ (1 << 18) | // ConnectorPunctuation = 18,
/* true */ (1 << 19) | // DashPunctuation = 19,
/* true */ (1 << 20) | // OpenPunctuation = 20,
/* true */ (1 << 21) | // ClosePunctuation = 21,
/* true */ (1 << 22) | // InitialQuotePunctuation = 22,
/* true */ (1 << 23) | // FinalQuotePunctuation = 23,
/* true */ (1 << 24) | // OtherPunctuation = 24,
/* true */ (1 << 25) | // MathSymbol = 25,
/* true */ (1 << 26) | // CurrencySymbol = 26,
/* true */ (1 << 27) | // ModifierSymbol = 27,
/* true */ (1 << 28) | // OtherSymbol = 28,
/* false */ (0 << 29); // OtherNotAssigned = 29;
private static bool IsWordSeparator(UnicodeCategory category)
{
return (c_wordSeparatorMask & (1 << (int) category)) != 0;
}
private static bool IsLetterCategory(UnicodeCategory uc)
{
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.TitlecaseLetter
|| uc == UnicodeCategory.ModifierLetter
|| uc == UnicodeCategory.OtherLetter);
}
}
}
| 38.5 | 163 | 0.411379 |
[
"MIT"
] |
AaronRobinsonMSFT/coreclr
|
src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs
| 35,189 |
C#
|
namespace CommandsService.Models
{
using System.ComponentModel.DataAnnotations;
public class Command
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public string HowTo { get; set; }
[Required]
public string CommandLine { get; set; }
[Required]
public int PlatformId { get; set; }
public Platform Platform { get; set; }
}
}
| 19.727273 | 48 | 0.564516 |
[
"Unlicense"
] |
dmishne/.NET-Microservices-Course
|
CommandsService/Models/Command.cs
| 434 |
C#
|
using System;
using System.Text;
namespace Abstraction
{
public abstract class Figure : IFigure
{
public Figure()
{
}
public abstract double CalcSurface();
public abstract double CalcPerimeter();
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.AppendFormat("I am {0}", this.GetType().Name).AppendLine();
result.AppendFormat("My area is {0:f2}. My perimeter is {1:f2}", this.CalcSurface(), this.CalcPerimeter());
return result.ToString();
}
}
}
| 22.740741 | 119 | 0.587948 |
[
"MIT"
] |
aleksandra992/CSharp
|
High Quality Code/High-quality Classes Homework/Abstraction/Figure.cs
| 616 |
C#
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Elasticsearch.Net;
namespace Nest
{
public partial interface IElasticClient
{
/// <summary>
/// The update API allows to update a document based on a script provided.
/// <para>
/// The operation gets the document (collocated with the shard) from the index, runs the script
/// (with optional script language and parameters), and index back the result
/// (also allows to delete, or ignore the operation).
/// </para>
/// <para>It uses versioning to make sure no updates have happened during the "get" and "reindex".</para>
/// <para> </para>
/// http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-update.html
/// </summary>
/// <typeparam name="TDocument">The type to describe the document to be updated</typeparam>
/// <param name="selector">a descriptor that describes the update operation</param>
UpdateResponse<TDocument> Update<TDocument>(DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TDocument>, IUpdateRequest<TDocument, TDocument>> selector
) where TDocument : class;
/// <inheritdoc />
UpdateResponse<TDocument> Update<TDocument>(IUpdateRequest<TDocument, TDocument> request) where TDocument : class;
/// <inheritdoc />
UpdateResponse<TDocument> Update<TDocument, TPartialDocument>(DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TPartialDocument>, IUpdateRequest<TDocument, TPartialDocument>> selector
)
where TDocument : class
where TPartialDocument : class;
/// <inheritdoc />
UpdateResponse<TDocument> Update<TDocument, TPartialDocument>(IUpdateRequest<TDocument, TPartialDocument> request)
where TDocument : class
where TPartialDocument : class;
/// <inheritdoc />
Task<UpdateResponse<TDocument>> UpdateAsync<TDocument>(
DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TDocument>, IUpdateRequest<TDocument, TDocument>> selector,
CancellationToken cancellationToken = default
) where TDocument : class;
/// <inheritdoc />
Task<UpdateResponse<TDocument>> UpdateAsync<TDocument>(
IUpdateRequest<TDocument, TDocument> request,
CancellationToken ct = default
) where TDocument : class;
/// <inheritdoc />
Task<UpdateResponse<TDocument>> UpdateAsync<TDocument, TPartialDocument>(
DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TPartialDocument>, IUpdateRequest<TDocument, TPartialDocument>> selector,
CancellationToken cancellationToken = default
)
where TDocument : class
where TPartialDocument : class;
/// <inheritdoc />
Task<UpdateResponse<TDocument>> UpdateAsync<TDocument, TPartialDocument>(
IUpdateRequest<TDocument, TPartialDocument> request,
CancellationToken ct = default
)
where TDocument : class
where TPartialDocument : class;
}
public partial class ElasticClient
{
/// <inheritdoc />
public UpdateResponse<TDocument> Update<TDocument>(DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TDocument>, IUpdateRequest<TDocument, TDocument>> selector
) where TDocument : class =>
Update<TDocument, TDocument>(documentPath, selector);
/// <inheritdoc />
public UpdateResponse<TDocument> Update<TDocument>(IUpdateRequest<TDocument, TDocument> request) where TDocument : class =>
Update<TDocument, TDocument>(request);
/// <inheritdoc />
public UpdateResponse<TDocument> Update<TDocument, TPartialDocument>(DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TPartialDocument>, IUpdateRequest<TDocument, TPartialDocument>> selector
)
where TDocument : class
where TPartialDocument : class =>
Update(selector?.Invoke(new UpdateDescriptor<TDocument, TPartialDocument>(
documentPath.Document, documentPath.Self.Index, documentPath.Self.Id
)));
/// <inheritdoc />
public UpdateResponse<TDocument> Update<TDocument, TPartialDocument>(IUpdateRequest<TDocument, TPartialDocument> request)
where TDocument : class
where TPartialDocument : class =>
DoRequest<IUpdateRequest<TDocument, TPartialDocument>, UpdateResponse<TDocument>>(request, request.RequestParameters);
/// <inheritdoc />
public Task<UpdateResponse<TDocument>> UpdateAsync<TDocument>(
DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TDocument>, IUpdateRequest<TDocument, TDocument>> selector,
CancellationToken cancellationToken = default
)
where TDocument : class =>
UpdateAsync<TDocument, TDocument>(documentPath, selector, cancellationToken);
/// <inheritdoc />
public Task<UpdateResponse<TDocument>> UpdateAsync<TDocument>(
IUpdateRequest<TDocument, TDocument> request,
CancellationToken ct = default
)
where TDocument : class =>
UpdateAsync<TDocument, TDocument>(request, ct);
/// <inheritdoc />
public Task<UpdateResponse<TDocument>> UpdateAsync<TDocument, TPartialDocument>(
DocumentPath<TDocument> documentPath,
Func<UpdateDescriptor<TDocument, TPartialDocument>, IUpdateRequest<TDocument, TPartialDocument>> selector,
CancellationToken cancellationToken = default
)
where TDocument : class
where TPartialDocument : class =>
UpdateAsync(selector?.Invoke(new UpdateDescriptor<TDocument, TPartialDocument>(
documentPath.Document, documentPath.Self.Index, documentPath.Self.Id
)), cancellationToken);
/// <inheritdoc />
public Task<UpdateResponse<TDocument>> UpdateAsync<TDocument, TPartialDocument>(
IUpdateRequest<TDocument, TPartialDocument> request,
CancellationToken ct = default
)
where TDocument : class
where TPartialDocument : class =>
DoRequestAsync<IUpdateRequest<TDocument, TPartialDocument>, UpdateResponse<TDocument>>(request, request.RequestParameters, ct);
}
}
| 41.184397 | 130 | 0.762528 |
[
"Apache-2.0"
] |
591094733/elasticsearch-net
|
src/Nest/Document/Single/Update/ElasticClient-Update.cs
| 5,811 |
C#
|
#pragma checksum "..\..\..\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "1AA506F0524D97AD99CB1EA5F5EA6592"
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.18408
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms.Integration;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace I_RayTracer {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
#line 4 "..\..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
I_RayTracer.App app = new I_RayTracer.App();
app.InitializeComponent();
app.Run();
}
}
}
| 30.732394 | 113 | 0.608616 |
[
"MIT"
] |
soyleon/RayTracingInWirelessSignal
|
I-RayTracer/I-RayTracer/obj/x64/Debug/App.g.cs
| 2,290 |
C#
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Dfm
{
using System;
using System.Text.RegularExpressions;
using Microsoft.DocAsCode.MarkdownLite;
using Microsoft.DocAsCode.MarkdownLite.Matchers;
public class DfmNoteBlockRule : IMarkdownRule
{
private static readonly Matcher _NoteMatcher =
Matcher.WhiteSpacesOrEmpty +
"[!" +
(
Matcher.CaseInsensitiveString("note") |
Matcher.CaseInsensitiveString("warning") |
Matcher.CaseInsensitiveString("tip") |
Matcher.CaseInsensitiveString("important") |
Matcher.CaseInsensitiveString("caution")
).ToGroup("notetype") +
']' +
Matcher.WhiteSpacesOrEmpty +
Matcher.NewLine.RepeatAtLeast(0);
private static readonly Regex _dfmNoteRegex = new Regex(@"^(?<rawmarkdown> *\[\!(?<notetype>(NOTE|WARNING|TIP|IMPORTANT|CAUTION))\] *\n?)(?<text>.*)(?:\n|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase, TimeSpan.FromSeconds(10));
public virtual string Name => "DfmNote";
[Obsolete]
public virtual Regex DfmNoteRegex => _dfmNoteRegex;
public virtual Matcher NoteMatcher => _NoteMatcher;
public virtual IMarkdownToken TryMatch(IMarkdownParser parser, IMarkdownParsingContext context)
{
if (!parser.Context.Variables.ContainsKey(MarkdownBlockContext.IsBlockQuote) || !(bool)parser.Context.Variables[MarkdownBlockContext.IsBlockQuote])
{
return null;
}
if (DfmNoteRegex != _dfmNoteRegex || parser.Options.LegacyMode)
{
return TryMatchOld(parser, context);
}
var match = context.Match(NoteMatcher);
if (match?.Length > 0)
{
var sourceInfo = context.Consume(match.Length);
return new DfmNoteBlockToken(this, parser.Context, match["notetype"].GetValue(), sourceInfo.Markdown, sourceInfo);
}
return null;
}
private IMarkdownToken TryMatchOld(IMarkdownParser parser, IMarkdownParsingContext context)
{
var match = DfmNoteRegex.Match(context.CurrentMarkdown);
if (match.Length == 0)
{
return null;
}
var sourceInfo = context.Consume(match.Groups["rawmarkdown"].Length);
return new DfmNoteBlockToken(this, parser.Context, match.Groups["notetype"].Value, match.Groups["rawmarkdown"].Value, sourceInfo);
}
}
}
| 40.382353 | 242 | 0.619082 |
[
"MIT"
] |
brianlehr/docs-test-temp
|
src/Microsoft.DocAsCode.Dfm/Rules/DfmNoteBlockRule.cs
| 2,748 |
C#
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;
using Spect.Net.SpectrumEmu.Test.Helpers;
// ReSharper disable ArgumentsStyleStringLiteral
namespace Spect.Net.SpectrumEmu.Test.Cpu.BitOps
{
[TestClass]
public class BitOpTests0X00
{
/// <summary>
/// RLC B: 0xCB 0x00
/// </summary>
[TestMethod]
public void RLC_B_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x00 // RLC B
});
var regs = m.Cpu.Registers;
regs.B = 0x08;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC B: 0xCB 0x00
/// </summary>
[TestMethod]
public void RLC_B_SetsCarry()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x00 // RLC B
});
var regs = m.Cpu.Registers;
regs.B = 0x84;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0x09);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeTrue();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC B: 0xCB 0x00
/// </summary>
[TestMethod]
public void RLC_B_SetsZeroFlag()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x00 // RLC B
});
var regs = m.Cpu.Registers;
regs.B = 0x00;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0x00);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeTrue();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC B: 0xCB 0x00
/// </summary>
[TestMethod]
public void RLC_B_SetsSignFlag()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x00 // RLC B
});
var regs = m.Cpu.Registers;
regs.B = 0xC0;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0x81);
regs.SFlag.ShouldBeTrue();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeTrue();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC C: 0xCB 0x01
/// </summary>
[TestMethod]
public void RLC_C_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x01 // RLC C
});
var regs = m.Cpu.Registers;
regs.C = 0x08;
// --- Act
m.Run();
// --- Assert
regs.C.ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, C");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC D: 0xCB 0x02
/// </summary>
[TestMethod]
public void RLC_D_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x02 // RLC D
});
var regs = m.Cpu.Registers;
regs.D = 0x08;
// --- Act
m.Run();
// --- Assert
regs.D.ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, D");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC E: 0xCB 0x03
/// </summary>
[TestMethod]
public void RLC_E_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x03 // RLC E
});
var regs = m.Cpu.Registers;
regs.E = 0x08;
// --- Act
m.Run();
// --- Assert
regs.E.ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, E");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC H: 0xCB 0x04
/// </summary>
[TestMethod]
public void RLC_H_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x04 // RLC H
});
var regs = m.Cpu.Registers;
regs.H = 0x08;
// --- Act
m.Run();
// --- Assert
regs.H.ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, H");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC L: 0xCB 0x05
/// </summary>
[TestMethod]
public void RLC_L_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x05 // RLC L
});
var regs = m.Cpu.Registers;
regs.L = 0x08;
// --- Act
m.Run();
// --- Assert
regs.L.ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, L");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RLC (HL): 0xCB 0x06
/// </summary>
[TestMethod]
public void RLC_HLi_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x06 // RLC (HL)
});
var regs = m.Cpu.Registers;
regs.HL = 0x1000;
m.Memory[regs.HL] = 0x08;
// --- Act
m.Run();
// --- Assert
m.Memory[regs.HL].ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F");
m.ShouldKeepMemory(except: "1000");
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(15L);
}
/// <summary>
/// RLC A: 0xCB 0x07
/// </summary>
[TestMethod]
public void RLC_A_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x07 // RLC A
});
var regs = m.Cpu.Registers;
regs.A = 0x08;
// --- Act
m.Run();
// --- Assert
regs.A.ShouldBe((byte)0x10);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, A");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC B: 0xCB 0x08
/// </summary>
[TestMethod]
public void RRC_B_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x08 // RRC B
});
var regs = m.Cpu.Registers;
regs.B = 0x08;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC B: 0xCB 0x08
/// </summary>
[TestMethod]
public void RRC_B_SetsCarry()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x08 // RRC B
});
var regs = m.Cpu.Registers;
regs.B = 0x85;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0xC2);
regs.SFlag.ShouldBeTrue();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeTrue();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC B: 0xCB 0x08
/// </summary>
[TestMethod]
public void RRC_B_SetsZeroFlag()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x00 // RLC B
});
var regs = m.Cpu.Registers;
regs.B = 0x00;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0x00);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeTrue();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC B: 0xCB 0x08
/// </summary>
[TestMethod]
public void RRC_B_SetsSignFlag()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x08 // RRC B
});
var regs = m.Cpu.Registers;
regs.B = 0x41;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe((byte)0xA0);
regs.SFlag.ShouldBeTrue();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeTrue();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC C: 0xCB 0x09
/// </summary>
[TestMethod]
public void RRC_C_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x09 // RRC C
});
var regs = m.Cpu.Registers;
regs.C = 0x08;
// --- Act
m.Run();
// --- Assert
regs.C.ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, C");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC D: 0xCB 0x0A
/// </summary>
[TestMethod]
public void RRC_D_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x0A // RRC D
});
var regs = m.Cpu.Registers;
regs.D = 0x08;
// --- Act
m.Run();
// --- Assert
regs.D.ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, D");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC E: 0xCB 0x0B
/// </summary>
[TestMethod]
public void RRC_E_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x0B // RRC E
});
var regs = m.Cpu.Registers;
regs.E = 0x08;
// --- Act
m.Run();
// --- Assert
regs.E.ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, E");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC H: 0xCB 0x0C
/// </summary>
[TestMethod]
public void RRC_H_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x0C // RRC H
});
var regs = m.Cpu.Registers;
regs.H = 0x08;
// --- Act
m.Run();
// --- Assert
regs.H.ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, H");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC L: 0xCB 0x0D
/// </summary>
[TestMethod]
public void RRC_L_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x0D // RRC L
});
var regs = m.Cpu.Registers;
regs.L = 0x08;
// --- Act
m.Run();
// --- Assert
regs.L.ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, L");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
/// <summary>
/// RRC (HL): 0xCB 0x0E
/// </summary>
[TestMethod]
public void RRC_HLi_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x0E // RRC (HL)
});
var regs = m.Cpu.Registers;
regs.HL = 0x1000;
m.Memory[regs.HL] = 0x08;
// --- Act
m.Run();
// --- Assert
m.Memory[regs.HL].ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F");
m.ShouldKeepMemory(except: "1000");
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(15L);
}
/// <summary>
/// RRC A: 0xCB 0x0F
/// </summary>
[TestMethod]
public void RRC_A_WorksAsExpected()
{
// --- Arrange
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xCB, 0x0F // RRC A
});
var regs = m.Cpu.Registers;
regs.A = 0x08;
// --- Act
m.Run();
// --- Assert
regs.A.ShouldBe((byte)0x04);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, A");
m.ShouldKeepMemory();
regs.PC.ShouldBe((ushort)0x0002);
m.Cpu.Tacts.ShouldBe(8L);
}
}
}
| 26.877863 | 63 | 0.458961 |
[
"MIT"
] |
Dotneteer/spectnetide
|
Tests/Spect.Net.SpectrumEmu.Test/Cpu/BitOps/BitOpTests0X00.cs
| 21,128 |
C#
|
using System;
using System.Collections.Generic;
using System.Drawing;
using TNBase.Objects;
using TNBase.DataStorage;
using Microsoft.Extensions.DependencyInjection;
namespace TNBase
{
public partial class FormPrintDormantListeners
{
private readonly IServiceLayer serviceLayer = Program.ServiceProvider.GetRequiredService<IServiceLayer>();
List<Listener> theListeners = new List<Listener>();
int totalCount = 0;
int currentPageNumber = 0;
int totalPages = 0;
private void printDormantDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Font reportFont = new System.Drawing.Font("Times New Roman", 16, FontStyle.Bold);
Font reportFontSmall = new System.Drawing.Font("Times New Roman", 14);
Font reportFontSmallBold = new System.Drawing.Font("Times New Roman", 14, FontStyle.Bold);
Font reportFontSmallBoldTitles = new System.Drawing.Font("Times New Roman", 16, FontStyle.Bold);
Graphics g = e.Graphics;
int pageHeight = e.MarginBounds.Height;
g.DrawString(Settings.Default.AssociationName, reportFont, Brushes.Black, 100, 80, StringFormat.GenericTypographic);
string nowDate = null;
nowDate = System.DateTime.Now.ToString(ModuleGeneric.DATE_FORMAT);
g.DrawString("Listeners not sent/recieved for over 30 days. Current date: " + nowDate + ".", reportFontSmall, Brushes.Black, 140, 120);
if (theListeners.Count > 5) {
e.HasMorePages = true;
}
currentPageNumber = currentPageNumber + 1;
int min = Math.Min(theListeners.Count, 5);
min = min - 1;
int gap = 140;
int start = 220;
for (int value = 0; value <= min; value++) {
Listener theListener = theListeners[0];
g.DrawString(theListener.Wallet + ". " + theListener.Title + " " + theListener.Forename + " " + theListener.Surname, reportFontSmallBold, Brushes.Black, 100, start + (gap * value));
string statusStr = "";
if (theListener.Status.Equals(ListenerStates.PAUSED)) {
statusStr = "(Stopped)";
} else {
statusStr = "(No stop in place)";
}
g.DrawString(statusStr, reportFontSmallBold, Brushes.Black, 500, start + (gap * value));
string lineastr = "";
if (!(string.IsNullOrEmpty(theListener.Addr2))) {
lineastr = theListener.Addr1 + ", " + theListener.Addr2;
} else {
lineastr = theListener.Addr1;
}
string linebstr = "";
if (!(string.IsNullOrEmpty(theListener.Town))) {
linebstr = theListener.County;
if (!(string.IsNullOrEmpty(theListener.County))) {
linebstr = linebstr + ", " + theListener.County;
}
} else {
if (!(string.IsNullOrEmpty(theListener.County))) {
linebstr = theListener.County;
}
}
g.DrawString(lineastr, reportFontSmall, Brushes.Black, 150, start + (gap * value) + 25);
g.DrawString(linebstr, reportFontSmall, Brushes.Black, 150, start + (gap * value) + 50);
g.DrawString(theListener.Postcode, reportFontSmall, Brushes.Black, 150, start + (gap * value) + 75);
g.DrawString("Joined: " + theListener.Joined, reportFontSmall, Brushes.Black, 150, start + (gap * value) + 100);
g.DrawString("Tel: " + theListener.Telephone, reportFontSmall, Brushes.Black, 550, start + (gap * value) + 25);
g.DrawString("Stock: " + theListener.Stock, reportFontSmall, Brushes.Black, 550, start + (gap * value) + 50);
g.DrawString("Last In: " + theListener.LastIn, reportFontSmall, Brushes.Black, 550, start + (gap * value) + 75);
g.DrawString("Last Out: " + theListener.LastOut, reportFontSmall, Brushes.Black, 550, start + (gap * value) + 100);
theListeners.RemoveAt(0);
}
g.DrawString("Number of inactive Listeners: " + totalCount, reportFontSmallBold, Brushes.Black, 100, 950);
g.DrawString("Printed on " + System.DateTime.Now.ToString(ModuleGeneric.DATE_FORMAT), reportFontSmallBold, Brushes.Black, 550, 950);
g.DrawString("Page " + currentPageNumber + "/" + totalPages, reportFontSmallBold, Brushes.Black, 380, 970);
// VB is stupid.... have to reset this so its back when you actually print it!
if (!(e.HasMorePages)) {
SetInitial();
}
}
private void SetInitial()
{
theListeners = serviceLayer.Get1MonthDormantListeners();
totalCount = theListeners.Count;
currentPageNumber = 0;
}
// Print age analysis form.
private void printForm()
{
SetInitial();
totalPages = (int) Math.Ceiling((double) totalCount / 5);
if (totalPages == 0) {
totalPages = 1;
}
printPreview.Document = printDormantDoc;
printPreview.ClientSize = new Size(600, 600);
printPreview.ShowDialog();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void formPrintBirthdays_Load(object sender, EventArgs e)
{
printForm();
this.Close();
}
public FormPrintDormantListeners()
{
Load += formPrintBirthdays_Load;
InitializeComponent();
}
}
}
| 35.442029 | 185 | 0.688612 |
[
"MIT"
] |
achrisdale/TNBase
|
TNBase/Forms/Printing/FormPrintDormantListeners.cs
| 4,891 |
C#
|
using AutoMapper;
using EPlast.BLL.DTO.EducatorsStaff;
using EPlast.BLL.Interfaces.EducatorsStaff;
using EPlast.DataAccess.Entities.EducatorsStaff;
using EPlast.DataAccess.Repositories;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EPlast.BLL.Services.EducatorsStaff
{
public class KadrasTypesService:IKadrasTypeService
{
private readonly IRepositoryWrapper _repositoryWrapper;
private readonly IMapper _mapper;
public KadrasTypesService(IRepositoryWrapper repositoryWrapper, IMapper mapper)
{
_repositoryWrapper = repositoryWrapper;
_mapper = mapper;
}
public async Task<KadraVykhovnykivTypesDTO> CreateKVType(KadraVykhovnykivTypesDTO kvTypeDTO)
{
var newKVType = _mapper.Map<KadraVykhovnykivTypesDTO,KadraVykhovnykivTypes>(kvTypeDTO);
await _repositoryWrapper.KVTypes.CreateAsync(newKVType);
await _repositoryWrapper.SaveAsync();
return _mapper.Map<KadraVykhovnykivTypes, KadraVykhovnykivTypesDTO>(newKVType);
}
public async Task<IEnumerable<KadraVykhovnykivTypesDTO>> GetAllKVTypesAsync()
{
return _mapper.Map<IEnumerable<KadraVykhovnykivTypes>, IEnumerable<KadraVykhovnykivTypesDTO>>(
await _repositoryWrapper.KVTypes.GetAllAsync());
}
public async Task<IEnumerable<KadraVykhovnykivDTO>> GetKadrasWithSuchType(KadraVykhovnykivTypesDTO kvTypeDTO)
{
var KVs = _mapper.Map<IEnumerable<KadraVykhovnykiv>, IEnumerable<KadraVykhovnykivDTO>>(await _repositoryWrapper.KVs.GetAllAsync(c => c.KadraVykhovnykivTypeId == kvTypeDTO.ID));
return KVs;
}
public async Task<KadraVykhovnykivTypesDTO> GetKVsTypeByIdAsync(int KV_id)
{
var KV = _mapper.Map<KadraVykhovnykiv, KadraVykhovnykivDTO>(await _repositoryWrapper.KVs.GetFirstOrDefaultAsync(c => c.ID == KV_id));
var Type = await _repositoryWrapper.KVTypes.GetFirstOrDefaultAsync(a => a.ID == KV.KadraVykhovnykivTypeId);
return _mapper.Map<KadraVykhovnykivTypes,KadraVykhovnykivTypesDTO>(Type);
}
}
}
| 40.142857 | 188 | 0.704181 |
[
"MIT"
] |
gatalyak/EPlast
|
EPlast/EPlast.BLL/Services/EducatorsStaff/KadrasTypesService.cs
| 2,250 |
C#
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.ContractsLight;
using System.Diagnostics.Tracing;
using System.IO;
using System.Threading.Tasks;
using BuildXL;
using BuildXL.Storage;
using BuildXL.Storage.Diagnostics;
using BuildXL.Storage.FileContentTableAccessor;
using BuildXL.Utilities;
using BuildXL.Utilities.Instrumentation.Common;
using BuildXL.Utilities.Tracing;
namespace Tool.VerifyFileContentTable
{
/// <summary>
/// Main program.
/// </summary>
public static class Program
{
/// <summary>
/// Main method.
/// </summary>
public static int Main(string[] args)
{
Contract.Assert(args != null);
Args a = Args.Acquire(args);
if (a == null)
{
HelpText.DisplayHelp();
return 1;
}
if (!a.NoLogo)
{
HelpText.DisplayLogo();
}
if (a.HelpRequested)
{
HelpText.DisplayHelp();
return 1;
}
return Run(a) ? 0 : 1;
}
/// <summary>
/// Runs the verifier
/// </summary>
public static bool Run(Args args)
{
Contract.Requires(args != null);
Contract.Requires(!args.HelpRequested);
Contract.Assume(args.FileContentTablePath != null); // Should be provable from the invariant on Args
DateTime now = DateTime.UtcNow;
using (ConfigureConsoleLogging(now))
{
var pt = new PathTable();
AbsolutePath path;
Contract.Assert(args.FileContentTablePath != null, "Implied when help was not requested");
if (!AbsolutePath.TryCreate(pt, Path.GetFullPath(args.FileContentTablePath), out path))
{
Console.Error.WriteLine(Resources.Bad_table_path, args.FileContentTablePath);
return false;
}
Console.WriteLine(Resources.Verifying_path, path.ToString(pt));
FileContentTable tableToVerify = TryLoadFileContentTable(pt, path).Result;
if (tableToVerify == null)
{
// Note the error has already been logged via TryLoadFileContentTable
return false;
}
if (!FileContentTableAccessorFactory.TryCreate(out IFileContentTableAccessor accessor, out string error))
{
Console.Error.WriteLine(error);
return false;
}
Stopwatch sw = Stopwatch.StartNew();
List<FileContentTableDiagnosticExtensions.IncorrectFileContentEntry> incorrectEntries = null;
using (accessor)
{
incorrectEntries = tableToVerify.FindIncorrectEntries(accessor);
}
sw.Stop();
foreach (FileContentTableDiagnosticExtensions.IncorrectFileContentEntry incorrectEntry in incorrectEntries)
{
Console.Error.WriteLine(
Resources.Incorrect_entry,
incorrectEntry.Path,
incorrectEntry.ExpectedHash.ToHex(),
incorrectEntry.ActualHash.ToHex(),
incorrectEntry.Usn);
}
Console.WriteLine(Resources.Verification_summary, tableToVerify.Count, incorrectEntries.Count, sw.Elapsed);
return incorrectEntries.Count == 0;
}
}
private static async Task<FileContentTable> TryLoadFileContentTable(PathTable pt, AbsolutePath path)
{
try
{
return await FileContentTable.LoadAsync(path.ToString(pt));
}
catch (BuildXLException ex)
{
Console.Error.WriteLine(Resources.Failed_to_load_table, path.ToString(pt), ex.LogEventMessage);
return null;
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static EventListener ConfigureConsoleLogging(DateTime baseTime)
{
return new ConsoleEventListener(Events.Log, baseTime, colorize: true, animateTaskbar: false, level: EventLevel.Informational, updatingConsole: false, useCustomPipDescription: false);
}
}
}
| 35.442029 | 195 | 0.559804 |
[
"MIT"
] |
buildxl-team-collab/BuildXL
|
Public/Src/Tools/VerifyFileContentTable/Program.cs
| 4,891 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeGrower : MonoBehaviour {
private List<GameObject> tips;
//What happens when you make these member variables public?
private float growChance = 0.94f;
private float splitChance = 0.99f;
private Vector3 SplitRotation = new Vector3(0.0f, 0.0f, -15.0f);
private Vector3 GrowthRotation = new Vector3(0.0f, 0.0f, 0.5f);
private Object GrowthPrefab;
// Use this for initialization
void Start () {
this.tips = new List<GameObject>();
this.GrowthPrefab = Resources.Load("growth");
GameObject newGrowthAtOrigin;
//What is the (GameObject) casting bad practice?
newGrowthAtOrigin = (GameObject)Instantiate(this.GrowthPrefab, new Vector3(0, 0, 0), Quaternion.identity);
this.tips.Add(newGrowthAtOrigin);
}
// Update is called once per frame
void Update () {
var tipsToRemove = new List<GameObject>();
var tipsToAdd = new List<GameObject>();
foreach (var tip in this.tips)
{
float rnd = Random.value;
if(rnd < this.growChance)
{
var newTip = (GameObject)Instantiate(this.GrowthPrefab, tip.transform);
newTip.transform.Rotate(this.GrowthRotation);
newTip.transform.Translate(Vector3.up * 1.0f);
tipsToRemove.Add(tip);
tipsToAdd.Add(newTip);
}
else if(rnd < this.splitChance)
{
var splitTip = (GameObject)Instantiate(this.GrowthPrefab, tip.transform);
splitTip.transform.Rotate(this.SplitRotation);
tipsToAdd.Add(splitTip);
} else
{
tipsToRemove.Add(tip);
}
}
//Why is this.tips being modified outside of the first foreach loop in this function?
foreach (var tip in tipsToRemove)
{
this.tips.Remove(tip);
}
foreach (var tip in tipsToAdd)
{
this.tips.Add(tip);
}
}
}
| 33.703125 | 115 | 0.583681 |
[
"MIT"
] |
pviktor9/AngryBirdsStyleGame
|
Projects/PCGTree/Assets/scripts/TreeGrower.cs
| 2,159 |
C#
|
using DirSync.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace DirSync.Test
{
public class MainServiceTest : IDisposable
{
private readonly MainService _mainService;
private readonly Options _options;
private readonly string _src;
private string _target;
public MainServiceTest()
{
_src = TestHelper.GetRandomFolderPath();
_target = TestHelper.GetRandomFolderPath();
_options = new Options { SourceDir = _src, TargetDir = _target };
_mainService = new MainService(_options);
}
public void Dispose()
{
TestHelper.DeleteFolder(_src);
TestHelper.DeleteFolder(_target);
TestHelper.DeleteFolder(_src);
TestHelper.DeleteFolder(_target);
}
[Fact]
public async Task Test1_EmptySrc_NoTarget()
{
_target = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(0, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(0, executorResult.SrcFileCount.First().Value);
}
[Fact]
public async Task Test2_Src_Has_File()
{
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(9, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(9, executorResult.SrcFileCount.First().Value);
Assert.Equal(9, Directory.GetFiles(_target).Length);
}
[Fact]
public async Task Test3_Src_Has_File_And_Folder()
{
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
var srcFolder1 = TestHelper.GetFolderPath(_src);
await TestHelper.CreateRandomFileAsync(srcFolder1, 1, 10, new byte[2000]);
var srcFolder2 = TestHelper.GetFolderPath(_src);
await TestHelper.CreateRandomFileAsync(srcFolder2, 1, 10, new byte[3000]);
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(2, executorResult.SrcDirCount.First().Value);
Assert.Equal(27, executorResult.SrcFileCount.First().Value);
Assert.Equal(27, Directory.GetFiles(_target, "*", SearchOption.AllDirectories).Length);
Assert.Equal(2, Directory.GetDirectories(_target, "*", SearchOption.AllDirectories).Length);
}
[Fact]
public async Task Test4_Cleanup_On_No_Same_File()
{
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
await TestHelper.CreateRandomFileAsync(_target, 10, 19, new byte[1000]);
var srcFolder1 = TestHelper.GetFolderPath(_src);
await TestHelper.CreateRandomFileAsync(srcFolder1, 1, 10, new byte[2000]);
var srcFolder2 = TestHelper.GetFolderPath(_src);
await TestHelper.CreateRandomFileAsync(srcFolder2, 1, 10, new byte[3000]);
var targetFolder1 = TestHelper.GetFolderPath(_target);
await TestHelper.CreateRandomFileAsync(targetFolder1, 10, 19, new byte[5000000]);
_options.Cleanup = true;
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(45, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(2, executorResult.SrcDirCount.First().Value);
Assert.Equal(27, executorResult.SrcFileCount.First().Value);
Assert.Equal(27, Directory.GetFiles(_target, "*", SearchOption.AllDirectories).Length);
Assert.Equal(2, Directory.GetDirectories(_target, "*", SearchOption.AllDirectories).Length);
}
[Fact]
public async Task Test5_Cleanup_On_With_Same_File()
{
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
await TestHelper.CreateRandomFileAsync(_target, 1, 10, new byte[1000]);
var srcFolder1 = TestHelper.GetFolderPath(_src);
await TestHelper.CreateRandomFileAsync(srcFolder1, 1, 10, new byte[2000]);
var srcFolder2 = TestHelper.GetFolderPath(_src);
await TestHelper.CreateRandomFileAsync(srcFolder2, 1, 10, new byte[3000]);
var targetFolder1 = TestHelper.GetFolderPath(_target);
await TestHelper.CreateRandomFileAsync(targetFolder1, 10, 19, new byte[5000000]);
_options.Cleanup = true;
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(27, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(2, executorResult.SrcDirCount.First().Value);
Assert.Equal(27, executorResult.SrcFileCount.First().Value);
Assert.Equal(27, Directory.GetFiles(_target, "*", SearchOption.AllDirectories).Length);
Assert.Equal(2, Directory.GetDirectories(_target, "*", SearchOption.AllDirectories).Length);
}
[Fact]
public async Task Test6_Force_On()
{
await TestHelper.CreateRandomFileAsync(_target, 5, 10, new byte[1000 * 1000]);
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
_options.Force = true;
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(9, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(9, executorResult.SrcFileCount.First().Value);
Assert.Equal(9, Directory.GetFiles(_target).Length);
}
[Fact]
public async Task Test7_Force_Off()
{
await TestHelper.CreateRandomFileAsync(_target, 5, 10, new byte[1000 * 1000]);
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
_options.Force = false;
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(4, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(9, executorResult.SrcFileCount.First().Value);
Assert.Equal(9, Directory.GetFiles(_target).Length);
}
[Fact]
public async Task Test8_Strict_On()
{
await TestHelper.CreateRandomFileAsync(_target, 5, 10, new byte[1000 * 1000]);
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
_options.Strict = true;
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(9, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(9, executorResult.SrcFileCount.First().Value);
Assert.Equal(9, Directory.GetFiles(_target).Length);
}
[Fact]
public async Task Test9_Strict_On()
{
await TestHelper.CreateRandomFileAsync(_target, 5, 6, new byte[1000 * 1000]);
await TestHelper.CreateRandomFileAsync(_target, 6, 10, new byte[1000]);
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
_options.Strict = true;
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(5, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(9, executorResult.SrcFileCount.First().Value);
Assert.Equal(9, Directory.GetFiles(_target).Length);
}
[Fact]
public async Task Test10_Include()
{
await TestHelper.CreateRandomFileAsync(_target, 5, 6, new byte[1000 * 1000]);
await TestHelper.CreateRandomFileAsync(_target, 6, 10, new byte[1000]);
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
_options.Include = new List<string> { "2*", "3*" };
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(2, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(9, executorResult.SrcFileCount.First().Value);
Assert.Equal(7, Directory.GetFiles(_target).Length);
}
[Fact]
public async Task Test11_Exclude()
{
await TestHelper.CreateRandomFileAsync(_target, 5, 6, new byte[1000 * 1000]);
await TestHelper.CreateRandomFileAsync(_target, 6, 10, new byte[1000]);
await TestHelper.CreateRandomFileAsync(_src, 1, 10, new byte[1000]);
_options.Exclude = new List<string> { "2*" };
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(3, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(9, executorResult.SrcFileCount.First().Value);
Assert.Equal(8, Directory.GetFiles(_target).Length);
}
[Fact]
public async Task Test12_Include_Exclude()
{
await TestHelper.CreateRandomFileAsync(_target, 5, 6, new byte[1000 * 1000]);
await TestHelper.CreateRandomFileAsync(_target, 6, 10, new byte[1000]);
await TestHelper.CreateRandomFileAsync(_src, 1, 18, new byte[1000]);
_options.Exclude = new List<string> { "12*" };
_options.Include = new List<string> { "2*" };
var executorResult = await _mainService.RunAsync();
Assert.True(executorResult.Succeed);
Assert.Equal(1, executorResult.TargetAffectedFileCount.First().Value);
Assert.Equal(0, executorResult.SrcDirCount.First().Value);
Assert.Equal(17, executorResult.SrcFileCount.First().Value);
Assert.Equal(6, Directory.GetFiles(_target).Length);
}
}
}
| 47.213043 | 104 | 0.640943 |
[
"MIT"
] |
JerryBian/dirsync
|
test/DirSync.Test/MainServiceTest.cs
| 10,861 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
namespace me.cqp.luohuaming.Calculator.Tool.Http
{
/// <summary>
/// 提供用于将数据发送到和接收来自通过 URI 确认的资源数据丰富的常用方法。
/// </summary>
public class HttpWebClient : WebClient
{
#region --属性--
/// <summary>
/// 获取或设置请求的方法
/// </summary>
/// <exception cref="ArgumentException">未提供任何方法。 - 或 - 方法字符串包含无效字符。</exception>
public string Method { get; set; }
/// <summary>
/// 获取或设置 User-Agent HTTP 标头的值
/// </summary>
public string UserAgent { get; set; }
/// <summary>
/// 获取或设置 Referer HTTP 标头的值
/// </summary>
public string Referer { get; set; }
/// <summary>
/// 获取或设置获取 Intelnet 资源过程的超时值
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">指定的值是小于零,且不是 System.Threading.Timeout.Infinite。</exception>
public int TimeOut { get; set; }
/// <summary>
/// 获取或设置 Accept HTTP 标头的值
/// </summary>
public string Accept { get; set; }
/// <summary>
/// 获取或设置与此请求关联的 <see cref="CookieContainer"/>
/// </summary>
public CookieCollection CookieCollection { get; set; }
/// <summary>
/// 获取或设置 Content-Type HTTP 标头的值
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// 获取或设置一个值, 该值指示请求是否跟应跟随重定向响应
/// </summary>
public bool AllowAutoRedirect { get; set; }
/// <summary>
/// 获取或设置请求将跟随的重定向的最大数目。
/// </summary>
/// <exception cref="ArgumentException">值设置为 0 或更小。</exception>
public int MaximumAutomaticRedirections { get; set; }
/// <summary>
/// 获取或设置一个值, 该值指示是否与 Internal 建立持续型的连接
/// </summary>
public bool KeepAlive { get; set; }
/// <summary>
/// 获取或设置一个值, 该值指示是否获取 Internet 资源后自动合并关联的 <see cref="CookieContainer"/>
/// </summary>
public bool AutoCookieMerge { get; set; }
/// <summary>
/// 获取或设置一个值, 该值指示仅用 HTTPS 请求时客户端的安全验证类型
/// <para/>
/// 验证类型为: SSL3.0 (48), TLS1.0 (192), TLS1.1 (768), TLS1.2 (3072), TLS1.3 (12288)
/// </summary>
public SecurityProtocolType ServiceSecurityType { get; set; }
#endregion
#region --构造函数--
/// <summary>
/// 初始化 <see cref="HttpWebClient"/> 类的一个实例对象
/// </summary>
public HttpWebClient ()
{
this.ServiceSecurityType = GetSecurityAllValue ();
}
#endregion
#region --公开方法--
#region --Get--
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="userAgent">User-Agent HTTP 标头</param>
/// <param name="accept">Accept HTTP 标头</param>
/// <param name="timeout">超时时间</param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="proxy">代理 <see cref="HttpWebClient"/> 的 <see cref="WebProxy"/> 实例</param>
/// <param name="encoding">文本编码</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, string referer, string userAgent, string accept, int timeout, ref CookieCollection cookies, ref WebHeaderCollection headers, WebProxy proxy, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
HttpWebClient httpWebClient = new HttpWebClient ();
httpWebClient.CookieCollection = cookies;
httpWebClient.Headers = headers;
httpWebClient.Referer = referer;
httpWebClient.UserAgent = userAgent;
httpWebClient.Accept = accept;
httpWebClient.TimeOut = timeout;
httpWebClient.Encoding = encoding;
httpWebClient.Proxy = proxy;
httpWebClient.AllowAutoRedirect = allowAutoRedirect;
httpWebClient.AutoCookieMerge = autoCookieMerge;
byte[] result = httpWebClient.DownloadData (new Uri (url));
headers = httpWebClient.ResponseHeaders;
cookies = httpWebClient.CookieCollection;
return result;
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="proxy">代理 <see cref="HttpWebClient"/> 的 <see cref="WebProxy"/> 实例</param>
/// <param name="encoding">文本编码</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, WebProxy proxy, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
return Get (url, referer, string.Empty, string.Empty, 0, ref cookies, ref headers, proxy, encoding, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="encoding">文本编码</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
return Get (url, referer, ref cookies, ref headers, null, encoding, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
return Get (url, referer, ref cookies, ref headers, null, Encoding.UTF8, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, string referer, ref CookieCollection cookies, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
WebHeaderCollection headers = new WebHeaderCollection ();
return Get (url, referer, ref cookies, ref headers, null, Encoding.UTF8, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, string referer, ref WebHeaderCollection headers, bool allowAutoRedirect = true)
{
CookieCollection cookies = new CookieCollection ();
return Get (url, referer, ref cookies, ref headers, null, Encoding.UTF8, allowAutoRedirect, false);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, string referer, bool allowAutoRedirect = true)
{
WebHeaderCollection headers = new WebHeaderCollection ();
return Get (url, referer, ref headers, allowAutoRedirect);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, ref CookieCollection cookies, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
WebHeaderCollection headers = new WebHeaderCollection ();
return Get (url, string.Empty, ref cookies, ref headers, null, Encoding.UTF8, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, ref WebHeaderCollection headers, bool allowAutoRedirect = true)
{
CookieCollection cookies = new CookieCollection ();
return Get (url, string.Empty, ref cookies, ref headers, null, Encoding.UTF8, allowAutoRedirect, false);
}
/// <summary>
/// 向服务器发送 HTTP GET 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Get (string url, bool allowAutoRedirect = true)
{
return Get (url, string.Empty, allowAutoRedirect);
}
#endregion
#region --Post--
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="userAgent">User-Agent HTTP 标头</param>
/// <param name="accept">Accept HTTP 标头</param>
/// <param name="timeout">超时时间</param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="proxy">代理 <see cref="HttpWebClient"/> 的 <see cref="WebProxy"/> 实例</param>
/// <param name="encoding">文本编码</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, string referer, string userAgent, string accept, int timeout, ref CookieCollection cookies, ref WebHeaderCollection headers, WebProxy proxy, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
HttpWebClient httpWebClient = new HttpWebClient ();
httpWebClient.ContentType = contentType;
httpWebClient.Referer = referer;
httpWebClient.UserAgent = userAgent;
httpWebClient.Accept = accept;
httpWebClient.TimeOut = timeout;
httpWebClient.CookieCollection = cookies;
httpWebClient.Headers = headers;
httpWebClient.Proxy = proxy;
httpWebClient.AutoCookieMerge = autoCookieMerge;
httpWebClient.AllowAutoRedirect = allowAutoRedirect;
byte[] result = httpWebClient.UploadData (new Uri (url), data);
headers = httpWebClient.ResponseHeaders;
cookies = httpWebClient.CookieCollection;
return result;
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="proxy">代理 <see cref="HttpWebClient"/> 的 <see cref="WebProxy"/> 实例</param>
/// <param name="encoding">文本编码</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, WebProxy proxy, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
return Post (url, data, contentType, referer, string.Empty, string.Empty, 0, ref cookies, ref headers, proxy, encoding, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="encoding">文本编码</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, Encoding encoding, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
return Post (url, data, contentType, referer, ref cookies, ref headers, null, encoding, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, string referer, ref CookieCollection cookies, ref WebHeaderCollection headers, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
return Post (url, data, contentType, referer, ref cookies, ref headers, Encoding.UTF8, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, string referer, ref CookieCollection cookies, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
WebHeaderCollection headers = new WebHeaderCollection ();
return Post (url, data, contentType, referer, ref cookies, ref headers, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, string referer, ref WebHeaderCollection headers, bool allowAutoRedirect = true)
{
CookieCollection cookies = new CookieCollection ();
return Post (url, data, contentType, referer, ref cookies, ref headers, allowAutoRedirect, false);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="cookies">请求附带的 Cookies
/// <para>此参数支持自动更新 <see cref="CookieContainer"/>, 若 <see cref="AutoCookieMerge"/> 参数为 True, 将合并新旧 Cookie</para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <param name="autoCookieMerge">指定自动 <see cref="CookieContainer"/> 合并</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, ref CookieCollection cookies, bool allowAutoRedirect = true, bool autoCookieMerge = true)
{
return Post (url, data, contentType, string.Empty, ref cookies, allowAutoRedirect, autoCookieMerge);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="headers">请求附带的 Headers
/// <para>此参数支持自动更新 <see cref="WebHeaderCollection"/></para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, ref WebHeaderCollection headers, bool allowAutoRedirect = true)
{
return Post (url, data, contentType, string.Empty, ref headers, allowAutoRedirect);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="referer">参考页链接
/// <para>告知服务器, 访问时的来源地址</para>
/// </param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, string referer, bool allowAutoRedirect = true)
{
WebHeaderCollection headers = new WebHeaderCollection ();
return Post (url, data, contentType, referer, ref headers, allowAutoRedirect);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="contentType">Content-Type HTTP 标头</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, string contentType, bool allowAutoRedirect = true)
{
return Post (url, data, contentType, string.Empty, allowAutoRedirect);
}
/// <summary>
/// 向服务器发送 HTTP POST 请求 <see cref="ContentType"/>: application/x-www-form-urlencoded
/// </summary>
/// <param name="url">完整的网页地址
/// <para>必须包含 "http://" 或 "https://"</para>
/// </param>
/// <param name="data">请求所需的上传数据</param>
/// <param name="allowAutoRedirect">跟随重定向响应</param>
/// <returns>返回从 Internal 读取的 <see cref="byte"/> 数组</returns>
public static byte[] Post (string url, byte[] data, bool allowAutoRedirect = true)
{
return Post (url, data, string.Empty, string.Empty, allowAutoRedirect);
}
#endregion
#region --Cookie--
/// <summary>
/// <see cref="System.Net.CookieCollection"/> 合并更新
/// </summary>
/// <param name="oldCookies">原始的Cookis</param>
/// <param name="newCookies">欲合并Cookies</param>
/// <returns>返回处理过的 <see cref="System.Net.CookieCollection"/></returns>
public static CookieCollection UpdateCookie (CookieCollection oldCookies, CookieCollection newCookies)
{
if (oldCookies == null)
{
throw new ArgumentNullException ("oldCookies");
}
if (newCookies == null)
{
throw new ArgumentNullException ("newCookies");
}
for (int i = 0; i < newCookies.Count; i++)
{
int index = CheckCookie (oldCookies, newCookies[i].Name);
if (index >= 0)
{
oldCookies[index].Value = newCookies[i].Value;
}
else
{
oldCookies.Add (newCookies[i]);
}
}
return oldCookies;
}
#endregion
#endregion
#region --私有方法--
/// <summary>
/// 验证HTTPS证书
/// </summary>
/// <param name="sender"></param>
/// <param name="certificate"></param>
/// <param name="chain"></param>
/// <param name="sslPolicyErrors"></param>
/// <returns></returns>
private bool CheckValidationResult (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
/// <summary>
/// 确认Cookie是否存在
/// </summary>
/// <param name="cookie">Cookie对象</param>
/// <param name="name">cookie名称</param>
/// <returns></returns>
private static int CheckCookie (CookieCollection cookie, string name)
{
for (int i = 0; i < cookie.Count; i++)
{
if (cookie[i].Name == name)
{
return i;
}
}
return -1;
}
/// <summary>
/// 获取 <see cref="SecurityProtocolType"/> 类型所有值的或
/// </summary>
/// <returns></returns>
private static SecurityProtocolType GetSecurityAllValue ()
{
SecurityProtocolType temp = (SecurityProtocolType)0;
foreach (SecurityProtocolType item in Enum.GetValues (typeof (SecurityProtocolType)))
{
temp |= item;
}
return temp;
}
#endregion
#region --重写方法--
/// <summary>
/// 返回带有 Cookies 的 HttpWebRequest
/// </summary>
/// <param name="address">一个 System.Uri,它标识要请求的资源</param>
/// <returns></returns>
protected override WebRequest GetWebRequest (Uri address)
{
if (address.OriginalString.StartsWith ("https", StringComparison.OrdinalIgnoreCase))
{
// 强行验证HTTPS通过
// 验证方式改为用户手动指定
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
ServicePointManager.SecurityProtocol = this.ServiceSecurityType;
}
HttpWebRequest httpWebRequest = (HttpWebRequest)base.GetWebRequest (address);
httpWebRequest.ProtocolVersion = HttpVersion.Version11;
httpWebRequest.KeepAlive = KeepAlive; // 默认: False, 不建立持续型连接
if (CookieCollection != null)
{
httpWebRequest.CookieContainer = new CookieContainer ();
httpWebRequest.CookieContainer.Add (address, CookieCollection);
}
else
{
httpWebRequest.CookieContainer = new CookieContainer ();
}
if (!string.IsNullOrEmpty (this.UserAgent))
{
httpWebRequest.UserAgent = UserAgent;
}
else
{
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 Safari/537.36";
}
if (TimeOut > 0)
{
httpWebRequest.Timeout = this.TimeOut;
}
if (!string.IsNullOrEmpty (this.Accept))
{
httpWebRequest.Accept = this.Accept;
}
else
{
httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
}
httpWebRequest.AllowAutoRedirect = this.AllowAutoRedirect;
if (this.AllowAutoRedirect)
{
if (this.MaximumAutomaticRedirections <= 0)
{
httpWebRequest.MaximumAutomaticRedirections = 5;
}
else
{
httpWebRequest.MaximumAutomaticRedirections = this.MaximumAutomaticRedirections;
}
}
if (!string.IsNullOrEmpty (this.Referer))
{
httpWebRequest.Referer = this.Referer;
}
if (httpWebRequest.Method.ToUpper () != "GET") //GET不需要包体参数
{
if (!string.IsNullOrEmpty (this.ContentType))
{
httpWebRequest.ContentType = this.ContentType;
}
else
{
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
}
}
return httpWebRequest;
}
/// <summary>
/// 返回指定 System.Net.WebResponse 的 System.Net.WebRequest。
/// </summary>
/// <param name="request">一个 System.Net.WebRequest 用于获得响应。</param>
/// <returns>一个 System.Net.WebResponse 包含指定的响应 System.Net.WebRequest。</returns>
protected override WebResponse GetWebResponse (WebRequest request)
{
HttpWebResponse httpWebResponse = (HttpWebResponse)base.GetWebResponse (request);
this.Method = httpWebResponse.Method;
this.ContentType = httpWebResponse.ContentType;
// 开启自动合并更新时, 若传入的 CookieCollection 为 null, 则将反回的 CookieCollection 赋给传入的 CookieCollection
if (this.AutoCookieMerge && this.CookieCollection != null)
{
UpdateCookie (this.CookieCollection, httpWebResponse.Cookies);
}
else
{
this.CookieCollection = httpWebResponse.Cookies;
}
return httpWebResponse;
}
#endregion
}
}
| 45.922652 | 299 | 0.56647 |
[
"Apache-2.0"
] |
Hellobaka/Calc-Rate
|
me.cqp.luohuaming.Calculator.Tool/Http/HttpWebClient.cs
| 37,498 |
C#
|
using System;
using System.Net;
using System.Threading.Tasks;
using EPiServer.Commerce.Order;
using EPiServer.Logging;
using Klarna.Common.Models;
using Klarna.OrderManagement;
using Klarna.OrderManagement.Steps;
using Mediachase.Commerce;
using Mediachase.Commerce.Orders;
namespace Klarna.Checkout.Steps
{
public class AuthorizePaymentStep : AuthorizePaymentStepBase
{
private static readonly ILogger Logger = LogManager.GetLogger(typeof(AuthorizePaymentStep));
public AuthorizePaymentStep(IPayment payment, MarketId marketId, KlarnaOrderServiceFactory klarnaOrderServiceFactory)
: base(payment, marketId, klarnaOrderServiceFactory)
{
}
public override async Task<PaymentStepResult> ProcessAuthorization(IPayment payment, IOrderGroup orderGroup)
{
var paymentStepResult = new PaymentStepResult();
var orderId = orderGroup.Properties[Constants.KlarnaCheckoutOrderIdCartField]?.ToString();
try
{
var result = await KlarnaOrderService.GetOrder(orderId).ConfigureAwait(false);
if (result != null)
{
payment.Properties[Common.Constants.FraudStatusPaymentField] = result.FraudStatus;
AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Fraud status: {result.FraudStatus}");
if (result.FraudStatus == OrderManagementFraudStatus.REJECTED)
{
paymentStepResult.Message = "Klarna fraud status rejected";
payment.Status = PaymentStatus.Failed.ToString();
}
else
{
paymentStepResult.Status = true;
}
}
AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Authorize completed");
}
catch (Exception ex) when (ex is ApiException || ex is WebException || ex is AggregateException)
{
var exceptionMessage = GetExceptionMessage(ex);
payment.Status = PaymentStatus.Failed.ToString();
paymentStepResult.Message = exceptionMessage;
AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}");
Logger.Error(exceptionMessage, ex);
}
return paymentStepResult;
}
}
}
| 38.261538 | 125 | 0.628066 |
[
"Apache-2.0"
] |
Geta/Klarna
|
src/Klarna.Checkout/Steps/AuthorizePaymentStep.cs
| 2,489 |
C#
|
namespace CoreCourse.DIBasics.Domain.CoffeeSystem
{
public interface ICoffeeCup
{
ICreamer Creamer { get; }
ISweetener Sweetener { get; }
}
}
| 19 | 50 | 0.643275 |
[
"MIT"
] |
sigged/aspnetcore-dibasics
|
src/CoreCourse.DIBasics.Domain/CoffeeSystem/ICoffeeCup.cs
| 173 |
C#
|
using System;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extras.Moq;
using Ketchup.Caching.Configurations;
using Ketchup.Caching.Internal;
using Ketchup.Caching.Internal.Redis;
using Xunit;
namespace Ketchup.Redis.Test
{
public class RedisProviderTest
{
private readonly AutoMock _autoMock;
private readonly RedisCacheProvider redisCache;
public RedisProviderTest()
{
_autoMock = AutoMock.GetLoose();
redisCache = _autoMock.Create<RedisCacheProvider>(new TypedParameter(typeof(CacheOption), new CacheOption()
{
IpAddress = "192.168.180.55",
Password = "qwe123QWE"
}));
}
[Fact]
public async Task GetOrAddAsync_Test()
{
var result = await redisCache.GetOrAddAsync("a", "123456789");
Assert.Equal("123456789", result);
}
[Fact]
public async Task GetOrAddAsync_TimeSpane_Test()
{
var result = await redisCache.GetOrAddAsync("b", "123456789", TimeSpan.FromSeconds(10));
Assert.Equal("123456789", result);
}
[Fact]
public async Task GetAsync_Test()
{
var one = await redisCache.GetAsync<string>("a");
Assert.Equal("123456789", one);
}
[Fact]
public async Task AddAsync_Test()
{
await redisCache.AddAsync<string>("b", "test");
var one = await redisCache.GetAsync<string>("b");
Assert.Equal("test", one);
}
[Fact]
public async Task Remove_Test()
{
await redisCache.RemoveAsync("a");
var one = await redisCache.GetAsync<string>("a");
Assert.Null(one);
}
}
}
| 24.567568 | 119 | 0.573707 |
[
"MIT"
] |
ZParas/ketchup
|
test/Ketchup.Redis.Test/RedisProviderTest.cs
| 1,818 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace NORSU.BioPay.Views
{
/// <summary>
/// Interaction logic for DevTeam.xaml
/// </summary>
public partial class DevTeam : UserControl
{
public DevTeam()
{
InitializeComponent();
}
}
}
| 21.642857 | 46 | 0.706271 |
[
"MIT"
] |
awooo-ph/biopay
|
NORSU.BioPay/Views/DevTeam.xaml.cs
| 608 |
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 eks-2017-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EKS.Model
{
/// <summary>
/// The request is invalid given the state of the cluster. Check the state of the cluster
/// and the associated operations.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class InvalidRequestException : AmazonEKSException
{
private string _addonName;
private string _clusterName;
private string _nodegroupName;
/// <summary>
/// Constructs a new InvalidRequestException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidRequestException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidRequestException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="innerException"></param>
public InvalidRequestException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidRequestException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidRequestException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InvalidRequestException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InvalidRequestException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
this.AddonName = (string)info.GetValue("AddonName", typeof(string));
this.ClusterName = (string)info.GetValue("ClusterName", typeof(string));
this.NodegroupName = (string)info.GetValue("NodegroupName", typeof(string));
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("AddonName", this.AddonName);
info.AddValue("ClusterName", this.ClusterName);
info.AddValue("NodegroupName", this.NodegroupName);
}
#endif
/// <summary>
/// Gets and sets the property AddonName.
/// </summary>
public string AddonName
{
get { return this._addonName; }
set { this._addonName = value; }
}
// Check to see if AddonName property is set
internal bool IsSetAddonName()
{
return this._addonName != null;
}
/// <summary>
/// Gets and sets the property ClusterName.
/// <para>
/// The Amazon EKS cluster associated with the exception.
/// </para>
/// </summary>
public string ClusterName
{
get { return this._clusterName; }
set { this._clusterName = value; }
}
// Check to see if ClusterName property is set
internal bool IsSetClusterName()
{
return this._clusterName != null;
}
/// <summary>
/// Gets and sets the property NodegroupName.
/// <para>
/// The Amazon EKS managed node group associated with the exception.
/// </para>
/// </summary>
public string NodegroupName
{
get { return this._nodegroupName; }
set { this._nodegroupName = value; }
}
// Check to see if NodegroupName property is set
internal bool IsSetNodegroupName()
{
return this._nodegroupName != null;
}
}
}
| 43.513514 | 179 | 0.631677 |
[
"Apache-2.0"
] |
philasmar/aws-sdk-net
|
sdk/src/Services/EKS/Generated/Model/InvalidRequestException.cs
| 8,050 |
C#
|
using System.Security.Authentication;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
namespace question_metrics_api
{
public static class MongoSupportUtils
{
public static void AddMongo(this IServiceCollection services, string connectionString)
{
MongoClientSettings settings = MongoClientSettings.FromUrl(
new MongoUrl(connectionString)
);
settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
var client = new MongoClient(settings);
services.AddSingleton(client);
}
}
}
| 29.954545 | 102 | 0.666161 |
[
"Apache-2.0"
] |
Rafael-Miceli/questions-metric-back
|
question-metrics-api/MongoSupportUtils.cs
| 659 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Evolve.MSBuild;
using Xunit;
namespace Evolve.Tests.Configuration
{
public class JsonCliArgsBuilderTest
{
[Fact]
[Category(Test.Configuration)]
public void Load_json_configuration_file_works()
{
var builder = new JsonCliArgsBuilder(TestContext.EvolveJsonPath);
Assert.Equal("Erase", builder.Command);
Assert.Equal("postgresql", builder.Database);
Assert.Equal("Server=127.0.0.1;Port=5432;Database=myDataBase;User Id=myUsername;Password=myPassword;", builder.ConnectionString);
Assert.True(new List<string>() { "migration", "dataset" }.SequenceEqual(builder.Locations));
Assert.Equal("true", builder.EraseDisabled);
Assert.Equal("True", builder.EraseOnValidationError);
Assert.Equal("utf-16", builder.Encoding);
Assert.Equal("Ver", builder.SqlMigrationPrefix);
Assert.Equal("Z", builder.SqlRepeatableMigrationPrefix);
Assert.Equal("@", builder.SqlMigrationSeparator);
Assert.Equal(".query", builder.SqlMigrationSuffix);
Assert.Equal("my_shema", builder.Schemas.Single());
Assert.Equal("my_metadata_schema", builder.MetadataTableSchema);
Assert.Equal("metadata_store", builder.MetadataTableName);
Assert.Equal("@{", builder.PlaceholderPrefix);
Assert.Equal("@}", builder.PlaceholderSuffix);
Assert.Equal("2_1_0", builder.TargetVersion);
Assert.Equal("1_1_0", builder.StartVersion);
Assert.True(new List<string>() { "Schema:my_schema", "Pwd:password" }.SequenceEqual(builder.Placeholders));
Assert.Equal("true", builder.EnableClusterMode);
Assert.Equal("true", builder.OutOfOrder);
Assert.Equal("200", builder.CommandTimeout);
Assert.True(new List<string>() { "Evolve.Tests.dll" }.SequenceEqual(builder.EmbeddedResourceAssemblies));
Assert.True(new List<string>() { "Evolve.Tests.Resources" }.SequenceEqual(builder.EmbeddedResourceFilters));
}
[Fact]
[Category(Test.Configuration)]
public void Load_multiple_json_configuration_files_works()
{
var builder = new JsonCliArgsBuilder(TestContext.Evolve2JsonPath, env: "staging");
Assert.Equal(@"Server=srv1\dbserver;Port=5432;Database=myDataBase;User Id=myUsername;Password=myPassword;", builder.ConnectionString);
Assert.Equal("postgresql", builder.Database);
Assert.True(new List<string>() { "migration" }.SequenceEqual(builder.Locations));
Assert.Equal("utf-16", builder.Encoding);
Assert.Equal("Ver", builder.SqlMigrationPrefix);
Assert.Equal("Z", builder.SqlRepeatableMigrationPrefix);
Assert.Equal("@", builder.SqlMigrationSeparator);
Assert.Equal(".query", builder.SqlMigrationSuffix);
Assert.Equal("my_shema", builder.Schemas.Single());
Assert.Equal("my_metadata_schema", builder.MetadataTableSchema);
Assert.Equal("metadata_store", builder.MetadataTableName);
Assert.Equal("@{", builder.PlaceholderPrefix);
Assert.Equal("@}", builder.PlaceholderSuffix);
Assert.Equal("2_1_0", builder.TargetVersion);
Assert.Equal("1_1_0", builder.StartVersion);
Assert.True(new List<string>() { "Schema:my_schema", "Pwd:password" }.SequenceEqual(builder.Placeholders));
Assert.Equal("true", builder.EraseDisabled);
Assert.Equal("false", builder.EraseOnValidationError);
Assert.Equal("migrate", builder.Command);
Assert.Equal("false", builder.EnableClusterMode);
Assert.Equal("false", builder.OutOfOrder);
Assert.Null(builder.CommandTimeout);
Assert.True(new List<string>() { "Evolve.Tests.dll" }.SequenceEqual(builder.EmbeddedResourceAssemblies));
Assert.True(new List<string>() { "Evolve.Tests.Resources.Migrations" }.SequenceEqual(builder.EmbeddedResourceFilters));
}
[Fact]
[Category(Test.Configuration)]
public void Load_incomplete_json_configuration_files_works()
{
var builder = new JsonCliArgsBuilder(TestContext.Evolve3JsonPath);
Assert.Equal("Erase", builder.Command);
Assert.Equal("postgresql", builder.Database);
Assert.Equal("Server=127.0.0.1;Port=5432;Database=myDataBase;User Id=myUsername;Password=myPassword;", builder.ConnectionString);
Assert.True(new List<string>() { "migration", "dataset" }.SequenceEqual(builder.Locations));
Assert.Null(builder.Encoding);
Assert.Null(builder.SqlMigrationPrefix);
Assert.Null(builder.SqlRepeatableMigrationPrefix);
Assert.Null(builder.SqlMigrationSeparator);
Assert.Null(builder.SqlMigrationSuffix);
Assert.Null(builder.Schemas);
Assert.Null(builder.MetadataTableSchema);
Assert.Null(builder.MetadataTableName);
Assert.Null(builder.PlaceholderPrefix);
Assert.Null(builder.PlaceholderSuffix);
Assert.Null(builder.TargetVersion);
Assert.Null(builder.StartVersion);
Assert.Empty(builder.Placeholders);
Assert.Null(builder.EraseDisabled);
Assert.Null(builder.EraseOnValidationError);
Assert.Null(builder.EnableClusterMode);
Assert.Null(builder.OutOfOrder);
Assert.Null(builder.CommandTimeout);
Assert.Null(builder.EmbeddedResourceAssemblies);
Assert.Null(builder.EmbeddedResourceFilters);
}
[Fact]
[Category(Test.Configuration)]
public void Build_CommandLine_Args_works()
{
string expected = @"Erase postgresql -c=""Server=127.0.0.1;Port=5432;Database=myDataBase;User Id=myUsername;Password=myPassword;"" -l=""migration"" -l=""dataset"" -s=""my_shema"" --metadata-table-schema=""my_metadata_schema"" --metadata-table=""metadata_store"" -p=""Schema:my_schema"" -p=""Pwd:password"" --placeholder-prefix=@{ --placeholder-suffix=@} --target-version=2_1_0 --start-version=1_1_0 --scripts-prefix=Ver --repeatable-scripts-prefix=Z --scripts-suffix=.query --scripts-separator=@ --encoding=utf-16 --command-timeout=200 --out-of-order=true --erase-disabled=true --erase-on-validation-error=True --enable-cluster-mode=true -a=""Evolve.Tests.dll"" -f=""Evolve.Tests.Resources""";
string actual = new JsonCliArgsBuilder(TestContext.EvolveJsonPath).Build();
Assert.Equal(expected, actual);
}
}
}
| 57.271186 | 705 | 0.661142 |
[
"MIT"
] |
Zarun1/Evolve
|
test/Evolve.Tests/Configuration/JsonCliArgsBuilderTest.cs
| 6,760 |
C#
|
using System;
using System.Xml.Linq;
namespace Java.Interop.Tools.JavaSource
{
public class XmldocSettings
{
public string DocRootValue { get; set; } = string.Empty;
public XElement []? ExtraRemarks { get; set; }
public XmldocStyle Style { get; set; } = XmldocStyle.Full;
}
}
| 22 | 60 | 0.716783 |
[
"MIT"
] |
Wivra/java.interop
|
src/Java.Interop.Tools.JavaSource/Java.Interop.Tools.JavaSource/XmldocSettings.cs
| 286 |
C#
|
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.RabbitMqTransport.Tests
{
using System;
using System.Threading.Tasks;
using NUnit.Framework;
using Turnout.Contracts;
[TestFixture]
public class Creating_a_turnout_job :
RabbitMqTestFixture
{
[Test]
public async Task Should_allow_scheduling_a_job()
{
var endpoint = await Bus.GetSendEndpoint(_commandEndpointAddress);
await endpoint.Send(new ProcessFile
{
Filename = "log.txt",
Size = 1
});
ConsumeContext<JobCompleted> context = await _completed;
await endpoint.Send(new ProcessFile
{
Filename = "log.txt",
Size = 2
});
context = await _completed2;
}
public class ProcessFile
{
public string Filename { get; set; }
public int Size { get; set; }
}
Task<ConsumeContext<JobCompleted>> _completed;
Uri _commandEndpointAddress;
Task<ConsumeContext<JobCompleted>> _completed2;
protected override void ConfigureBusHost(IRabbitMqBusFactoryConfigurator configurator, IRabbitMqHost host)
{
configurator.UseDelayedExchangeMessageScheduler();
base.ConfigureBusHost(configurator, host);
configurator.TurnoutEndpoint<ProcessFile>(host, "process_queue", endpoint =>
{
endpoint.SuperviseInterval = TimeSpan.FromSeconds(1);
endpoint.SetJobFactory(async context => await Task.Delay(TimeSpan.FromSeconds(context.Command.Size)).ConfigureAwait(false));
_commandEndpointAddress = endpoint.InputAddress;
});
}
protected override void ConfigureInputQueueEndpoint(IRabbitMqReceiveEndpointConfigurator configurator)
{
_completed = Handled<JobCompleted>(configurator, context => context.Message.GetArguments<ProcessFile>().Size == 1);
_completed2 = Handled<JobCompleted>(configurator, context => context.Message.GetArguments<ProcessFile>().Size == 2);
}
}
[TestFixture]
public class Stopping_the_bus_before_the_job_is_done :
RabbitMqTestFixture
{
[Test]
public async Task Should_send_the_job_canceled()
{
var endpoint = await Bus.GetSendEndpoint(_commandEndpointAddress);
await endpoint.Send(new ProcessFile
{
Filename = "log.txt",
Size = 10
});
var context = await _started;
Console.WriteLine("Started on address: {0}", context.Message.ManagementAddress);
}
public class ProcessFile
{
public string Filename { get; set; }
public int Size { get; set; }
}
Task<ConsumeContext<JobStarted>> _started;
Uri _commandEndpointAddress;
protected override void ConfigureBusHost(IRabbitMqBusFactoryConfigurator configurator, IRabbitMqHost host)
{
configurator.UseDelayedExchangeMessageScheduler();
base.ConfigureBusHost(configurator, host);
configurator.TurnoutEndpoint<ProcessFile>(host, "process_queue", endpoint =>
{
endpoint.SuperviseInterval = TimeSpan.FromSeconds(1);
endpoint.SetJobFactory(async context =>
{
try
{
await Task.Delay(TimeSpan.FromSeconds(context.Command.Size), context.CancellationToken).ConfigureAwait(false);
}
catch (TaskCanceledException ex)
{
Console.WriteLine("Task was canceled!");
throw;
}
});
_commandEndpointAddress = endpoint.InputAddress;
});
}
protected override void ConfigureInputQueueEndpoint(IRabbitMqReceiveEndpointConfigurator configurator)
{
_started = Handled<JobStarted>(configurator);
}
}
[TestFixture]
public class Cancelling_a_job_using_the_management_address :
RabbitMqTestFixture
{
[Test]
public async Task Should_send_the_job_canceled()
{
var endpoint = await Bus.GetSendEndpoint(_commandEndpointAddress);
await endpoint.Send(new ProcessFile
{
Filename = "log.txt",
Size = 10
});
var context = await _started;
Console.WriteLine("Started on address: {0}", context.Message.ManagementAddress);
var managementEndpoint = await Bus.GetSendEndpoint(context.Message.ManagementAddress);
await managementEndpoint.Send<CancelJob>(new
{
JobId = context.Message.JobId,
Timestamp = DateTime.UtcNow,
Reason = "Impatient!"
});
await _canceled;
Console.WriteLine("Canceled, yea!");
}
public class ProcessFile
{
public string Filename { get; set; }
public int Size { get; set; }
}
Task<ConsumeContext<JobStarted>> _started;
Uri _commandEndpointAddress;
Task<ConsumeContext<JobCanceled<ProcessFile>>> _canceled;
protected override void ConfigureBusHost(IRabbitMqBusFactoryConfigurator configurator, IRabbitMqHost host)
{
configurator.UseDelayedExchangeMessageScheduler();
base.ConfigureBusHost(configurator, host);
configurator.TurnoutEndpoint<ProcessFile>(host, "process_queue", endpoint =>
{
endpoint.SuperviseInterval = TimeSpan.FromSeconds(1);
endpoint.SetJobFactory(async context =>
{
try
{
await Task.Delay(TimeSpan.FromSeconds(context.Command.Size), context.CancellationToken).ConfigureAwait(false);
}
catch (TaskCanceledException ex)
{
Console.WriteLine("Task was canceled!");
throw;
}
});
_commandEndpointAddress = endpoint.InputAddress;
});
}
protected override void ConfigureInputQueueEndpoint(IRabbitMqReceiveEndpointConfigurator configurator)
{
_started = Handled<JobStarted>(configurator);
_canceled = Handled<JobCanceled<ProcessFile>>(configurator);
}
}
}
| 34.20362 | 141 | 0.575605 |
[
"Apache-2.0"
] |
zengdl/MassTransit
|
src/MassTransit.RabbitMqTransport.Tests/Turnout_Specs.cs
| 7,561 |
C#
|
using System;
using NUnit.Framework;
using Org.BouncyCastle.Asn1.Esf;
using Org.BouncyCastle.Asn1.X509;
namespace Org.BouncyCastle.Asn1.Tests
{
[TestFixture]
public class OtherSigningCertificateUnitTest
: Asn1UnitTest
{
public override string Name
{
get { return "OtherSigningCertificate"; }
}
public override void PerformTest()
{
AlgorithmIdentifier algId = new AlgorithmIdentifier(new DerObjectIdentifier("1.2.2.3"));
byte[] digest = new byte[20];
OtherHash otherHash = new OtherHash(
new OtherHashAlgAndValue(algId, digest));
OtherCertID otherCertID = new OtherCertID(otherHash);
OtherSigningCertificate otherCert = new OtherSigningCertificate(otherCertID);
checkConstruction(otherCert, otherCertID);
otherCert = OtherSigningCertificate.GetInstance(null);
if (otherCert != null)
{
Fail("null GetInstance() failed.");
}
try
{
OtherCertID.GetInstance(new Object());
Fail("GetInstance() failed to detect bad object.");
}
catch (ArgumentException)
{
// expected
}
}
private void checkConstruction(
OtherSigningCertificate otherCert,
OtherCertID otherCertID)
{
checkValues(otherCert, otherCertID);
otherCert = OtherSigningCertificate.GetInstance(otherCert);
checkValues(otherCert, otherCertID);
Asn1InputStream aIn = new Asn1InputStream(otherCert.ToAsn1Object().GetEncoded());
Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();
otherCert = OtherSigningCertificate.GetInstance(seq);
checkValues(otherCert, otherCertID);
}
private void checkValues(
OtherSigningCertificate otherCert,
OtherCertID otherCertID)
{
if (otherCert.GetCerts().Length != 1)
{
Fail("GetCerts() length wrong");
}
checkMandatoryField("GetCerts()[0]", otherCertID, otherCert.GetCerts()[0]);
}
public static void MainOld(
string[] args)
{
RunTest(new OtherSigningCertificateUnitTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| 21.989474 | 91 | 0.712303 |
[
"MIT"
] |
TangoCS/BouncyCastle
|
crypto/test/src/asn1/test/OtherSigningCertificateUnitTest.cs
| 2,089 |
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
/// <summary>
/// The type WorkbookFunctionsMdurationRequestBody.
/// </summary>
[DataContract]
public partial class WorkbookFunctionsMdurationRequestBody
{
/// <summary>
/// Gets or sets Settlement.
/// </summary>
[DataMember(Name = "settlement", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken Settlement { get; set; }
/// <summary>
/// Gets or sets Maturity.
/// </summary>
[DataMember(Name = "maturity", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken Maturity { get; set; }
/// <summary>
/// Gets or sets Coupon.
/// </summary>
[DataMember(Name = "coupon", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken Coupon { get; set; }
/// <summary>
/// Gets or sets Yld.
/// </summary>
[DataMember(Name = "yld", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken Yld { get; set; }
/// <summary>
/// Gets or sets Frequency.
/// </summary>
[DataMember(Name = "frequency", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken Frequency { get; set; }
/// <summary>
/// Gets or sets Basis.
/// </summary>
[DataMember(Name = "basis", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken Basis { get; set; }
}
}
| 35.75 | 153 | 0.557576 |
[
"MIT"
] |
MIchaelMainer/GraphAPI
|
src/Microsoft.Graph/Models/Generated/WorkbookFunctionsMdurationRequestBody.cs
| 2,145 |
C#
|
using CSharpAnalyze.Domain.Event;
using Microsoft.CodeAnalysis.Operations;
namespace CSharpAnalyze.Domain.Model.Analyze.Operations
{
/// <summary>
/// Operation:ArrayElementReference
/// </summary>
internal class ArrayElementReference : AbstractOperation
{
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="operation">IOperationインスタンス</param>
/// <param name="container">イベントコンテナ</param>
public ArrayElementReference(IArrayElementReferenceOperation operation, EventContainer container) : base(container)
{
// 型名
Expressions.AddRange(OperationFactory.GetExpressionList(operation.ArrayReference, container));
// 要素取得
Expressions.Add(new Expression("[", string.Empty));
for (var i = 0; i < operation.Indices.Length; i++)
{
Expressions.AddRange(OperationFactory.GetExpressionList(operation.Indices[i], container));
if (i >= 0 && i < operation.Indices.Length - 1)
{
Expressions.Add(new Expression(",", string.Empty));
}
}
Expressions.Add(new Expression("]", string.Empty));
}
}
}
| 32.028571 | 119 | 0.665477 |
[
"MIT"
] |
kazenetu/CSharpAnalyze
|
CSharpAnalyze/Domain/Model/Analyze/Operations/ArrayElementReference.cs
| 1,177 |
C#
|
using BotSharp.Algorithm.HiddenMarkovModel.MathHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BotSharp.Algorithm.HiddenMarkovModel
{
public partial class HiddenMarkovModel
{
/// <summary>
/// Predicts next observations occurring after a given observation sequence.
/// </summary>
public int[] Predict(int[] observations, int next, out double logLikelihood)
{
double[][] logLikelihoods;
return Predict(observations, next, out logLikelihood, out logLikelihoods);
}
/// <summary>
/// Predicts next observations occurring after a given observation sequence.
/// </summary>
public int[] Predict(int[] observations, int next)
{
double logLikelihood;
double[][] logLikelihoods;
return Predict(observations, next, out logLikelihood, out logLikelihoods);
}
/// <summary>
/// Predicts next observations occurring after a given observation sequence.
/// </summary>
public int[] Predict(int[] observations, int next, out double[][] logLikelihoods)
{
double logLikelihood;
return Predict(observations, next, out logLikelihood, out logLikelihoods);
}
/// <summary>
/// Predicts the next observation occurring after a given observation sequence.
/// </summary>
public int Predict(int[] observations, out double[] probabilities)
{
double[][] logLikelihoods;
double logLikelihood;
int prediction = Predict(observations, 1, out logLikelihood, out logLikelihoods)[0];
probabilities = logLikelihoods[0];
return prediction;
}
/// <summary>
/// Predicts the next observations occurring after a given observation sequence (using Viterbi algorithm)
/// </summary>
public int[] Predict(int[] observations, int next, out double logLikelihood, out double[][] logLikelihoods)
{
int T = next;
double[,] logA = LogTransitionMatrix;
double[,] logB = LogEmissionMatrix;
double[] logPi = LogProbabilityVector;
int[] prediction = new int[next];
logLikelihoods = new double[next][];
// Compute forward probabilities for the given observation sequence.
double[,] lnFw0 = ForwardBackwardAlgorithm.LogForward(logA, logB, logPi, observations, out logLikelihood);
// Create a matrix to store the future probabilities for the prediction
// sequence and copy the latest forward probabilities on its first row.
double[,] lnFwd = new double[T + 1, mStateCount];
// 1. Initialization
for (int i = 0; i < mStateCount; i++)
lnFwd[0, i] = lnFw0[observations.Length - 1, i];
// 2. Induction
for (int t = 0; t < T; t++)
{
double[] weights = new double[mSymbolCount];
for (int s = 0; s < mSymbolCount; s++)
{
weights[s] = Double.NegativeInfinity;
for (int i = 0; i < mStateCount; i++)
{
double sum = Double.NegativeInfinity;
for (int j = 0; j < mStateCount; j++)
sum = LogHelper.LogSum(sum, lnFwd[t, j] + logA[j, i]);
lnFwd[t + 1, i] = sum + logB[i, s];
weights[s] = LogHelper.LogSum(weights[s], lnFwd[t + 1, i]);
}
}
double sumWeight = Double.NegativeInfinity;
for (int i = 0; i < weights.Length; i++)
sumWeight = LogHelper.LogSum(sumWeight, weights[i]);
for (int i = 0; i < weights.Length; i++)
weights[i] -= sumWeight;
// Select most probable symbol
double maxWeight = weights[0];
prediction[t] = 0;
for (int i = 1; i < weights.Length; i++)
{
if (weights[i] > maxWeight)
{
maxWeight = weights[i];
prediction[t] = i;
}
}
// Recompute log-likelihood
logLikelihoods[t] = weights;
logLikelihood = maxWeight;
}
return prediction;
}
}
}
| 36.864 | 118 | 0.530599 |
[
"Apache-2.0"
] |
david0718/BotSharp
|
BotSharp.Algorithm/HiddenMarkovModel/HiddenMarkovModel.Predict.cs
| 4,610 |
C#
|
namespace CadastroProduto.View
{
partial class PesquisarProduto
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.buttonPesquisar = new System.Windows.Forms.Button();
this.txtDescricao = new System.Windows.Forms.TextBox();
this.lblDescricao = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// buttonPesquisar
//
this.buttonPesquisar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonPesquisar.Location = new System.Drawing.Point(195, 185);
this.buttonPesquisar.Margin = new System.Windows.Forms.Padding(4);
this.buttonPesquisar.Name = "buttonPesquisar";
this.buttonPesquisar.Size = new System.Drawing.Size(100, 28);
this.buttonPesquisar.TabIndex = 8;
this.buttonPesquisar.Text = "Pesquisar";
this.buttonPesquisar.UseVisualStyleBackColor = true;
this.buttonPesquisar.Click += new System.EventHandler(this.buttonPesquisar_Click);
//
// txtDescricao
//
this.txtDescricao.Location = new System.Drawing.Point(195, 30);
this.txtDescricao.Margin = new System.Windows.Forms.Padding(4);
this.txtDescricao.Name = "txtDescricao";
this.txtDescricao.Size = new System.Drawing.Size(215, 22);
this.txtDescricao.TabIndex = 10;
//
// lblDescricao
//
this.lblDescricao.AutoSize = true;
this.lblDescricao.Location = new System.Drawing.Point(62, 30);
this.lblDescricao.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.lblDescricao.Name = "lblDescricao";
this.lblDescricao.Size = new System.Drawing.Size(71, 17);
this.lblDescricao.TabIndex = 9;
this.lblDescricao.Text = "Descriçao";
//
// PesquisarProduto
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(533, 261);
this.Controls.Add(this.txtDescricao);
this.Controls.Add(this.lblDescricao);
this.Controls.Add(this.buttonPesquisar);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.MinimumSize = new System.Drawing.Size(551, 308);
this.Name = "PesquisarProduto";
this.Text = "PesquisarProduto";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button buttonPesquisar;
private System.Windows.Forms.TextBox txtDescricao;
private System.Windows.Forms.Label lblDescricao;
}
}
| 42.325843 | 165 | 0.594903 |
[
"MIT"
] |
gusgustavoalves/CadastroProduto
|
View/PesquisarProduto.Designer.cs
| 3,770 |
C#
|
#region License
// Copyright (c) 2010-2019, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
namespace Bam.Core
{
/// <summary>
/// Information concerned each .NET framework assembly, including name and
/// required target framework version.
/// </summary>
public sealed class DotNetAssemblyDescription
{
/// <summary>
/// Construct a new instance, including a name.
/// </summary>
/// <param name="name">Name.</param>
public
DotNetAssemblyDescription(
string name) => this.Name = name;
/// <summary>
/// Get the name of the .NET framework assembly.
/// </summary>
/// <value>The name.</value>
public string Name { get; private set; }
/// <summary>
/// Get or set the required target framework version.
/// </summary>
/// <value>The required target framework.</value>
public string RequiredTargetFramework { get; set; }
}
}
| 42.372881 | 81 | 0.6988 |
[
"BSD-3-Clause"
] |
markfinal/BuildAMation
|
Bam.Core/Package/DotNetAssemblyDescription.cs
| 2,500 |
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CivGen
{
using System;
using System.Collections.Generic;
public partial class BoostName
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public BoostName()
{
this.BoostHandlers = new HashSet<BoostHandler>();
this.Boosts = new HashSet<Boost>();
}
public string BoostType { get; set; }
public long BoostValue { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<BoostHandler> BoostHandlers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Boost> Boosts { get; set; }
}
}
| 40.242424 | 128 | 0.603916 |
[
"MIT"
] |
ls612/CFCGen
|
CivGen/BoostName.cs
| 1,328 |
C#
|
using System.Web.Mvc;
using Ext.Net.MVC.Examples.Areas.DragDrop_Grid.Models;
namespace Ext.Net.MVC.Examples.Areas.DragDrop_Grid.Controllers
{
public class Cell_to_CellController : Controller
{
public ActionResult Index()
{
return View(new Cell_to_CellModel());
}
}
}
| 22.642857 | 62 | 0.675079 |
[
"Apache-2.0"
] |
yataya1987/EXT.Net-Theme-Hard-Coded
|
src/Areas/DragDrop_Grid/Controllers/Cell_to_CellController.cs
| 319 |
C#
|
// Instance generated by TankLibHelper.InstanceBuilder
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0x5CE04BB1)]
public class STU_5CE04BB1 : STUGenericSettings_Base {
[STUFieldAttribute(0x45A7A69C, "m_default", ReaderType = typeof(InlineInstanceFieldReader))]
public STU_25D5B0B1 m_default;
[STUFieldAttribute(0x2DAD8E99, ReaderType = typeof(InlineInstanceFieldReader))]
public STU_25D5B0B1 m_2DAD8E99;
[STUFieldAttribute(0x0630F9D3, ReaderType = typeof(InlineInstanceFieldReader))]
public STU_25D5B0B1 m_0630F9D3;
[STUFieldAttribute(0x81DBAA1A, ReaderType = typeof(InlineInstanceFieldReader))]
public STU_FA600F04 m_81DBAA1A;
[STUFieldAttribute(0xC1926B2B, ReaderType = typeof(InlineInstanceFieldReader))]
public STU_FA600F04 m_C1926B2B;
[STUFieldAttribute(0xDA4846A5, ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_25D5B0B1[] m_DA4846A5;
[STUFieldAttribute(0x1C413B73, ReaderType = typeof(InlineInstanceFieldReader))]
public STU_239267EA[] m_1C413B73;
[STUFieldAttribute(0x54B68306)]
public float m_54B68306;
[STUFieldAttribute(0x1D7C8ACE)]
public float m_1D7C8ACE;
[STUFieldAttribute(0x4D65010B)]
public float m_4D65010B;
[STUFieldAttribute(0x503F626D)]
public float m_503F626D;
}
}
| 34.731707 | 100 | 0.724719 |
[
"MIT"
] |
Mike111177/OWLib
|
TankLib/STU/Types/STU_5CE04BB1.cs
| 1,424 |
C#
|
/*
* Copyright 2020 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
using System;
using System.Web.Mvc;
using ServiceStack.Redis;
namespace BasicMvcApplication.Controllers
{
public class RedisController : Controller
{
public string Get()
{
using (var client = new RedisClient("localhost"))
{
client.ServerVersionNumber = 1;
ThisIsBadAndYouShouldFeelBad.SwallowExceptionsFromInvalidRedisHost(() => client.SaveAsync());
ThisIsBadAndYouShouldFeelBad.SwallowExceptionsFromInvalidRedisHost(() => client.Shutdown());
ThisIsBadAndYouShouldFeelBad.SwallowExceptionsFromInvalidRedisHost(() => client.RewriteAppendOnlyFileAsync());
}
return "Worked";
}
public class ThisIsBadAndYouShouldFeelBad
{
public static void SwallowExceptionsFromInvalidRedisHost(Action command)
{
try
{
command();
}
catch
{
//For reals, we should test against a real redis instance instead of
//throwing exceptions every call.
}
}
}
}
}
| 29.088889 | 126 | 0.572956 |
[
"Apache-2.0"
] |
Faithlife/newrelic-dotnet-agent
|
tests/Agent/IntegrationTests/Applications/BasicMvcApplication/Controllers/RedisController.cs
| 1,309 |
C#
|
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace VoxelImporter.grendgine_collada
{
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(ElementName="shader", Namespace="http://www.collada.org/2005/11/COLLADASchema", IsNullable=true)]
public partial class Grendgine_Collada_Shader
{
[XmlAttribute("stage")]
[System.ComponentModel.DefaultValueAttribute(Grendgine_Collada_Shader_Stage.VERTEX)]
public Grendgine_Collada_Shader_Stage Stage;
[XmlElement(ElementName = "sources")]
public Grendgine_Collada_Shader_Sources Sources;
}
}
| 28.458333 | 141 | 0.805271 |
[
"MIT"
] |
Syrapt0r/Protocol-18
|
Assets/VoxelImporter/Scripts/Editor/Library/Collada_Main/Collada_FX/Shaders/Grendgine_Collada_Shader.cs
| 683 |
C#
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using Minsk.CodeAnalysis.Text;
namespace Minsk.CodeAnalysis.Syntax
{
public sealed class SyntaxTree
{
private delegate void ParseHandler(SyntaxTree syntaxTree,
out CompilationUnitSyntax root,
out ImmutableArray<Diagnostic> diagnostics);
private SyntaxTree(SourceText text, ParseHandler handler)
{
Text = text;
handler(this, out var root, out var diagnostics);
Diagnostics = diagnostics;
Root = root;
}
public SourceText Text { get; }
public ImmutableArray<Diagnostic> Diagnostics { get; }
public CompilationUnitSyntax Root { get; }
public static SyntaxTree Load(string fileName)
{
var text = File.ReadAllText(fileName);
var sourceText = SourceText.From(text, fileName);
return Parse(sourceText);
}
private static void Parse(SyntaxTree syntaxTree, out CompilationUnitSyntax root, out ImmutableArray<Diagnostic> diagnostics)
{
var parser = new Parser(syntaxTree);
root = parser.ParseCompilationUnit();
diagnostics = parser.Diagnostics.ToImmutableArray();
}
public static SyntaxTree Parse(string text)
{
var sourceText = SourceText.From(text);
return Parse(sourceText);
}
public static SyntaxTree Parse(SourceText text)
{
return new SyntaxTree(text, Parse);
}
public static ImmutableArray<SyntaxToken> ParseTokens(string text)
{
var sourceText = SourceText.From(text);
return ParseTokens(sourceText);
}
public static ImmutableArray<SyntaxToken> ParseTokens(string text, out ImmutableArray<Diagnostic> diagnostics)
{
var sourceText = SourceText.From(text);
return ParseTokens(sourceText, out diagnostics);
}
public static ImmutableArray<SyntaxToken> ParseTokens(SourceText text)
{
return ParseTokens(text, out _);
}
public static ImmutableArray<SyntaxToken> ParseTokens(SourceText text, out ImmutableArray<Diagnostic> diagnostics)
{
var tokens = new List<SyntaxToken>();
void ParseTokens(SyntaxTree st, out CompilationUnitSyntax root, out ImmutableArray<Diagnostic> d)
{
root = null;
var l = new Lexer(st);
while (true)
{
var token = l.Lex();
if (token.Kind == SyntaxKind.EndOfFileToken)
{
root = new CompilationUnitSyntax(st, ImmutableArray<MemberSyntax>.Empty, token);
break;
}
tokens.Add(token);
}
d = l.Diagnostics.ToImmutableArray();
}
var syntaxTree = new SyntaxTree(text, ParseTokens);
diagnostics = syntaxTree.Diagnostics.ToImmutableArray();
return tokens.ToImmutableArray();
}
}
}
| 33.131313 | 132 | 0.57622 |
[
"MIT"
] |
CBenghi/minsk
|
src/Minsk/CodeAnalysis/Syntax/SyntaxTree.cs
| 3,280 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using UndefinableOfT;
// ReSharper disable PossibleInvalidOperationException
// ReSharper disable NonReadonlyMemberInGetHashCode
// ReSharper disable once CheckNamespace
namespace System
{
/// <summary>
/// Represents values that can be either undefined or an instance of the type (or null).
/// </summary>
[JsonConverter(typeof(UndefinableJsonConverter))]
public struct Undefinable<T>
{
/// <summary>
/// Returns the default value for this struct, which represents an undefined value.
/// </summary>
public static Undefinable<T> Undefined => default;
private T _value;
private bool _isDefined;
/// <summary>
/// Instantiates the Undefined class with a value.
/// </summary>
/// <param name="value"></param>
public Undefinable(T value)
{
_isDefined = true;
_value = value;
}
/// <summary>
/// True if a value has been set, even if it is null.
/// </summary>
public bool IsDefined => _isDefined;
/// <summary>
/// Gets the value of the current <see cref="Undefinable{T}"/>.
/// </summary>
public T Value
{
get
{
if (_isDefined)
{
return _value;
}
throw new InvalidOperationException("The value is undefined.");
}
}
/// <summary>
/// Conversion from value type.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator Undefinable<T>(T value)
{
return new Undefinable<T>
{
_isDefined = true,
_value = value
};
}
/// <summary>
/// Gets the wrapped value or the default of T.
/// </summary>
/// <returns></returns>
public T GetValueOrDefault()
{
return _isDefined ? _value : default;
}
public T GetValueOrDefault(T defaultValue)
{
return _isDefined ? _value : defaultValue;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <returns>
/// true if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
/// <param name="other">Another object to compare to. </param>
public override bool Equals(object other)
{
if (other == null)
{
return this._value == null;
}
if (other is Undefinable<T> anotherUndefined)
{
if (!this._isDefined && !anotherUndefined._isDefined)
{
return true;
}
}
var otherType = other.GetType();
if (otherType.IsGenericType && otherType.GetGenericTypeDefinition() == typeof(Undefinable<>))
{
//special case for types where one may be nullable and the other not
//e.g. we want Undefined<int?> and Undefined<int> to use the same equality comparison
var otherTypeArgument = otherType.GetGenericArguments().Single();
var thisTypeArgument = typeof(T);
if (TypeExtensions.DoTypesResolveToSameCoreType(otherTypeArgument, thisTypeArgument))
{
// ReSharper disable once PossibleNullReferenceException
if (!this._isDefined && !(bool) otherType.GetField(nameof(_isDefined),
BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(other))
{
return true;
}
// ReSharper disable once PossibleNullReferenceException
var otherValue = otherType
.GetField(nameof(_value), BindingFlags.Instance | BindingFlags.NonPublic).GetValue(other);
if (otherValue == null && _value == null)
{
return true;
}
return _value.Equals(otherValue);
}
}
//special case for structs - otherwise it would be equal since value would be set to something
if (!typeof(T).IsClass)
{
if (!_isDefined)
{
return false;
}
}
return _value.Equals(other);
}
/// <summary>
/// Implementation of the equals operator.
/// </summary>
/// <param name="t1"></param>
/// <param name="t2"></param>
/// <returns></returns>
public static bool operator ==(Undefinable<T> t1, Undefinable<T> t2)
{
// undefined equals undefined
if (!t1._isDefined && !t2.IsDefined) return true;
// undefined != everything else
if (t1._isDefined ^ t2._isDefined) return false;
if (t1._value == null && t2._value == null)
{
return true;
}
if (t1._value == null)
{
return t2._value.Equals(t1._value);
}
// if both are values, compare them
return t1._value.Equals(t2._value);
}
/// <summary>
/// Implementation of the inequality operator.
/// </summary>
/// <returns></returns>
public static bool operator !=(Undefinable<T> t1, Undefinable<T> t2)
{
return !(t1 == t2);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
if (!_isDefined)
{
return -1;
}
return _value.GetHashCode();
}
/// <summary>
/// Returns a text representation of
/// the value, or an empty string if no value
/// is present.
/// </summary>
public override string ToString()
{
if (!_isDefined)
{
return string.Empty;
}
return _value?.ToString() ?? string.Empty;
}
}
}
| 32.238532 | 129 | 0.482499 |
[
"MIT"
] |
schneidenbach/UndefinableOfT
|
src/UndefinableOfT/Undefinable`1.cs
| 7,030 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace hard
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ThueMorseGame.get(30, 3));
Console.WriteLine(ThueMorseGame.get(499999975, 49));
}
}
}
class ThueMorseGame
{
public static string get(int n, int m)
{
bool[] win = new bool[n + 1];
for (int j = 1; j <= n; j++)
{
for (int i = 1; i <= m; i++)
{
win[j] |= i <= j && !win[j - i];
}
}
if (win[n]) return "Alice";
else return "Bob";
}
}
| 19.314286 | 64 | 0.477811 |
[
"MIT"
] |
yu3mars/procon
|
topcoder/srm701/hard/Program.cs
| 678 |
C#
|
namespace Difi.SikkerDigitalPost.Klient.Domene.Entiteter.Interface
{
public interface IAsiceAttachable
{
string Filnavn { get; }
byte[] Bytes { get; }
string MimeType { get; }
string Id { get; }
}
}
| 18.923077 | 67 | 0.597561 |
[
"Apache-2.0"
] |
difi/difi-sikker-digital-post-klient-dotnet
|
Difi.SikkerDigitalPost.Klient.Domene/Entiteter/Interface/IAsiceAttachable.cs
| 248 |
C#
|
using SpreadCommander.Common.SqlScript;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SpreadCommander.Common.Code
{
public class ObjectDataReader : DbDataReader, IListSource
{
private readonly object _DataSource;
private IEnumerator _Enumerator;
private int _RowCounter;
private readonly CancellationToken _CancelToken;
private readonly List<PropertyInfo> _Properties = new List<PropertyInfo>();
public ObjectDataReader(IEnumerable dataSource, Type objectType) : this(dataSource, objectType, CancellationToken.None)
{
}
public ObjectDataReader(IEnumerable dataSource, Type objectType, CancellationToken cancelToken)
{
_DataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource));
_Enumerator = dataSource.GetEnumerator();
_CancelToken = cancelToken;
var properties = objectType.GetProperties();
_Properties.AddRange(properties);
FilterProperties();
}
public ObjectDataReader(IEnumerable dataSource, IEnumerable<PropertyInfo> properties) : this(dataSource, properties, CancellationToken.None)
{
}
public ObjectDataReader(IEnumerable dataSource, IEnumerable<PropertyInfo> properties, CancellationToken cancelToken)
{
_DataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource));
_Enumerator = dataSource.GetEnumerator();
_CancelToken = cancelToken;
_Properties.AddRange(properties);
FilterProperties();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_Enumerator != null)
_Enumerator = null;
}
public IList GetList() => _DataSource as IList;
public IEnumerator Enumerator => _Enumerator;
//Have both properties to maintain compatibility with ObjectDataReader<T>
public IList List => _Enumerator as IList;
public IList SimpleList => _Enumerator as IList;
public DbDataReaderResult Result { get; private set; }
public int MaxRows { get; set; } = -1;
public void Cancel()
{
switch (Result)
{
case DbDataReaderResult.Reading:
case DbDataReaderResult.FinishedTable:
Result = DbDataReaderResult.Cancelled;
break;
}
}
//DbDataReader properties and methods.
public override int Depth => 0;
public override int FieldCount => _Properties.Count;
public override bool HasRows => (GetList()?.Count ?? 1) > 0;
public override bool IsClosed => _Enumerator == null;
public override int RecordsAffected => -1;
public override int VisibleFieldCount => FieldCount;
public bool ContainsListCollection => false;
public int RowCount => GetList()?.Count ?? 0;
public int ProcessedRowCount => _RowCounter;
//Remove properties that are not primitive type.
//This class is using to insert data into spreadsheet, database etc.,
//so properties with non-primitive type are not needed.
protected void FilterProperties()
{
int i = _Properties.Count - 1;
while (i >= 0)
{
var property = _Properties[i];
if (!AcceptType(property))
_Properties.RemoveAt(i);
i--;
}
static bool AcceptType(PropertyInfo propInfo)
{
if (propInfo.PropertyType == typeof(Guid))
return true;
if (propInfo.PropertyType == typeof(TimeSpan))
return true;
return (Type.GetTypeCode(propInfo.PropertyType)) switch
{
TypeCode.Empty or TypeCode.Object or TypeCode.DBNull => false,
TypeCode.Boolean or TypeCode.SByte or TypeCode.Byte or
TypeCode.Int16 or TypeCode.UInt16 or TypeCode.Int32 or
TypeCode.UInt32 or TypeCode.Int64 or TypeCode.UInt64 or
TypeCode.Single or TypeCode.Double or TypeCode.Decimal or
TypeCode.DateTime or TypeCode.String or TypeCode.Char => true,
_ => false,
};
}
}
public override object this[int ordinal]
{
get
{
if (_Enumerator.Current == null)
return null;
if (ordinal < 0 || ordinal >= _Properties.Count)
return null;
return _Properties[ordinal].GetValue(_Enumerator.Current);
}
}
public override object this[string name] => this[GetOrdinal(name)];
public override void Close()
{
if (_Enumerator != null)
_Enumerator = null;
}
public override bool GetBoolean(int ordinal) => Convert.ToBoolean(this[ordinal]);
public override byte GetByte(int ordinal) => Convert.ToByte(this[ordinal]);
public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) =>
throw new NotImplementedException();
public override char GetChar(int ordinal) => Convert.ToChar(this[ordinal]);
public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) =>
throw new NotImplementedException();
public override string GetDataTypeName(int ordinal)
{
if (ordinal < 0 || ordinal >= _Properties.Count)
return null;
var result = SpreadCommander.Common.SqlScript.SqlScript.GetColumnDataType(_Properties[ordinal].PropertyType, int.MaxValue);
return result;
}
public override DateTime GetDateTime(int ordinal) => Convert.ToDateTime(this[ordinal]);
protected override DbDataReader GetDbDataReader(int ordinal) =>
throw new NotImplementedException();
public override decimal GetDecimal(int ordinal) => Convert.ToDecimal(this[ordinal]);
public override double GetDouble(int ordinal) => Convert.ToDouble(this[ordinal]);
[EditorBrowsable(EditorBrowsableState.Never)]
public override IEnumerator GetEnumerator() => new DbEnumerator(this);
public override Type GetFieldType(int ordinal)
{
if (ordinal < 0 || ordinal >= _Properties.Count)
return null;
return _Properties[ordinal].PropertyType;
}
public override float GetFloat(int ordinal) => (float)Convert.ToDouble(this[ordinal]);
public override Guid GetGuid(int ordinal)
{
object value = this[ordinal];
if (value is Guid guid)
return guid;
var strValue = Convert.ToString(value);
var result = Guid.Parse(strValue);
return result;
}
public override short GetInt16(int ordinal) => Convert.ToInt16(this[ordinal]);
public override int GetInt32(int ordinal) => Convert.ToInt32(this[ordinal]);
public override long GetInt64(int ordinal) => Convert.ToInt64(this[ordinal]);
public override string GetName(int ordinal)
{
if (ordinal < 0 || ordinal >= _Properties.Count)
return null;
return _Properties[ordinal].Name;
}
public override int GetOrdinal(string name)
{
for (int i = 0; i < _Properties.Count; i++)
{
var property = _Properties[i];
if (property.Name == name)
return i;
}
return -1;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override Type GetProviderSpecificFieldType(int ordinal) => GetFieldType(ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override object GetProviderSpecificValue(int ordinal) => this[ordinal];
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetProviderSpecificValues(object[] values) => GetValues(values);
public override DataTable GetSchemaTable()
{
var result = new DataTable("Schema");
result.Columns.Add("ColumnName", typeof(string));
result.Columns.Add("ColumnOrdinal", typeof(int));
result.Columns.Add("ColumnSize", typeof(int));
result.Columns.Add("DataType", typeof(Type));
result.Columns.Add("IsUnique", typeof(bool));
result.Columns.Add("IsKey", typeof(bool));
for (int i = 0; i < _Properties.Count; i++)
{
var property = _Properties[i];
var row = result.NewRow();
row["ColumnName"] = property.Name;
row["ColumnOrdinal"] = i;
row["ColumnSize"] = CalcColumnSize(property);
row["DataType"] = property.PropertyType;
row["IsUnique"] = false;
row["IsKey"] = false;
result.Rows.Add(row);
}
return result;
int CalcColumnSize(PropertyInfo propInfo)
{
switch (Type.GetTypeCode(propInfo.PropertyType))
{
case TypeCode.Empty:
return 0;
case TypeCode.Object:
return 0;
case TypeCode.DBNull:
return 0;
case TypeCode.Boolean:
return 1;
case TypeCode.SByte:
return 1;
case TypeCode.Byte:
return 1;
case TypeCode.Int16:
return 2;
case TypeCode.UInt16:
return 2;
case TypeCode.Int32:
return 4;
case TypeCode.UInt32:
return 4;
case TypeCode.Int64:
return 8;
case TypeCode.UInt64:
return 8;
case TypeCode.Single:
return 4;
case TypeCode.Double:
return 8;
case TypeCode.Decimal:
return 29;
case TypeCode.DateTime:
return 8;
case TypeCode.String:
case TypeCode.Char:
if (_DataSource is IList list)
{
int colSize = 0;
foreach (var item in list)
{
var strValue = Convert.ToString(propInfo.GetValue(item));
if (strValue != null && strValue.Length > colSize)
colSize = strValue.Length;
}
return Math.Max(colSize, 1);
}
else
return int.MaxValue;
default:
return 0;
}
}
}
public override string GetString(int ordinal) => Convert.ToString(this[ordinal]);
public override object GetValue(int ordinal)
{
var value = this[ordinal];
var result = (value == null) || (value == DBNull.Value);
return result;
}
public override int GetValues(object[] values)
{
if (values == null)
return 0;
var len = Math.Min(_Properties.Count, values.Length);
for (int i = 0; i < len; i++)
values[i] = this[i];
return len;
}
public override bool IsDBNull(int ordinal) => this[ordinal] == null;
public override bool NextResult() => false;
public override bool Read()
{
if (Result != DbDataReaderResult.Reading)
return false;
if (_CancelToken.IsCancellationRequested)
{
Result = DbDataReaderResult.Cancelled;
return false;
}
bool result = _Enumerator.MoveNext();
if (!result)
Result = DbDataReaderResult.FinishedTable;
_RowCounter++;
if (result && MaxRows >= 0 && _RowCounter > MaxRows)
{
Result = DbDataReaderResult.MaxRowsReached;
return false;
}
return result;
}
}
}
| 34.635417 | 148 | 0.542256 |
[
"Apache-2.0"
] |
VassilievVV/SpreadCommander
|
SpreadCommander.Common/Code/UntypedObjectDataReader.cs
| 13,302 |
C#
|
using System;
namespace LibMMD.Unity3D
{
public class ByteArrayReader
{
public static int ReadInt(byte[] data, ref int offset) {
var ret = BitConverter.ToInt32(data, offset);
offset += 4;
return ret;
}
public static uint ReadUInt(byte[] data, ref int offset) {
var ret = BitConverter.ToUInt32(data, offset);
offset += 4;
return ret;
}
public static short ReadShort(byte[] data, ref int offset) {
var ret = BitConverter.ToInt16(data, offset);
offset += 2;
return ret;
}
public static ushort ReadUShort(byte[] data, ref int offset) {
var ret = BitConverter.ToUInt16(data, offset);
offset += 2;
return ret;
}
}
}
| 20.333333 | 64 | 0.663189 |
[
"BSD-3-Clause"
] |
OneYoungMean/libmmd-for-unity
|
Assets/LibMmd/Unity3D/ByteArrayReader.cs
| 673 |
C#
|
#region copyright
/* MIT License
Copyright (c) 2019 Martin Lange ([email protected])
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. */
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using DataBase.Interfaces;
namespace DataBase.UndoRedo
{
/// <summary>
/// Handling the undo/redo actions and states
/// </summary>
public sealed class UndoRedoStack
{
/// <summary>
/// Container for a single undo/redo item
/// </summary>
private struct UndoRedoItem
{
internal IUndoRedoableNode Node { get; set; }
internal object OldValue { get; set; }
internal object NewValue { get; set; }
}
/*
internal sealed class UndoRedoItem
{
public IUndoRedoableNode Node { get; set; }
public object OldValue { get; set; }
public object NewValue { get; set; }
}
*/
private bool _undoRedoing;
private readonly List<UndoRedoItem> _stack = new List<UndoRedoItem>();
private bool _canUndo;
private bool _canRedo;
public UndoRedoStack() => UpdateCanUndoRedo();
/// <summary>
/// Set the specified value avoiding recursive loop
/// </summary>
private void SafeSetValue(object value)
{
if (_undoRedoing)
{
return;
}
_undoRedoing = true;
try
{
_stack[Pointer].Node.Set(value);
}
finally
{
_undoRedoing = false;
}
}
/// <summary>
/// Updates the state of the CanUndo and CanRedo properties
/// </summary>
private void UpdateCanUndoRedo()
{
CanUndo = (_stack.Count > 0) && (Pointer >= 0);
CanRedo = (_stack.Count > 0) && (Pointer < (_stack.Count - 1));
UndoRedoListChanged?.Invoke();
}
/// <summary>
/// The last change made to the data tree is reverted
/// </summary>
public void Undo(int count = 1)
{
if (Pointer < 0)
{
throw new InvalidOperationException("DataContainer.Undo: pointer to undo stack already at lower limit");
}
count.TimesDo(i =>
{
Debug.WriteLine("Undo: OldValue=" + _stack[Pointer].OldValue + " Ptr=" + Pointer);
SafeSetValue(_stack[Pointer].OldValue);
Pointer--;
UpdateCanUndoRedo();
});
}
/// <summary>
/// The last undo action made to the data tree is reverted
/// </summary>
public void Redo(int count = 1)
{
if (Pointer >= (_stack.Count - 1))
{
throw new InvalidOperationException("DataContainer.Undo: pointer to redo stack already at upper limit");
}
count.TimesDo(i =>
{
Pointer++;
Debug.WriteLine("Redo: NewValue=" + _stack[Pointer].NewValue + " Ptr=" + Pointer);
SafeSetValue(_stack[Pointer].NewValue);
UpdateCanUndoRedo();
});
}
/// <summary>
/// Returns true if the any change to the data tree can be reverted
/// </summary>
public bool CanUndo
{
get => _canUndo;
private set
{
if (CanUndo == value)
{
return;
}
_canUndo = value;
CanUndoRedoChanged?.Invoke();
}
}
/// <summary>
/// Returns true if any formerly undone change to the data tree can be redone
/// </summary>
public bool CanRedo
{
get => _canRedo;
private set
{
if (CanRedo == value)
{
return;
}
_canRedo = value;
CanUndoRedoChanged?.Invoke();
}
}
/// <summary>
/// Event fired when either the CanUndo or then CanRedo property has changed it's state
/// </summary>
public event Action CanUndoRedoChanged;
/// <summary>
/// Event fired when either the UndoList and/or then RedoList has changed
/// </summary>
public event Action UndoRedoListChanged;
/// <summary>
/// Stores the change of the specified paramerter with it's old and new value in the undo/redo stack
/// </summary>
/// <param name="dataNode">The data node who's value was changed</param>
/// <param name="oldValue">The former value of the parameter</param>
/// <param name="newValue">The new value of the parameter</param>
internal void ValueChanged(IUndoRedoableNode dataNode, object oldValue, object newValue)
{
if (_undoRedoing || IsMuted)
{
return;
}
// clear "Redo"-Entries when new change has occurred
if (_stack.Count > 0 && Pointer < (_stack.Count - 1))
{
_stack.RemoveRange(Pointer + 1, _stack.Count - Pointer - 1);
}
var undoItem = new UndoRedoItem()
{
Node = dataNode,
OldValue = oldValue,
NewValue = newValue
};
_stack.Add(undoItem);
Pointer++;
UpdateCanUndoRedo();
Debug.WriteLine("ValueChanged: " + undoItem.Node + " => " + newValue + " ptr=" + Pointer);
}
/// <summary>
/// Clears the undo/redo stack
/// </summary>
public void Clear()
{
_stack.Clear();
Pointer = -1;
UpdateCanUndoRedo();
}
/// <summary>
/// Returns a list of the changes on the undo stack that can be undone
/// </summary>
public IList<string> UndoList
{
get
{
var result = new List<string>();
if (Pointer < 0)
{
return result;
}
for (var i = Pointer; i >= 0; i--)
{
var item = _stack[i];
result.Add($"{item.Node.Designation}: {item.NewValue} -> {item.OldValue}");
}
return result;
}
}
/// <summary>
/// Returns a list of the changes on the redo stack that can be undone
/// </summary>
public IList<string> RedoList
{
get
{
var result = new List<string>();
for (var i = Pointer + 1; i < _stack.Count; i++)
{
var item = _stack[i];
result.Add($"{item.Node.Designation}: {item.OldValue} -> {item.NewValue}");
}
return result;
}
}
/// <summary>
/// If set the undo/redo stack is not updated
/// </summary>
internal bool IsMuted { private get; set; }
/// <summary>
/// Returns the current state of the stack pointer
/// </summary>
public int Pointer { get; private set; } = -1;
// for testing purposes only
internal int Count => _stack.Count;
}
}
| 31.978182 | 121 | 0.504094 |
[
"MIT"
] |
martinlangee/DataTree
|
DataTreeBase/UndoRedo/UndoRedoStack.cs
| 8,794 |
C#
|
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V24.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V24.Segment{
///<summary>
/// Represents an HL7 OM2 message segment.
/// This segment has the following fields:<ol>
///<li>OM2-1: Sequence Number - Test/ Observation Master File (NM)</li>
///<li>OM2-2: Units of Measure (CE)</li>
///<li>OM2-3: Range of Decimal Precision (NM)</li>
///<li>OM2-4: Corresponding SI Units of Measure (CE)</li>
///<li>OM2-5: SI Conversion Factor (TX)</li>
///<li>OM2-6: Reference (Normal) Range - Ordinal and Continuous Observations (RFR)</li>
///<li>OM2-7: Critical Range for Ordinal and Continuous Observations (NR)</li>
///<li>OM2-8: Absolute Range for Ordinal and Continuous Observations (RFR)</li>
///<li>OM2-9: Delta Check Criteria (DLT)</li>
///<li>OM2-10: Minimum Meaningful Increments (NM)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class OM2 : AbstractSegment {
/**
* Creates a OM2 (Numeric Observation) segment object that belongs to the given
* message.
*/
public OM2(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(NM), false, 1, 4, new System.Object[]{message}, "Sequence Number - Test/ Observation Master File");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Units of Measure");
this.add(typeof(NM), false, 0, 10, new System.Object[]{message}, "Range of Decimal Precision");
this.add(typeof(CE), false, 1, 250, new System.Object[]{message}, "Corresponding SI Units of Measure");
this.add(typeof(TX), false, 1, 60, new System.Object[]{message}, "SI Conversion Factor");
this.add(typeof(RFR), false, 1, 250, new System.Object[]{message}, "Reference (Normal) Range - Ordinal and Continuous Observations");
this.add(typeof(NR), false, 1, 205, new System.Object[]{message}, "Critical Range for Ordinal and Continuous Observations");
this.add(typeof(RFR), false, 1, 250, new System.Object[]{message}, "Absolute Range for Ordinal and Continuous Observations");
this.add(typeof(DLT), false, 0, 250, new System.Object[]{message}, "Delta Check Criteria");
this.add(typeof(NM), false, 1, 20, new System.Object[]{message}, "Minimum Meaningful Increments");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns Sequence Number - Test/ Observation Master File(OM2-1).
///</summary>
public NM SequenceNumberTestObservationMasterFile
{
get{
NM ret = null;
try
{
IType t = this.GetField(1, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Units of Measure(OM2-2).
///</summary>
public CE UnitsOfMeasure
{
get{
CE ret = null;
try
{
IType t = this.GetField(2, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Range of Decimal Precision(OM2-3).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public NM GetRangeOfDecimalPrecision(int rep)
{
NM ret = null;
try
{
IType t = this.GetField(3, rep);
ret = (NM)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Range of Decimal Precision (OM2-3).
///</summary>
public NM[] GetRangeOfDecimalPrecision() {
NM[] ret = null;
try {
IType[] t = this.GetField(3);
ret = new NM[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (NM)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Range of Decimal Precision (OM2-3).
///</summary>
public int RangeOfDecimalPrecisionRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(3);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Corresponding SI Units of Measure(OM2-4).
///</summary>
public CE CorrespondingSIUnitsOfMeasure
{
get{
CE ret = null;
try
{
IType t = this.GetField(4, 0);
ret = (CE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns SI Conversion Factor(OM2-5).
///</summary>
public TX SIConversionFactor
{
get{
TX ret = null;
try
{
IType t = this.GetField(5, 0);
ret = (TX)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Reference (Normal) Range - Ordinal and Continuous Observations(OM2-6).
///</summary>
public RFR ReferenceNormalRangeOrdinalAndContinuousObservations
{
get{
RFR ret = null;
try
{
IType t = this.GetField(6, 0);
ret = (RFR)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Critical Range for Ordinal and Continuous Observations(OM2-7).
///</summary>
public NR CriticalRangeForOrdinalAndContinuousObservations
{
get{
NR ret = null;
try
{
IType t = this.GetField(7, 0);
ret = (NR)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Absolute Range for Ordinal and Continuous Observations(OM2-8).
///</summary>
public RFR AbsoluteRangeForOrdinalAndContinuousObservations
{
get{
RFR ret = null;
try
{
IType t = this.GetField(8, 0);
ret = (RFR)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Delta Check Criteria(OM2-9).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public DLT GetDeltaCheckCriteria(int rep)
{
DLT ret = null;
try
{
IType t = this.GetField(9, rep);
ret = (DLT)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Delta Check Criteria (OM2-9).
///</summary>
public DLT[] GetDeltaCheckCriteria() {
DLT[] ret = null;
try {
IType[] t = this.GetField(9);
ret = new DLT[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (DLT)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Delta Check Criteria (OM2-9).
///</summary>
public int DeltaCheckCriteriaRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(9);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Minimum Meaningful Increments(OM2-10).
///</summary>
public NM MinimumMeaningfulIncrements
{
get{
NM ret = null;
try
{
IType t = this.GetField(10, 0);
ret = (NM)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
}}
| 36.075843 | 141 | 0.654442 |
[
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] |
afaonline/nHapi
|
src/NHapi.Model.V24/Segment/OM2.cs
| 12,843 |
C#
|
namespace tomenglertde.ResXManager.View.Behaviors
{
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using DataGridExtensions;
using JetBrains.Annotations;
using Microsoft.Xaml.Behaviors;
using tomenglertde.ResXManager.Model;
using tomenglertde.ResXManager.View.ColumnHeaders;
using TomsToolbox.Wpf;
public class ShowErrorsOnlyBehavior : Behavior<DataGrid>
{
[CanBeNull]
public ToggleButton ToggleButton
{
get => (ToggleButton)GetValue(ToggleButtonProperty);
set => SetValue(ToggleButtonProperty, value);
}
/// <summary>
/// Identifies the ToggleButton dependency property
/// </summary>
[NotNull]
public static readonly DependencyProperty ToggleButtonProperty =
DependencyProperty.Register("ToggleButton", typeof(ToggleButton), typeof(ShowErrorsOnlyBehavior), new FrameworkPropertyMetadata(null, (sender, e) => ((ShowErrorsOnlyBehavior)sender).ToggleButton_Changed((ToggleButton)e.OldValue, (ToggleButton)e.NewValue)));
public void Refresh()
{
Refresh(ToggleButton);
}
protected override void OnAttached()
{
base.OnAttached();
DataGrid.GetAdditionalEvents().ColumnVisibilityChanged += DataGrid_ColumnVisibilityChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
DataGrid.GetAdditionalEvents().ColumnVisibilityChanged -= DataGrid_ColumnVisibilityChanged;
}
[NotNull]
private DataGrid DataGrid => AssociatedObject;
private void ToggleButton_Changed([CanBeNull] ToggleButton oldValue, [CanBeNull] ToggleButton newValue)
{
if (oldValue != null)
{
oldValue.Checked -= ToggleButton_StateChanged;
oldValue.Unchecked -= ToggleButton_StateChanged;
}
if (newValue != null)
{
newValue.Checked += ToggleButton_StateChanged;
newValue.Unchecked += ToggleButton_StateChanged;
ToggleButton_StateChanged(newValue, EventArgs.Empty);
}
}
private void ToggleButton_StateChanged([NotNull] object sender, [NotNull] EventArgs e)
{
Refresh((ToggleButton)sender);
}
private void Refresh([CanBeNull] ToggleButton button)
{
var dataGrid = DataGrid;
if ((button == null) || (AssociatedObject == null))
return;
UpdateErrorsOnlyFilter(button.IsChecked.GetValueOrDefault());
var selectedItem = dataGrid.SelectedItem;
if (selectedItem != null)
dataGrid.ScrollIntoView(selectedItem);
}
private void DataGrid_ColumnVisibilityChanged([NotNull] object source, [NotNull] EventArgs e)
{
var toggleButton = ToggleButton;
if (toggleButton == null)
return;
if (toggleButton.IsChecked.GetValueOrDefault())
{
toggleButton.BeginInvoke(() => UpdateErrorsOnlyFilter(true));
}
}
private void UpdateErrorsOnlyFilter(bool isEnabled)
{
if (AssociatedObject == null)
return;
var dataGrid = DataGrid;
try
{
dataGrid.CommitEdit();
if (!isEnabled)
{
dataGrid.Items.Filter = null;
dataGrid.SetIsAutoFilterEnabled(true);
return;
}
var visibleLanguages = dataGrid.Columns
.Where(column => column.Visibility == Visibility.Visible)
.Select(column => column.Header)
.OfType<LanguageHeader>()
.Select(header => header.CultureKey)
.ToArray();
dataGrid.SetIsAutoFilterEnabled(false);
dataGrid.Items.Filter = row =>
{
var entry = (ResourceTableEntry)row;
var neutralCulture = entry.NeutralLanguage.CultureKey;
var hasInvariantMismatches = visibleLanguages
.Select(lang => new { Value = entry.Values.GetValue(lang), IsInvariant = (neutralCulture != lang) && (entry.IsItemInvariant.GetValue(lang) || entry.IsInvariant) })
.Any(v => v.IsInvariant != string.IsNullOrEmpty(v.Value));
return entry.IsDuplicateKey
|| hasInvariantMismatches
|| entry.HasRulesMismatches(visibleLanguages)
|| entry.HasSnapshotDifferences(visibleLanguages);
};
}
catch (InvalidOperationException)
{
}
}
}
}
| 33.947712 | 270 | 0.555834 |
[
"MIT"
] |
JeroenOortwijn/ResXResourceManager
|
ResXManager.View/Behaviors/ShowErrorsOnlyBehavior.cs
| 5,196 |
C#
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winnt.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="SLIST_HEADER_X86" /> struct.</summary>
public static unsafe partial class SLIST_HEADER_X86Tests
{
/// <summary>Validates that the <see cref="SLIST_HEADER_X86" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<SLIST_HEADER_X86>(), Is.EqualTo(sizeof(SLIST_HEADER_X86)));
}
/// <summary>Validates that the <see cref="SLIST_HEADER_X86" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutExplicitTest()
{
Assert.That(typeof(SLIST_HEADER_X86).IsExplicitLayout, Is.True);
}
/// <summary>Validates that the <see cref="SLIST_HEADER_X86" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(SLIST_HEADER_X86), Is.EqualTo(16));
}
}
| 37.142857 | 145 | 0.716154 |
[
"MIT"
] |
reflectronic/terrafx.interop.windows
|
tests/Interop/Windows/Windows/um/winnt/SLIST_HEADER_X86Tests.Manual.cs
| 1,302 |
C#
|
using UnityEngine;
public enum KinematicState { Seek, Flee, Wandering}
public class Movement : MonoBehaviour
{
public Transform target;
public float maxTimeToRotate = 5f;
private float currentTimeToROtate = 0f;
public float maxRotation = 50f;
public float maxSpeed = 2f;
public float radius = 1f;
public float timeToTarget = 1f;
public KinematicState kinematicState = KinematicState.Seek;
private class KinematicOutput
{
public Vector3 velocity { get; set; }
public float rotation { get; set; }
public void Reset()
{
velocity = Vector3.zero;
rotation = 0f;
}
}
private KinematicOutput kinematicOutput = new KinematicOutput { velocity = Vector3.zero, rotation = 0f };
private Rigidbody2D character;
private void Awake()
{
character = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
if(kinematicState == KinematicState.Wandering)
{
currentTimeToROtate += Time.fixedDeltaTime;
getWanderingOutput();
}
else
{
getKinematicOutput();
}
character.transform.position += kinematicOutput.velocity * Time.fixedDeltaTime;
character.transform.rotation = Quaternion.AngleAxis(kinematicOutput.rotation, Vector3.forward);
}
private void getWanderingOutput()
{
// Move in direction of current orientation
kinematicOutput.velocity = character.transform.right * maxSpeed;
// Modify current orientation
if(currentTimeToROtate >= maxTimeToRotate)
{
kinematicOutput.rotation = Random.Range(-1f, 1f) * maxRotation;
currentTimeToROtate = 0;
}
}
private void getKinematicOutput()
{
// Get Direction of movement
kinematicOutput.velocity = kinematicState == KinematicState.Seek ? target.position - character.transform.position : character.transform.position - target.position ;
if(kinematicOutput.velocity.magnitude < radius)
{
kinematicOutput.Reset();
return;
}
kinematicOutput.velocity /= timeToTarget;
if(kinematicOutput.velocity.magnitude > maxSpeed)
{
// Normalize vector
kinematicOutput.velocity = kinematicOutput.velocity.normalized;
// Max speed
kinematicOutput.velocity *= maxSpeed;
}
// Calculate angle of rotation
kinematicOutput.rotation = CacluateOrientation(kinematicOutput.velocity);
}
private float CacluateOrientation(Vector3 direction)
{
return Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
}
}
| 26.122642 | 174 | 0.632719 |
[
"MIT"
] |
andro98/KinematicMovement
|
Assets/Scripts/Movement.cs
| 2,769 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Valve.VR;
public class GripController : MonoBehaviour
{
public SteamVR_Input_Sources Hand;
public SteamVR_Action_Boolean ToggleGripButton;
public SteamVR_Action_Pose position;
public SteamVR_Behaviour_Skeleton HandSkeleton;
public SteamVR_Behaviour_Skeleton PreviewSkeleton;
public Grabber grabber;
private GameObject ConnectedObject;
private Transform OffsetObject;
private bool DomanantGrip;
private void Update()
{
if (ConnectedObject != null )
{
if (DomanantGrip || !ConnectedObject.GetComponent<Interactable>().SecondGripped)
{
if (ConnectedObject.GetComponent<Interactable>().touchCount == 0&& !ConnectedObject.GetComponent<Interactable>().SecondGripped)
{
grabber.FixedJoint.connectedBody = null;
grabber.StrongGrip.connectedBody = null;
ConnectedObject.transform.position = Vector3.MoveTowards(ConnectedObject.transform.position, transform.position - ConnectedObject.transform.rotation * OffsetObject.GetComponent<GrabPoint>().Offset, .25f);
ConnectedObject.transform.rotation = Quaternion.RotateTowards(ConnectedObject.transform.rotation, transform.rotation*Quaternion.Inverse( OffsetObject.GetComponent<GrabPoint>().RotationOffset), 10);
grabber.FixedJoint.connectedBody = ConnectedObject.GetComponent<Rigidbody>();
}
else if (ConnectedObject.GetComponent<Interactable>().touchCount > 0|| ConnectedObject.GetComponent<Interactable>().SecondGripped)
{
grabber.FixedJoint.connectedBody = null;
grabber.StrongGrip.connectedAnchor = OffsetObject.GetComponent<GrabPoint>().Offset;
grabber.StrongGrip.connectedBody = ConnectedObject.GetComponent<Rigidbody>();
}else if(ConnectedObject.GetComponent<Interactable>().touchCount < 0)
{
ConnectedObject.GetComponent<Interactable>().touchCount = 0;
}
}
else
{
grabber.FixedJoint.connectedBody = null;
grabber.StrongGrip.connectedBody = null;
grabber.WeakGrip.connectedBody = ConnectedObject.GetComponent<Rigidbody>();
}
if (ToggleGripButton.GetStateUp(Hand))
{
Release();
}
if(PreviewSkeleton)
PreviewSkeleton.transform.gameObject.SetActive(false);
}
else
{
if (grabber.ClosestGrabbable() && PreviewSkeleton)
{
PreviewSkeleton.transform.gameObject.SetActive(true);
OffsetObject = grabber.ClosestGrabbable().transform;
if (grabber.ClosestGrabbable().GetComponent<SteamVR_Skeleton_Poser>())
{
if (!OffsetObject.GetComponent<GrabPoint>().Gripped)
{
PreviewSkeleton.transform.SetParent(OffsetObject, false);
PreviewSkeleton.BlendToPoser(OffsetObject.GetComponent<SteamVR_Skeleton_Poser>(), 0f);
}
}
}
else
{
PreviewSkeleton.transform.gameObject.SetActive(false);
}
if (ToggleGripButton.GetStateDown(Hand))
{
Grip();
}
}
}
private void Grip()
{
GameObject NewObject = grabber.ClosestGrabbable();
if (NewObject != null)
{
OffsetObject = grabber.ClosestGrabbable().transform;
ConnectedObject = OffsetObject.GetComponent<GrabPoint>().ParentInteractable.gameObject;//find the Closest Grabbable and set it to the connected object
ConnectedObject.GetComponent<Rigidbody>().useGravity = false;
OffsetObject.GetComponent<GrabPoint>().Gripped = true;
if (ConnectedObject.GetComponent<Interactable>().gripped)
{
ConnectedObject.GetComponent<Interactable>().SecondGripped = true;
if (OffsetObject.GetComponent<GrabPoint>().HelperGrip)
{
DomanantGrip = false;
grabber.WeakGrip.connectedBody = ConnectedObject.GetComponent<Rigidbody>();
grabber.WeakGrip.connectedAnchor = OffsetObject.GetComponent<GrabPoint>().Offset;
}
grabber.WeakGrip.connectedBody = ConnectedObject.GetComponent<Rigidbody>();
grabber.WeakGrip.connectedAnchor = OffsetObject.GetComponent<GrabPoint>().Offset;
}
else
{
ConnectedObject.GetComponent<Interactable>().Hand = Hand;
ConnectedObject.GetComponent<Interactable>().gripped = true;
if (!OffsetObject.GetComponent<GrabPoint>().HelperGrip)
{
DomanantGrip = true;
ConnectedObject.GetComponent<Interactable>().GrippedBy = transform.parent.gameObject;
}
}
if (OffsetObject.GetComponent<SteamVR_Skeleton_Poser>()&&HandSkeleton)
{
HandSkeleton.transform.SetParent(OffsetObject, false);
HandSkeleton.BlendToPoser(OffsetObject.GetComponent<SteamVR_Skeleton_Poser>(), 0f);
}
}
}
private void Release()
{
grabber.FixedJoint.connectedBody = null;
grabber.StrongGrip.connectedBody = null;
grabber.WeakGrip.connectedBody = null;
ConnectedObject.GetComponent<Rigidbody>().velocity = position.GetVelocity(Hand) + transform.parent.GetComponent<Rigidbody>().velocity;
ConnectedObject.GetComponent<Rigidbody>().angularVelocity = position.GetAngularVelocity(Hand) + transform.parent.GetComponent<Rigidbody>().angularVelocity;
ConnectedObject.GetComponent<Rigidbody>().useGravity = true;
if (!ConnectedObject.GetComponent<Interactable>().SecondGripped)
{
ConnectedObject.GetComponent<Interactable>().gripped = false;
ConnectedObject.GetComponent<Interactable>().GrippedBy =null;
}
else
{
ConnectedObject.GetComponent<Interactable>().SecondGripped = false;
}
ConnectedObject = null;
if (OffsetObject.GetComponent<SteamVR_Skeleton_Poser>() && HandSkeleton)
{
HandSkeleton.transform.SetParent(transform, false);
HandSkeleton.BlendToSkeleton();
}
OffsetObject.GetComponent<GrabPoint>().Gripped = false;
OffsetObject = null;
}
}
| 42.85625 | 224 | 0.613096 |
[
"MIT"
] |
TusiimeAllan/VR_Vaccination_Sensitization
|
Assets/Modules/VR Instincts/Scripts/Interaction/GripController.cs
| 6,859 |
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
#region Usings
using System.Linq;
using Dnn.PersonaBar.Vocabularies.Components;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Content.Taxonomy;
using DotNetNuke.Web.Validators;
#endregion
namespace Dnn.PersonaBar.Vocabularies.Validators
{
public class VocabularyNameValidator : ObjectValidator
{
private IVocabularyController _vocabularyController;
private ITermController _termController;
public VocabularyNameValidator(IVocabularyController vocabularyController, ITermController termController)
{
this._vocabularyController = vocabularyController;
this._termController = termController;
}
public override ValidationResult ValidateObject(object target)
{
if (target is Vocabulary)
{
var vocabulary = target as Vocabulary;
var existVocabulary =
this._vocabularyController.GetVocabularies().FirstOrDefault(v => v.Name == vocabulary.Name && v.ScopeId == vocabulary.ScopeId);
if (existVocabulary != null && (vocabulary.VocabularyId == Null.NullInteger || existVocabulary.VocabularyId != vocabulary.VocabularyId))
{
return new ValidationResult(new[] { new ValidationError { ErrorMessage = Constants.VocabularyExistsError, PropertyName = Constants.VocabularyValidationPropertyName, Validator = this } });
}
}
else if (target is Term)
{
var term = target as Term;
var vocabulary = this._vocabularyController.GetVocabularies().FirstOrDefault(v => v.VocabularyId == term.VocabularyId);
var terms = this._termController.GetTermsByVocabulary(term.VocabularyId);
if (vocabulary != null)
{
if (vocabulary.IsHeirarchical)
{
if (term.ParentTermId > 0)
{
var existTerm = terms.FirstOrDefault(v => v.Name == term.Name && v.TermId != term.TermId && v.ParentTermId == term.ParentTermId);
if (existTerm != null)
{
return
new ValidationResult(new[]
{
new ValidationError
{
ErrorMessage = Constants.TermValidationError,
PropertyName = Constants.TermValidationPropertyName,
Validator = this
}
});
}
}
}
else
{
var existTerm = terms.FirstOrDefault(v => v.Name == term.Name && v.TermId != term.TermId);
if (existTerm != null)
{
return new ValidationResult(new[] { new ValidationError { ErrorMessage = Constants.TermValidationError, PropertyName = Constants.TermValidationPropertyName, Validator = this } });
}
}
}
else
{
return new ValidationResult(new[] { new ValidationError { ErrorMessage = Constants.VocabularyValidationError, PropertyName = "", Validator = this } });
}
}
return ValidationResult.Successful;
}
}
}
| 44.477273 | 207 | 0.52606 |
[
"MIT"
] |
MaiklT/Dnn.Platform
|
Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Vocabularies/Validators/VocabularyNameValidator.cs
| 3,916 |
C#
|
namespace FoundationDbNet
{
using System;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
/// <summary>
/// Provides a set of methods to help with <see cref="FdbError"/> values.
/// </summary>
internal static class FdbErrorExtensions
{
private static readonly ConcurrentDictionary<FdbError, string> ErrorMessages = new ConcurrentDictionary<FdbError, string>();
/// <summary>
/// Converts the given <paramref name="error"/> to an exception.
/// </summary>
/// <param name="error">The error code to convert to an <see cref="Exception"/>.</param>
/// <returns>The exception encapsulating the error code.</returns>
/// <exception cref="InvalidOperationException">Thrown when <paramref name="error"/> is Success.</exception>
public static FoundationDbException ToException(this FdbError error)
{
if (error == FdbError.Success)
{
throw new InvalidOperationException("FdbError.Success is not an error.");
}
if (!ErrorMessages.TryGetValue(error, out string errorMessage))
{
errorMessage = GetOrAddErrorMessage(error);
}
return new FoundationDbException(errorMessage, error);
}
/// <summary>
/// Ensures success by throwing an exception if <paramref name="error"/> does not indicate Success.
/// </summary>
/// <param name="error">The error code to check.</param>
/// <exception cref="FoundationDbException">Thrown when <paramref name="error"/> does not indicate Success.</exception>
public static void EnsureSuccess(this FdbError error)
{
if (error == FdbError.Success)
{
return;
}
ThrowFoundationDbException(error);
}
private static string GetOrAddErrorMessage(FdbError error)
{
return ErrorMessages.GetOrAdd(error, err =>
{
var msgPtr = fdb_get_error(err);
string message = Marshal.PtrToStringAnsi(msgPtr);
return message;
});
}
private static void ThrowFoundationDbException(FdbError error)
{
throw error.ToException();
}
[DllImport(FdbConstants.FdbDll)]
private static extern IntPtr fdb_get_error(FdbError error);
}
}
| 34.830986 | 132 | 0.601294 |
[
"Apache-2.0"
] |
jvandertil/FoundationDbNet
|
src/FoundationDbNet/FdbErrorExtensions.cs
| 2,475 |
C#
|
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by SpecFlow (http://www.specflow.org/).
// SpecFlow Version:1.9.0.77
// SpecFlow Generator Version:1.9.0.0
// 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>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace Orchard.Specs
{
using TechTalk.SpecFlow;
[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[NUnit.Framework.TestFixtureAttribute()]
[NUnit.Framework.DescriptionAttribute("Link Field")]
public partial class LinkFieldFeature
{
private static TechTalk.SpecFlow.ITestRunner testRunner;
#line 1 "Link.feature"
#line hidden
[NUnit.Framework.OneTimeSetUp()]
public virtual void FeatureSetup()
{
testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Link Field", " In order to add Link content to my types\r\n As an administrator\r\n I want to cr" +
"eate, edit and publish Link fields", ProgrammingLanguage.CSharp, ((string[])(null)));
testRunner.OnFeatureStart(featureInfo);
}
[NUnit.Framework.OneTimeTearDown()]
public virtual void FeatureTearDown()
{
testRunner.OnFeatureEnd();
testRunner = null;
}
[NUnit.Framework.SetUpAttribute()]
public virtual void TestInitialize()
{
}
[NUnit.Framework.TearDownAttribute()]
public virtual void ScenarioTearDown()
{
testRunner.OnScenarioEnd();
}
public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
{
testRunner.OnScenarioStart(scenarioInfo);
}
public virtual void ScenarioCleanup()
{
testRunner.CollectScenarioErrors();
}
[NUnit.Framework.TestAttribute()]
[NUnit.Framework.DescriptionAttribute("Creating and using Link fields")]
public virtual void CreatingAndUsingLinkFields()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Creating and using Link fields", ((string[])(null)));
#line 6
this.ScenarioSetup(scenarioInfo);
#line 9
testRunner.Given("I have installed Orchard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given ");
#line 10
testRunner.And("I have installed \"Orchard.Fields\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 11
testRunner.When("I go to \"Admin/ContentTypes\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 12
testRunner.Then("I should see \"<a[^>]*>.*?Create new type</a>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 13
testRunner.When("I go to \"Admin/ContentTypes/Create\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table1.AddRow(new string[] {
"DisplayName",
"Event"});
table1.AddRow(new string[] {
"Name",
"Event"});
#line 14
testRunner.And("I fill in", ((string)(null)), table1, "And ");
#line 18
testRunner.And("I hit \"Create\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 19
testRunner.And("I go to \"Admin/ContentTypes/\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 20
testRunner.Then("I should see \"Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 23
testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 24
testRunner.And("I follow \"Add Field\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table2.AddRow(new string[] {
"DisplayName",
"Site Url"});
table2.AddRow(new string[] {
"Name",
"SiteUrl"});
table2.AddRow(new string[] {
"FieldTypeName",
"LinkField"});
#line 25
testRunner.And("I fill in", ((string)(null)), table2, "And ");
#line 30
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 31
testRunner.And("I am redirected", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 32
testRunner.Then("I should see \"The \\\"Site Url\\\" field has been added.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 35
testRunner.When("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 36
testRunner.Then("I should see \"Site Url\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table3.AddRow(new string[] {
"Event.SiteUrl.Value",
"http://www.orchardproject.net"});
#line 37
testRunner.When("I fill in", ((string)(null)), table3, "When ");
#line hidden
TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table4.AddRow(new string[] {
"Event.SiteUrl.Text",
"Orchard"});
#line 40
testRunner.And("I fill in", ((string)(null)), table4, "And ");
#line 43
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 44
testRunner.And("I am redirected", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 45
testRunner.Then("I should see \"Your Event has been created.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 46
testRunner.When("I go to \"Admin/Contents/List\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 47
testRunner.Then("I should see \"Site Url:\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 48
testRunner.And("I should see \"<a href=\\\"http://www.orchardproject.net\\\">Orchard</a>\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 51
testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table5.AddRow(new string[] {
"Fields[0].LinkFieldSettings.Hint",
"Enter the url of the web site"});
#line 52
testRunner.And("I fill in", ((string)(null)), table5, "And ");
#line 55
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 56
testRunner.And("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 57
testRunner.Then("I should see \"Enter the url of the web site\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 60
testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table6 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table6.AddRow(new string[] {
"Fields[0].LinkFieldSettings.Required",
"true"});
#line 61
testRunner.And("I fill in", ((string)(null)), table6, "And ");
#line 64
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 65
testRunner.And("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
TechTalk.SpecFlow.Table table7 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table7.AddRow(new string[] {
"Event.SiteUrl.Value",
""});
#line 66
testRunner.And("I fill in", ((string)(null)), table7, "And ");
#line 69
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 70
testRunner.Then("I should see \"Url is required for Site Url.\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 73
testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table8 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table8.AddRow(new string[] {
"Fields[0].LinkFieldSettings.DefaultValue",
"http://www.orchardproject.net"});
#line 74
testRunner.And("I fill in", ((string)(null)), table8, "And ");
#line 77
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 78
testRunner.And("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 79
testRunner.Then("I should see \"value=\\\"http://www.orchardproject.net\\\"\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 82
testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table9 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table9.AddRow(new string[] {
"Fields[0].LinkFieldSettings.Required",
"true"});
#line 83
testRunner.And("I fill in", ((string)(null)), table9, "And ");
#line 86
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 87
testRunner.And("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 88
testRunner.Then("I should see \"required=\\\"required\\\"\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 91
testRunner.When("I go to \"Admin/ContentTypes/Edit/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
TechTalk.SpecFlow.Table table10 = new TechTalk.SpecFlow.Table(new string[] {
"name",
"value"});
table10.AddRow(new string[] {
"Fields[0].LinkFieldSettings.Required",
"false"});
#line 92
testRunner.And("I fill in", ((string)(null)), table10, "And ");
#line 95
testRunner.And("I hit \"Save\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 96
testRunner.And("I go to \"Admin/Contents/Create/Event\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line 97
testRunner.Then("I should not see \"required=\\\"required\\\"\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
this.ScenarioCleanup();
}
}
}
#pragma warning restore
#endregion
| 47.339623 | 240 | 0.561897 |
[
"BSD-3-Clause"
] |
mannyqiao/enjoy
|
src/Orchard.Specs/Link.feature.cs
| 12,547 |
C#
|
// Copyright © 2010-2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Callback interface used for asynchronous continuation of authentication requests.
/// </summary>
public interface IAuthCallback : IDisposable
{
/// <summary>
/// Continue the authentication request.
/// </summary>
/// <param name="username">requested username</param>
/// <param name="password">requested password</param>
void Continue(string username, string password);
/// <summary>
/// Cancel the authentication request.
/// </summary>
void Cancel();
/// <summary>
/// Gets a value indicating whether the callback has been disposed of.
/// </summary>
bool IsDisposed { get; }
}
}
| 29.65625 | 100 | 0.617492 |
[
"BSD-3-Clause"
] |
GenesysPureConnect/CefSharp
|
CefSharp/Callback/IAuthCallback.cs
| 952 |
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("06. Odd Numbers at Odd Positions")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. Odd Numbers at Odd Positions")]
[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("4603f26c-11ba-449f-9112-24d02598fbb8")]
// 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.837838 | 84 | 0.743911 |
[
"MIT"
] |
PavelIvanov96/Programming-Fundamentals-Extended-CSharp
|
05.Arrays - Lab/06. Odd Numbers at Odd Positions/Properties/AssemblyInfo.cs
| 1,440 |
C#
|
using System.Runtime.CompilerServices;
using ThemesOfDotNet.Indexing.AzureDevOps;
using ThemesOfDotNet.Indexing.GitHub;
namespace ThemesOfDotNet.Indexing.WorkItems;
public sealed class WorkItemRoadmap
{
public static WorkItemRoadmap Empty { get; } = new();
private readonly IReadOnlyDictionary<WorkItem, WorkItemRoadmapEntry> _map;
private WorkItemRoadmap()
{
_map = new Dictionary<WorkItem, WorkItemRoadmapEntry>();
Workspace = Workspace.Empty;
Milestones = Array.Empty<WorkItemMilestone>();
}
private WorkItemRoadmap(Workspace workspace,
WorkItemProduct product,
Func<WorkItemMilestone, bool> milestoneFilter)
{
ArgumentNullException.ThrowIfNull(workspace);
ArgumentNullException.ThrowIfNull(product);
ArgumentNullException.ThrowIfNull(milestoneFilter);
var allMilestones = new HashSet<WorkItemMilestone>();
allMilestones.UnionWith(product.Milestones.Where(m => m.Version.Build == 0));
var selectedMilestones = allMilestones.OrderBy(m => m.Version).ToArray();
var entries = new Dictionary<WorkItem, WorkItemRoadmapEntry>();
var states = new List<(WorkItemMilestone, WorkItemState)>();
foreach (var workItem in workspace.WorkItems)
{
states.Clear();
var relevantProduct = GetRelevantProduct(workItem);
if (relevantProduct != product)
continue;
var nextMilestone = (WorkItemMilestone?)null;
var nextState = (WorkItemState?)null;
for (var i = workItem.Changes.Count - 1; i >= 0; i--)
{
var stateChange = workItem.Changes[i];
if (stateChange.Kind != WorkItemChangeKind.StateChanged)
continue;
if (stateChange.Value is not WorkItemState previousState)
continue;
if (nextState is not null)
{
if (IsHigherOrEqual(previousState, nextState.Value))
{
// That means a later state "corrected" an earlier state.
// Let's ignore the earlier state then.
continue;
}
}
var previousMilestone = GetMilestone(selectedMilestones, stateChange.When);
if (previousMilestone is null)
continue;
if (nextMilestone is not null)
{
if (previousMilestone.Version >= nextMilestone.Version)
{
// That means a later state "corrected" an earlier state.
// Let's ignore the earlier state then.
continue;
}
}
states.Add((previousMilestone, previousState));
nextMilestone = previousMilestone;
nextState = previousState;
}
if (states.Count == 0)
{
if (workItem.Milestone is not null)
{
states.Add((workItem.Milestone, workItem.State));
nextState = workItem.State;
}
}
if (nextState != WorkItemState.Proposed)
{
var proposedMilestone = GetMilestone(selectedMilestones, workItem.CreatedAt);
if (proposedMilestone is not null)
states.Add((proposedMilestone, WorkItemState.Proposed));
}
static bool IsHigherOrEqual(WorkItemState left, WorkItemState right)
{
return Rank(left) >= Rank(right);
static int Rank(WorkItemState state)
{
return state switch
{
WorkItemState.Proposed => 0,
WorkItemState.Committed => 1,
WorkItemState.InProgress => 2,
WorkItemState.Cut or WorkItemState.Completed => 3,
_ => throw new SwitchExpressionException(state)
};
}
}
if (states.Count > 0)
{
states.Reverse();
var data = new WorkItemRoadmapEntry(this, workItem, states.ToArray());
entries.Add(workItem, data);
}
}
Workspace = workspace;
Milestones = selectedMilestones.Where(milestoneFilter).ToArray();
_map = entries;
}
private WorkItemProduct? GetRelevantProduct(WorkItem workItem)
{
if (workItem.Milestone is not null)
return workItem.Milestone.Product;
for (var i = workItem.Changes.Count - 1; i >= 0; i--)
{
var change = workItem.Changes[i];
var milestone = change.Value as WorkItemMilestone;
if (milestone is not null)
return milestone.Product;
}
var products = workItem.Workspace.Products;
var config = workItem.Workspace.Configuration;
var defaultProductName = (string?)null;
if (workItem.Original is AzureDevOpsWorkItem item)
{
if (config.AzureDevOpsQueryById.TryGetValue(item.QueryId, out var queryConfiguration))
defaultProductName = queryConfiguration.DefaultProduct;
}
if (workItem.Original is GitHubIssue issue)
{
var org = issue.Repo.Owner;
var repo = issue.Repo.Name;
if (config.GitHubOrgByName.TryGetValue(org, out var orgConfiguration))
{
if (orgConfiguration.Repos.TryGetValue(repo, out var repoConfiguration) && repoConfiguration.DefaultProduct is not null)
defaultProductName = repoConfiguration.DefaultProduct;
else
defaultProductName = orgConfiguration.DefaultProduct;
}
}
return products.FirstOrDefault(p => string.Equals(p.Name, defaultProductName, StringComparison.OrdinalIgnoreCase));
}
public Workspace Workspace { get; }
public IReadOnlyList<WorkItemMilestone> Milestones { get; }
public WorkItemRoadmapEntry? GetEntry(WorkItem workItem)
{
ArgumentNullException.ThrowIfNull(workItem);
return _map.GetValueOrDefault(workItem);
}
public static WorkItemRoadmap Create(Workspace workspace,
WorkItemProduct product,
Func<WorkItemMilestone, bool> milestoneFilter)
{
ArgumentNullException.ThrowIfNull(workspace);
ArgumentNullException.ThrowIfNull(product);
return new WorkItemRoadmap(workspace, product, milestoneFilter);
}
private static WorkItemMilestone? GetMilestone(IReadOnlyList<WorkItemMilestone> milestones, DateTimeOffset dateTime)
{
// TODO: Use a binary search
foreach (var m in milestones.Where(m => m.ReleaseDate is not null))
{
var r = m.ReleaseDate!.Value;
if (r >= dateTime)
return m;
}
return null;
}
}
| 34.832536 | 136 | 0.565659 |
[
"MIT"
] |
terrajobst/themesof.net
|
src/ThemesOfDotNet.Indexing/WorkItems/WorkItemRoadmap.cs
| 7,282 |
C#
|
using System;
using Newtonsoft.Json;
namespace TdLib
{
/// <summary>
/// Autogenerated TDLib APIs
/// </summary>
public static partial class TdApi
{
public partial class InputPassportElementErrorSource : Object
{
/// <summary>
/// The front side of the document contains an error. The error is considered resolved when the file with the front side of the document changes
/// </summary>
public class InputPassportElementErrorSourceFrontSide : InputPassportElementErrorSource
{
/// <summary>
/// Data type for serialization
/// </summary>
[JsonProperty("@type")]
public override string DataType { get; set; } = "inputPassportElementErrorSourceFrontSide";
/// <summary>
/// Extra data attached to the message
/// </summary>
[JsonProperty("@extra")]
public override string Extra { get; set; }
/// <summary>
/// Current hash of the file containing the front side
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("file_hash")]
public byte[] FileHash { get; set; }
}
}
}
}
| 34.871795 | 156 | 0.531618 |
[
"MIT"
] |
0x25CBFC4F/tdsharp
|
TDLib.Api/Objects/InputPassportElementErrorSourceFrontSide.cs
| 1,360 |
C#
|
using GitVersion.Extensions;
using GitVersion.Logging;
using LibGit2Sharp;
using Microsoft.Extensions.Options;
using System;
using System.IO;
using System.Linq;
namespace GitVersion
{
public class GitPreparer : IGitPreparer
{
private readonly ILog log;
private readonly IEnvironment environment;
private readonly IOptions<GitVersionOptions> options;
private readonly ICurrentBuildAgent buildAgent;
private const string DefaultRemoteName = "origin";
public GitPreparer(ILog log, IEnvironment environment, ICurrentBuildAgent buildAgent, IOptions<GitVersionOptions> options)
{
this.log = log ?? throw new ArgumentNullException(nameof(log));
this.environment = environment ?? throw new ArgumentNullException(nameof(environment));
this.options = options ?? throw new ArgumentNullException(nameof(options));
this.buildAgent = buildAgent;
}
public void Prepare()
{
var gitVersionOptions = options.Value;
// Normalize if we are running on build server
var normalizeGitDirectory = !gitVersionOptions.Settings.NoNormalize && buildAgent != null;
var shouldCleanUpRemotes = buildAgent != null && buildAgent.ShouldCleanUpRemotes();
var currentBranch = ResolveCurrentBranch();
var dotGitDirectory = gitVersionOptions.DotGitDirectory;
var projectRoot = gitVersionOptions.ProjectRootDirectory;
log.Info($"Project root is: {projectRoot}");
log.Info($"DotGit directory is: {dotGitDirectory}");
if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
{
throw new Exception($"Failed to prepare or find the .git directory in path '{gitVersionOptions.WorkingDirectory}'.");
}
PrepareInternal(normalizeGitDirectory, currentBranch, shouldCleanUpRemotes);
}
private void PrepareInternal(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false)
{
var gitVersionOptions = options.Value;
if (!string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl))
{
CreateDynamicRepository(currentBranch);
}
else
{
if (normalizeGitDirectory)
{
if (shouldCleanUpRemotes)
{
CleanupDuplicateOrigin();
}
NormalizeGitDirectory(currentBranch, gitVersionOptions.DotGitDirectory, false);
}
}
}
private string ResolveCurrentBranch()
{
var gitVersionOptions = options.Value;
var targetBranch = gitVersionOptions.RepositoryInfo.TargetBranch;
if (buildAgent == null)
{
return targetBranch;
}
var isDynamicRepository = !string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath);
var currentBranch = buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch;
log.Info("Branch from build environment: " + currentBranch);
return currentBranch;
}
private void CleanupDuplicateOrigin()
{
var remoteToKeep = DefaultRemoteName;
using var repo = new Repository(options.Value.DotGitDirectory);
// check that we have a remote that matches defaultRemoteName if not take the first remote
if (!repo.Network.Remotes.Any(remote => remote.Name.Equals(DefaultRemoteName, StringComparison.InvariantCultureIgnoreCase)))
{
remoteToKeep = repo.Network.Remotes.First().Name;
}
var duplicateRepos = repo.Network
.Remotes
.Where(remote => !remote.Name.Equals(remoteToKeep, StringComparison.InvariantCultureIgnoreCase))
.Select(remote => remote.Name);
// remove all remotes that are considered duplicates
foreach (var repoName in duplicateRepos)
{
repo.Network.Remotes.Remove(repoName);
}
}
private void CreateDynamicRepository(string targetBranch)
{
var gitVersionOptions = options.Value;
if (string.IsNullOrWhiteSpace(targetBranch))
{
throw new Exception("Dynamic Git repositories must have a target branch (/b)");
}
var repositoryInfo = gitVersionOptions.RepositoryInfo;
var gitDirectory = gitVersionOptions.DynamicGitRepositoryPath;
using (log.IndentLog($"Creating dynamic repository at '{gitDirectory}'"))
{
var authentication = gitVersionOptions.Authentication;
if (!Directory.Exists(gitDirectory))
{
CloneRepository(repositoryInfo.TargetUrl, gitDirectory, authentication);
}
else
{
log.Info("Git repository already exists");
}
NormalizeGitDirectory(targetBranch, gitDirectory, true);
}
}
private void NormalizeGitDirectory(string targetBranch, string gitDirectory, bool isDynamicRepository)
{
using (log.IndentLog($"Normalizing git directory for branch '{targetBranch}'"))
{
// Normalize (download branches) before using the branch
NormalizeGitDirectory(gitDirectory, options.Value.Settings.NoFetch, targetBranch, isDynamicRepository);
}
}
private void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo auth)
{
Credentials credentials = null;
if (auth != null)
{
if (!string.IsNullOrWhiteSpace(auth.Username))
{
log.Info($"Setting up credentials using name '{auth.Username}'");
credentials = new UsernamePasswordCredentials
{
Username = auth.Username,
Password = auth.Password ?? string.Empty
};
}
}
try
{
using (log.IndentLog($"Cloning repository from url '{repositoryUrl}'"))
{
var cloneOptions = new CloneOptions
{
Checkout = false,
CredentialsProvider = (url, usernameFromUrl, types) => credentials
};
var returnedPath = Repository.Clone(repositoryUrl, gitDirectory, cloneOptions);
log.Info($"Returned path after repository clone: {returnedPath}");
}
}
catch (LibGit2SharpException ex)
{
var message = ex.Message;
if (message.Contains("401"))
{
throw new Exception("Unauthorized: Incorrect username/password");
}
if (message.Contains("403"))
{
throw new Exception("Forbidden: Possibly Incorrect username/password");
}
if (message.Contains("404"))
{
throw new Exception("Not found: The repository was not found");
}
throw new Exception("There was an unknown problem with the Git repository you provided", ex);
}
}
/// <summary>
/// Normalization of a git directory turns all remote branches into local branches, turns pull request refs into a real branch and a few other things. This is designed to be run *only on the build server* which checks out repositories in different ways.
/// It is not recommended to run normalization against a local repository
/// </summary>
private void NormalizeGitDirectory(string gitDirectory, bool noFetch, string currentBranch, bool isDynamicRepository)
{
var authentication = options.Value.Authentication;
using var repository = new Repository(gitDirectory);
// Need to ensure the HEAD does not move, this is essentially a BugCheck
var expectedSha = repository.Head.Tip.Sha;
var expectedBranchName = repository.Head.CanonicalName;
try
{
var remote = repository.EnsureOnlyOneRemoteIsDefined(log);
repository.AddMissingRefSpecs(log, remote);
//If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
if (noFetch)
{
log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
}
else
{
log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}.");
Commands.Fetch(repository, remote.Name, new string[0], authentication.ToFetchOptions(), null);
}
repository.EnsureLocalBranchExistsForCurrentBranch(log, remote, currentBranch);
repository.CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, remote.Name);
// Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
// if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
if (expectedSha != repository.Head.Tip.Sha &&
(isDynamicRepository || !expectedBranchName.IsBranch(currentBranch)))
{
var newExpectedSha = repository.Head.Tip.Sha;
var newExpectedBranchName = repository.Head.CanonicalName;
log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");
expectedSha = newExpectedSha;
}
var headSha = repository.Refs.Head.TargetIdentifier;
if (!repository.Info.IsHeadDetached)
{
log.Info($"HEAD points at branch '{headSha}'.");
return;
}
log.Info($"HEAD is detached and points at commit '{headSha}'.");
log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, repository.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})")));
// In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
// If they do, go ahead and checkout that branch
// If no, go ahead and check out a new branch, using the known commit SHA as the pointer
var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();
var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
: null;
if (matchingCurrentBranch != null)
{
log.Info($"Checking out local branch '{currentBranch}'.");
Commands.Checkout(repository, matchingCurrentBranch);
}
else if (localBranchesWhereCommitShaIsHead.Count > 1)
{
var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
var csvNames = string.Join(", ", branchNames);
const string moveBranchMsg = "Move one of the branches along a commit to remove warning";
log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master");
if (master != null)
{
log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
Commands.Checkout(repository, master);
}
else
{
var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList();
if (branchesWithoutSeparators.Count == 1)
{
var branchWithoutSeparator = branchesWithoutSeparators[0];
log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg);
Commands.Checkout(repository, branchWithoutSeparator);
}
else
{
throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
}
}
}
else if (localBranchesWhereCommitShaIsHead.Count == 0)
{
log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
repository.CreateFakeBranchPointingAtThePullRequestTip(log, authentication);
}
else
{
log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'.");
Commands.Checkout(repository, repository.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]);
}
}
finally
{
if (repository.Head.Tip.Sha != expectedSha)
{
if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
{
// Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.
To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1
Please run `git {LibGitExtensions.CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion");
}
}
}
}
}
}
| 47.395062 | 261 | 0.577624 |
[
"MIT"
] |
AndreasAlexHyp/GitVersion
|
src/GitVersionCore/Core/GitPreparer.cs
| 15,356 |
C#
|
//#define REFRESH_TOKENS
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Web;
using System.Xml.Serialization;
using ISBoxerEVELauncher.Security;
using ISBoxerEVELauncher.Extensions;
using ISBoxerEVELauncher.Enums;
using ISBoxerEVELauncher.Web;
using System.Security.Cryptography;
using ISBoxerEVELauncher.Interface;
namespace ISBoxerEVELauncher.Games.EVE
{
/// <summary>
/// An EVE Online account and related data
/// </summary>
public class EVEAccount : INotifyPropertyChanged, IDisposable, ILaunchTarget
{
[XmlIgnore]
private Guid challengeCodeSource;
[XmlIgnore]
private byte[] challengeCode;
[XmlIgnore]
private string challengeHash;
[XmlIgnore]
private Guid state;
[XmlIgnore]
private string code;
public string Profile { get; set; }
public EVEAccount()
{
state = Guid.NewGuid();
challengeCodeSource = Guid.NewGuid();
challengeCode = Encoding.UTF8.GetBytes(challengeCodeSource.ToString().Replace("-", ""));
challengeHash = Base64UrlEncoder.Encode(ISBoxerEVELauncher.Security.SHA256.GenerateHash(Base64UrlEncoder.Encode(challengeCode)));
Profile = "Default";
}
/// <summary>
/// An Outh2 Access Token
/// </summary>
public class Token
{
private authObj _authObj;
public Token()
{
}
/// <summary>
/// We usually just need to parse a Uri for the Access Token details. So here is the constructor that does it for us.
/// </summary>
/// <param name="fromUri"></param>
public Token(authObj resp)
{
_authObj = resp;
TokenString = resp.access_token;
Expiration = DateTime.Now.AddSeconds(resp.expires_in).AddMinutes(-1);
}
public override string ToString()
{
return TokenString;
}
/// <summary>
/// Determine if the Access Token is expired. If it is, we know we can't use it...
/// </summary>
public bool IsExpired
{
get
{
return DateTime.Now >= Expiration;
}
}
/// <summary>
/// The actual token data
/// </summary>
public string TokenString { get; set; }
/// <summary>
/// When the token is good until...
/// </summary>
public DateTime Expiration { get; set; }
}
CookieContainer _Cookies;
/// <summary>
/// The EVE login process requires cookies; this will ensure we maintain the same cookies for the account
/// </summary>
[XmlIgnore]
CookieContainer Cookies
{
get
{
if (_Cookies == null)
{
if (!string.IsNullOrEmpty(NewCookieStorage))
{
BinaryFormatter formatter = new BinaryFormatter();
using (Stream s = new MemoryStream(Convert.FromBase64String(NewCookieStorage)))
{
_Cookies = (CookieContainer)formatter.Deserialize(s);
}
}
else
_Cookies = new CookieContainer();
}
return _Cookies;
}
set
{
_Cookies = value;
}
}
public void UpdateCookieStorage()
{
if (Cookies == null)
{
NewCookieStorage = null;
return;
}
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, Cookies);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
NewCookieStorage = Convert.ToBase64String(ms.ToArray());
}
}
string _Username;
/// <summary>
/// EVE Account username
/// </summary>
public string Username { get { return _Username; } set { _Username = value; OnPropertyChanged("Username"); } }
/// <summary>
/// Old cookie storage. If found in the XML, it will automatically be split into separate storage
/// </summary>
public string CookieStorage
{
get
{
return null;// return ISBoxerEVELauncher.CookieStorage.GetCookies(this);
}
set
{
if (!string.IsNullOrEmpty(value))
{
ISBoxerEVELauncher.Web.CookieStorage.SetCookies(this, value);
EVEAccount.ShouldUgradeCookieStorage = true;
}
}
}
public static bool ShouldUgradeCookieStorage { get; private set; }
/// <summary>
/// New method of storing cookies
/// </summary>
[XmlIgnore]
public string NewCookieStorage
{
get
{
return ISBoxerEVELauncher.Web.CookieStorage.GetCookies(this);
}
set
{
ISBoxerEVELauncher.Web.CookieStorage.SetCookies(this, value);
}
}
#region Password
System.Security.SecureString _SecurePassword;
/// <summary>
/// A Secure (and non-plaintext) representation of the password. This will NOT be stored in XML.
/// </summary>
[XmlIgnore]
public System.Security.SecureString SecurePassword { get { return _SecurePassword; } set { _SecurePassword = value; OnPropertyChanged("SecurePassword"); EncryptedPassword = null; EncryptedPasswordIV = null; } }
string _EncryptedPassword;
/// <summary>
/// An encrypted version of the password for the account. It is protected by the Password Master Key. Changing the Password Master Key will wipe this.
/// </summary>
public string EncryptedPassword
{
get
{
return _EncryptedPassword;
}
set { _EncryptedPassword = value; OnPropertyChanged("EncryptedPassword"); }
}
string _EncryptedPasswordIV;
/// <summary>
/// The Initialization Vector used to encrypt the password
/// </summary>
public string EncryptedPasswordIV { get { return _EncryptedPasswordIV; } set { _EncryptedPasswordIV = value; OnPropertyChanged("EncryptedPasswordIV"); } }
/// <summary>
/// Sets the encrypted password to the given SecureString, if possible
/// </summary>
/// <param name="password"></param>
void SetEncryptedPassword(System.Security.SecureString password)
{
if (!App.Settings.UseMasterKey || password == null)
{
ClearEncryptedPassword();
return;
}
if (!App.Settings.RequestMasterPassword())
{
System.Windows.MessageBox.Show("Your configured Master Password is required in order to save EVE Account passwords. It can be reset or disabled by un-checking 'Save passwords (securely)', and then all currently saved EVE Account passwords will be lost.");
return;
}
using (RijndaelManaged rjm = new RijndaelManaged())
{
if (string.IsNullOrEmpty(EncryptedPasswordIV))
{
rjm.GenerateIV();
EncryptedPasswordIV = Convert.ToBase64String(rjm.IV);
}
else
rjm.IV = Convert.FromBase64String(EncryptedPasswordIV);
using (SecureBytesWrapper sbwKey = new SecureBytesWrapper(App.Settings.PasswordMasterKey, true))
{
rjm.Key = sbwKey.Bytes;
using (ICryptoTransform encryptor = rjm.CreateEncryptor())
{
using (SecureStringWrapper ssw2 = new SecureStringWrapper(password, Encoding.Unicode))
{
byte[] inblock = ssw2.ToByteArray();
byte[] encrypted = encryptor.TransformFinalBlock(inblock, 0, inblock.Length);
EncryptedPassword = Convert.ToBase64String(encrypted);
}
}
}
}
}
/// <summary>
/// Attempts to prepare the encrypted verison of the currently active SecurePassword
/// </summary>
public void EncryptPassword()
{
SetEncryptedPassword(SecurePassword);
}
/// <summary>
/// Prepares the EVEAccount for storage by ensuring that the Encrypted fields are set, if available
/// </summary>
public void PrepareStorage()
{
if (SecurePassword != null)
{
EncryptPassword();
}
if (SecureCharacterName != null)
{
EncryptCharacterName();
}
}
/// <summary>
/// Removes the encrypted password and IV
/// </summary>
public void ClearEncryptedPassword()
{
EncryptedPassword = null;
EncryptedPasswordIV = null;
}
/// <summary>
/// Decrypts the currently EncryptedPassword if possible, populating SecurePassword (which can then be used to log in...)
/// </summary>
public void DecryptPassword(bool allowPopup)
{
if (string.IsNullOrEmpty(EncryptedPassword) || string.IsNullOrEmpty(EncryptedPasswordIV))
{
// no password stored to decrypt.
return;
}
// password is indeed encrypted
if (!App.Settings.HasPasswordMasterKey)
{
// Master Password not yet entered
if (!allowPopup)
{
// can't ask for it right now
return;
}
// ok, ask for it
if (!App.Settings.RequestMasterPassword())
{
// not entered. can't decrypt.
return;
}
}
using (RijndaelManaged rjm = new RijndaelManaged())
{
rjm.IV = Convert.FromBase64String(EncryptedPasswordIV);
using (SecureBytesWrapper sbwKey = new SecureBytesWrapper(App.Settings.PasswordMasterKey, true))
{
rjm.Key = sbwKey.Bytes;
using (ICryptoTransform decryptor = rjm.CreateDecryptor())
{
byte[] pass = Convert.FromBase64String(EncryptedPassword);
using (SecureBytesWrapper sbw = new SecureBytesWrapper())
{
sbw.Bytes = decryptor.TransformFinalBlock(pass, 0, pass.Length);
SecurePassword = new System.Security.SecureString();
foreach (char c in Encoding.Unicode.GetChars(sbw.Bytes))
{
SecurePassword.AppendChar(c);
}
SecurePassword.MakeReadOnly();
}
}
}
}
}
#endregion
#region CharacterName
System.Security.SecureString _SecureCharacterName;
/// <summary>
/// A Secure (and non-plaintext) representation of the CharacterName. This will NOT be stored in XML.
/// </summary>
[XmlIgnore]
public System.Security.SecureString SecureCharacterName { get { return _SecureCharacterName; } set { _SecureCharacterName = value; OnPropertyChanged("SecureCharacterName"); EncryptedCharacterName = null; EncryptedCharacterNameIV = null; } }
string _EncryptedCharacterName;
/// <summary>
/// An encrypted version of the CharacterName for the account. It is protected by the CharacterName Master Key. Changing the CharacterName Master Key will wipe this.
/// </summary>
public string EncryptedCharacterName
{
get
{
return _EncryptedCharacterName;
}
set { _EncryptedCharacterName = value; OnPropertyChanged("EncryptedCharacterName"); }
}
string _EncryptedCharacterNameIV;
/// <summary>
/// The Initialization Vector used to encrypt the CharacterName
/// </summary>
public string EncryptedCharacterNameIV { get { return _EncryptedCharacterNameIV; } set { _EncryptedCharacterNameIV = value; OnPropertyChanged("EncryptedCharacterNameIV"); } }
/// <summary>
/// Attempts to prepare the encrypted verison of the currently active SecureCharacterName
/// </summary>
public void EncryptCharacterName()
{
SetEncryptedCharacterName(SecureCharacterName);
}
/// <summary>
/// Removes the encrypted CharacterName and IV
/// </summary>
public void ClearEncryptedCharacterName()
{
EncryptedCharacterName = null;
EncryptedCharacterNameIV = null;
}
/// <summary>
/// Sets the encrypted CharacterName to the given SecureString, if possible
/// </summary>
/// <param name="CharacterName"></param>
void SetEncryptedCharacterName(System.Security.SecureString CharacterName)
{
if (!App.Settings.UseMasterKey || CharacterName == null)
{
ClearEncryptedCharacterName();
return;
}
if (!App.Settings.RequestMasterPassword())
{
System.Windows.MessageBox.Show("Your configured Master Password is required in order to save EVE Account Character Names and passwords. It can be reset or disabled by un-checking 'Save passwords (securely)', and then all currently saved EVE Account Character Names will be lost.");
return;
}
using (RijndaelManaged rjm = new RijndaelManaged())
{
if (string.IsNullOrEmpty(EncryptedCharacterNameIV))
{
rjm.GenerateIV();
EncryptedCharacterNameIV = Convert.ToBase64String(rjm.IV);
}
else
rjm.IV = Convert.FromBase64String(EncryptedCharacterNameIV);
using (SecureBytesWrapper sbwKey = new SecureBytesWrapper(App.Settings.PasswordMasterKey, true))
{
rjm.Key = sbwKey.Bytes;
using (ICryptoTransform encryptor = rjm.CreateEncryptor())
{
using (SecureStringWrapper ssw2 = new SecureStringWrapper(CharacterName, Encoding.Unicode))
{
byte[] inblock = ssw2.ToByteArray();
byte[] encrypted = encryptor.TransformFinalBlock(inblock, 0, inblock.Length);
EncryptedCharacterName = Convert.ToBase64String(encrypted);
}
}
}
}
}
/// <summary>
/// Decrypts the currently EncryptedCharacterName if possible, populating SecureCharacterName (which can then be used to log in...)
/// </summary>
public void DecryptCharacterName(bool allowPopup)
{
if (string.IsNullOrEmpty(EncryptedCharacterName) || string.IsNullOrEmpty(EncryptedCharacterNameIV))
{
// no CharacterName stored to decrypt.
return;
}
// CharacterName is indeed encrypted
if (!App.Settings.HasPasswordMasterKey)
{
// Master CharacterName not yet entered
if (!allowPopup)
{
// can't ask for it right now
return;
}
// ok, ask for it
if (!App.Settings.RequestMasterPassword())
{
// not entered. can't decrypt.
return;
}
}
using (RijndaelManaged rjm = new RijndaelManaged())
{
rjm.IV = Convert.FromBase64String(EncryptedCharacterNameIV);
using (SecureBytesWrapper sbwKey = new SecureBytesWrapper(App.Settings.PasswordMasterKey, true))
{
rjm.Key = sbwKey.Bytes;
using (ICryptoTransform decryptor = rjm.CreateDecryptor())
{
byte[] pass = Convert.FromBase64String(EncryptedCharacterName);
using (SecureBytesWrapper sbw = new SecureBytesWrapper())
{
sbw.Bytes = decryptor.TransformFinalBlock(pass, 0, pass.Length);
SecureCharacterName = new System.Security.SecureString();
foreach (char c in Encoding.Unicode.GetChars(sbw.Bytes))
{
SecureCharacterName.AppendChar(c);
}
SecureCharacterName.MakeReadOnly();
}
}
}
}
}
#endregion
Token _TranquilityToken;
/// <summary>
/// AccessToken for Tranquility. Lasts up to 11 hours?
/// </summary>
[XmlIgnore]
public Token TranquilityToken { get { return _TranquilityToken; } set { _TranquilityToken = value; OnPropertyChanged("TranquilityToken"); } }
Token _SisiToken;
/// <summary>
/// AccessToken for Singularity. Lasts up to 11 hours?
/// </summary>
[XmlIgnore]
public Token SisiToken { get { return _SisiToken; } set { _SisiToken = value; OnPropertyChanged("SisiToken"); } }
#region Refresh Tokens
/* This section is for experimental implemtnation using Refresh Tokens, which are used by the official EVE Launcher and described as insecure.
* They ultimately need the same encrypted storage care as a Password. May or may not be worth implementing.
* The code will not compile at this time if enabled.
*/
#if REFRESH_TOKENS
string _SisiRefreshToken;
public string SisiRefreshToken { get { return _SisiRefreshToken; } set { _SisiRefreshToken = value; OnPropertyChanged("SisiRefreshToken"); } }
string _TranquilityRefreshToken;
public string TranquilityRefreshToken { get { return _TranquilityRefreshToken; } set { _TranquilityRefreshToken = value; OnPropertyChanged("TranquilityRefreshToken"); } }
public void GetTokensFromCode(bool sisi, string code)
{
string uri = "https://client.eveonline.com/launcher/en/SSOVerifyUser";
if (sisi)
{
uri = "https://testclient.eveonline.com/launcher/en/SSOVerifyUser";
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Timeout = 5000;
req.AllowAutoRedirect = true;
/*
if (!sisi)
{
req.Headers.Add("Origin", "https://login.eveonline.com");
}
else
{
req.Headers.Add("Origin", "https://sisilogin.testeveonline.com");
}
/**/
//req.Referer = uri;
//req.CookieContainer = Cookies;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] body = Encoding.ASCII.GetBytes(String.Format("authCode={0}", Uri.EscapeDataString(code)));
req.ContentLength = body.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(body, 0, body.Length);
}
string refreshCode;
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
// https://login.eveonline.com/launcher?client_id=eveLauncherTQ#access_token=...&token_type=Bearer&expires_in=43200
string responseBody = null;
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
responseBody = sr.ReadToEnd();
}
}
/*
<span id="ValidationContainer"><div class="validation-summary-errors"><span>Login failed. Possible reasons can be:</span>
<ul><li>Invalid username / password</li>
</ul></div></span>
*/
// https://login.eveonline.com/launcher?client_id=eveLauncherTQ#access_token=l4nGki1CTUI7pCQZoIdnARcCLqL6ZGJM1X1tPf1bGKSJxEwP8lk_shS19w3sjLzyCbecYAn05y-Vbs-Jm1d1cw2&token_type=Bearer&expires_in=43200
//accessToken = new Token(resp.ResponseUri);
//refreshCode = HttpUtility.ParseQueryString(resp.ResponseUri.Query).Get("code");
// String expires_in = HttpUtility.ParseQueryString(fromUri.Fragment).Get("expires_in");
throw new NotImplementedException();
// responseBody should now be JSON containing the needed tokens.
}
}
public LoginResult GetRefreshToken(bool sisi, out string refreshToken)
{
string checkToken = sisi ? SisiRefreshToken : TranquilityRefreshToken;
if (!string.IsNullOrEmpty(checkToken))
{
refreshToken = checkToken;
return LoginResult.Success;
}
// need PlaintextPassword.
if (SecurePassword == null || SecurePassword.Length == 0)
{
Windows.EVELogin el = new Windows.EVELogin(this, false);
bool? result = el.ShowDialog();
if (SecurePassword == null || SecurePassword.Length == 0)
{
// password is required, sorry dude
refreshToken = null;
return LoginResult.InvalidUsernameOrPassword;
}
}
string uri = "https://login.eveonline.com/Account/LogOn?ReturnUrl=%2Foauth%2Fauthorize%2F%3Fclient_id%3DeveLauncherTQ%26lang%3Den%26response_type%3Dcode%26redirect_uri%3Dhttps%3A%2F%2Flogin.eveonline.com%2Flauncher%3Fclient_id%3DeveLauncherTQ%26scope%3DeveClientToken%2520user";
if (sisi)
{
uri = "https://sisilogin.testeveonline.com/Account/LogOn?ReturnUrl=%2Foauth%2Fauthorize%2F%3Fclient_id%3DeveLauncherTQ%26lang%3Den%26response_type%3Dcode%26redirect_uri%3Dhttps%3A%2F%2Fsisilogin.testeveonline.com%2Flauncher%3Fclient_id%3DeveLauncherTQ%26scope%3DeveClientToken%2520user";
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Timeout = 5000;
req.AllowAutoRedirect = true;
if (!sisi)
{
req.Headers.Add("Origin", "https://login.eveonline.com");
}
else
{
req.Headers.Add("Origin", "https://sisilogin.testeveonline.com");
}
req.Referer = uri;
req.CookieContainer = Cookies;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
using (SecureBytesWrapper body = new SecureBytesWrapper())
{
byte[] body1 = Encoding.ASCII.GetBytes(String.Format("UserName={0}&Password=", Uri.EscapeDataString(Username)));
using (SecureStringWrapper ssw = new SecureStringWrapper(SecurePassword, Encoding.ASCII))
{
using (SecureBytesWrapper escapedPassword = new SecureBytesWrapper())
{
escapedPassword.Bytes = System.Web.HttpUtility.UrlEncodeToBytes(ssw.ToByteArray());
body.Bytes = new byte[body1.Length + escapedPassword.Bytes.Length];
System.Buffer.BlockCopy(body1, 0, body.Bytes, 0, body1.Length);
System.Buffer.BlockCopy(escapedPassword.Bytes, 0, body.Bytes, body1.Length, escapedPassword.Bytes.Length);
}
}
req.ContentLength = body.Bytes.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(body.Bytes, 0, body.Bytes.Length);
}
}
string refreshCode;
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
// https://login.eveonline.com/launcher?client_id=eveLauncherTQ#access_token=...&token_type=Bearer&expires_in=43200
string responseBody = null;
using (Stream stream = resp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
responseBody = sr.ReadToEnd();
}
}
if (responseBody.Contains("Invalid username / password"))
{
refreshToken = null;
return LoginResult.InvalidUsernameOrPassword;
}
/*
<span id="ValidationContainer"><div class="validation-summary-errors"><span>Login failed. Possible reasons can be:</span>
<ul><li>Invalid username / password</li>
</ul></div></span>
*/
// https://login.eveonline.com/launcher?client_id=eveLauncherTQ#access_token=l4nGki1CTUI7pCQZoIdnARcCLqL6ZGJM1X1tPf1bGKSJxEwP8lk_shS19w3sjLzyCbecYAn05y-Vbs-Jm1d1cw2&token_type=Bearer&expires_in=43200
//accessToken = new Token(resp.ResponseUri);
refreshCode = HttpUtility.ParseQueryString(resp.ResponseUri.Query).Get("code");
// String expires_in = HttpUtility.ParseQueryString(fromUri.Fragment).Get("expires_in");
}
GetTokensFromCode(sisi,refreshCode);
throw new NotImplementedException();
if (!sisi)
{
TranquilityRefreshToken = refreshToken;
}
else
{
SisiRefreshToken = refreshToken;
}
return LoginResult.Success;
}
#endif
#endregion
public LoginResult GetSecurityWarningChallenge(bool sisi, string responseBody, Uri referer, out Token accessToken)
{
var uri = RequestResponse.GetSecurityWarningChallenge(sisi, state.ToString(), challengeHash);
var req = RequestResponse.CreateGetRequest(uri, sisi, true, referer.ToString(), Cookies);
return GetAccessToken(sisi, req, out accessToken);
}
public LoginResult GetEmailChallenge(bool sisi, string responseBody, out Token accessToken)
{
Windows.EmailChallengeWindow emailWindow = new Windows.EmailChallengeWindow(responseBody);
emailWindow.ShowDialog();
if (!emailWindow.DialogResult.HasValue || !emailWindow.DialogResult.Value)
{
SecurePassword = null;
accessToken = null;
return LoginResult.EmailVerificationRequired;
}
SecurePassword = null;
accessToken = null;
return LoginResult.EmailVerificationRequired;
}
public LoginResult GetEULAChallenge(bool sisi, string responseBody, Uri referer, out Token accessToken)
{
Windows.EVEEULAWindow eulaWindow = new Windows.EVEEULAWindow(responseBody);
eulaWindow.ShowDialog();
if (!eulaWindow.DialogResult.HasValue || !eulaWindow.DialogResult.Value)
{
SecurePassword = null;
accessToken = null;
return LoginResult.EULADeclined;
}
//string uri = "https://login.eveonline.com/OAuth/Eula";
//if (sisi)
//{
// uri = "https://sisilogin.testeveonline.com/OAuth/Eula";
//}
var uri = RequestResponse.GetEulaUri(sisi, state.ToString(), challengeHash);
HttpWebRequest req = RequestResponse.CreatePostRequest(uri, sisi, true, referer.ToString(), Cookies);
using (SecureBytesWrapper body = new SecureBytesWrapper())
{
string eulaHash = RequestResponse.GetEulaHashFromBody(responseBody);
string returnUrl = RequestResponse.GetEulaReturnUrlFromBody(responseBody);
string formattedString = String.Format("eulaHash={0}&returnUrl={1}&action={2}", Uri.EscapeDataString(eulaHash), Uri.EscapeDataString(returnUrl), "Accept");
body.Bytes = Encoding.ASCII.GetBytes(formattedString);
req.ContentLength = body.Bytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(body.Bytes, 0, body.Bytes.Length);
}
}
catch (System.Net.WebException e)
{
switch (e.Status)
{
case WebExceptionStatus.Timeout:
{
accessToken = null;
return LoginResult.Timeout;
}
default:
throw;
}
}
}
LoginResult result;
try
{
result = GetAccessToken(sisi, req, out accessToken);
}
catch (System.Net.WebException we)
{
result = GetAccessToken(sisi, out accessToken);
}
result = GetAccessToken(sisi, req, out accessToken);
if (result == LoginResult.Success)
{
// successful verification code challenge, make sure we save the cookies.
App.Settings.Store();
}
return result;
}
public LoginResult GetEmailCodeChallenge(bool sisi, string responseBody, out Token accessToken)
{
Windows.VerificationCodeChallengeWindow acw = new Windows.VerificationCodeChallengeWindow(this);
acw.ShowDialog();
if (!acw.DialogResult.HasValue || !acw.DialogResult.Value)
{
SecurePassword = null;
accessToken = null;
return LoginResult.InvalidEmailVerificationChallenge;
}
var uri = RequestResponse.GetVerifyTwoFactorUri(sisi, state.ToString(), challengeHash);
var req = RequestResponse.CreatePostRequest(uri, sisi, true, null, Cookies);
using (SecureBytesWrapper body = new SecureBytesWrapper())
{
// body.Bytes = Encoding.ASCII.GetBytes(String.Format("Challenge={0}&IsPasswordBreached={1}&NumPasswordBreaches={2}&command={3}", Uri.EscapeDataString(acw.VerificationCode), IsPasswordBreached, NumPasswordBreaches, "Continue"));
body.Bytes = Encoding.ASCII.GetBytes(String.Format("Challenge={0}&command={1}", Uri.EscapeDataString(acw.VerificationCode), "Continue"));
req.ContentLength = body.Bytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(body.Bytes, 0, body.Bytes.Length);
}
}
catch (System.Net.WebException e)
{
switch (e.Status)
{
case WebExceptionStatus.Timeout:
{
accessToken = null;
return LoginResult.Timeout;
}
default:
throw;
}
}
}
LoginResult result = GetAccessToken(sisi, req, out accessToken);
if (result == LoginResult.Success)
{
// successful verification code challenge, make sure we save the cookies.
App.Settings.Store();
}
return result;
}
public LoginResult GetAuthenticatorChallenge(bool sisi, out Token accessToken)
{
Windows.AuthenticatorChallengeWindow acw = new Windows.AuthenticatorChallengeWindow(this);
acw.ShowDialog();
if (!acw.DialogResult.HasValue || !acw.DialogResult.Value)
{
SecurePassword = null;
accessToken = null;
return LoginResult.InvalidAuthenticatorChallenge;
}
var uri = RequestResponse.GetAuthenticatorUri(sisi, state.ToString(), challengeHash);
var req = RequestResponse.CreatePostRequest(uri, sisi, true, uri.ToString(), Cookies);
using (SecureBytesWrapper body = new SecureBytesWrapper())
{
body.Bytes = Encoding.ASCII.GetBytes(String.Format("Challenge={0}&RememberTwoFactor={1}&command={2}", Uri.EscapeDataString(acw.AuthenticatorCode), "true", "Continue"));
req.ContentLength = body.Bytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(body.Bytes, 0, body.Bytes.Length);
}
}
catch (System.Net.WebException e)
{
switch (e.Status)
{
case WebExceptionStatus.Timeout:
{
accessToken = null;
return LoginResult.Timeout;
}
default:
throw;
}
}
}
LoginResult result = GetAccessToken(sisi, req, out accessToken);
if (result == LoginResult.Success)
{
// successful authenticator challenge, make sure we save the cookies.
App.Settings.Store();
}
return result;
}
public LoginResult GetCharacterChallenge(bool sisi, out Token accessToken)
{
// need SecureCharacterName.
if (SecureCharacterName == null || SecureCharacterName.Length == 0)
{
DecryptCharacterName(true);
if (SecureCharacterName == null || SecureCharacterName.Length == 0)
{
Windows.CharacterChallengeWindow ccw = new Windows.CharacterChallengeWindow(this);
bool? result = ccw.ShowDialog();
if (string.IsNullOrWhiteSpace(ccw.CharacterName))
{
// CharacterName is required, sorry dude
accessToken = null;
// SecurePassword = null;
SecureCharacterName = null;
return LoginResult.InvalidCharacterChallenge;
}
SecureCharacterName = new System.Security.SecureString();
foreach (char c in ccw.CharacterName)
{
SecureCharacterName.AppendChar(c);
}
SecureCharacterName.MakeReadOnly();
EncryptCharacterName();
App.Settings.Store();
}
}
var uri = RequestResponse.GetCharacterChallengeUri(sisi, state.ToString(), challengeHash);
var req = RequestResponse.CreatePostRequest(uri, sisi, true, uri.ToString(), Cookies);
using (SecureBytesWrapper body = new SecureBytesWrapper())
{
byte[] body1 = Encoding.ASCII.GetBytes(String.Format("RememberCharacterChallenge={0}&Challenge=", "true"));
using (SecureStringWrapper ssw = new SecureStringWrapper(SecureCharacterName, Encoding.ASCII))
{
using (SecureBytesWrapper escapedCharacterName = new SecureBytesWrapper())
{
escapedCharacterName.Bytes = System.Web.HttpUtility.UrlEncodeToBytes(ssw.ToByteArray());
body.Bytes = new byte[body1.Length + escapedCharacterName.Bytes.Length];
System.Buffer.BlockCopy(body1, 0, body.Bytes, 0, body1.Length);
System.Buffer.BlockCopy(escapedCharacterName.Bytes, 0, body.Bytes, body1.Length, escapedCharacterName.Bytes.Length);
}
}
req.ContentLength = body.Bytes.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(body.Bytes, 0, body.Bytes.Length);
}
}
catch (System.Net.WebException e)
{
switch (e.Status)
{
case WebExceptionStatus.Timeout:
{
accessToken = null;
return LoginResult.Timeout;
}
default:
throw;
}
}
}
return GetAccessToken(sisi, req, out accessToken);
}
public LoginResult GetAccessToken(bool sisi, HttpWebRequest req, out Token accessToken)
{
accessToken = null;
Response response = null;
try
{
response = new Response(req);
string responseBody = response.Body;
UpdateCookieStorage();
if (responseBody.Contains("Incorrect character name entered"))
{
accessToken = null;
SecurePassword = null;
SecureCharacterName = null;
return LoginResult.InvalidCharacterChallenge;
}
if (responseBody.Contains("Invalid username / password"))
{
accessToken = null;
SecurePassword = null;
return LoginResult.InvalidUsernameOrPassword;
}
// I'm just guessing on this one at the moment.
if (responseBody.Contains("Invalid authenticat")
|| (responseBody.Contains("Verification code mismatch") && responseBody.Contains("/account/authenticator"))
)
{
accessToken = null;
SecurePassword = null;
return LoginResult.InvalidAuthenticatorChallenge;
}
//The 2FA page now has "Character challenge" in the text but it is hidden. This should fix it from
//Coming up during 2FA challenge
if (responseBody.Contains("Character challenge") && !responseBody.Contains("visuallyhidden"))
{
return GetCharacterChallenge(sisi, out accessToken);
}
if (responseBody.Contains("Email verification required"))
{
return GetEmailChallenge(sisi, responseBody, out accessToken);
}
if (responseBody.Contains("Authenticator is enabled"))
{
return GetAuthenticatorChallenge(sisi, out accessToken);
}
if (responseBody.Contains("Please enter the verification code "))
{
return GetEmailCodeChallenge(sisi, responseBody, out accessToken);
}
if (responseBody.Contains("Security Warning"))
{
return GetSecurityWarningChallenge(sisi, responseBody, response.ResponseUri, out accessToken);
}
if (responseBody.ToLower().Contains("form action=\"/oauth/eula\""))
{
return GetEULAChallenge(sisi, responseBody, response.ResponseUri, out accessToken);
}
try
{
code = HttpUtility.ParseQueryString(response.ResponseUri.ToString()).Get("code");
if (code == null)
{
return LoginResult.Error;
}
GetAccessToken(sisi, code, out response);
accessToken = new Token(JsonConvert.DeserializeObject<authObj>(response.Body));
}
catch (Exception e)
{
Windows.UnhandledResponseWindow urw = new Windows.UnhandledResponseWindow(responseBody);
urw.ShowDialog();
// can't get the token
accessToken = null;
SecurePassword = null;
return LoginResult.TokenFailure;
}
if (!sisi)
{
TranquilityToken = accessToken;
}
else
{
SisiToken = accessToken;
}
return LoginResult.Success;
}
catch (System.Net.WebException we)
{
switch (we.Status)
{
case WebExceptionStatus.Timeout:
return LoginResult.Timeout;
default:
Windows.UnhandledResponseWindow urw = new Windows.UnhandledResponseWindow(response.ToString());
urw.ShowDialog();
return LoginResult.Error;
}
}
}
public class authObj
{
private int _expiresIn;
public string access_token { get; set; }
public int expires_in
{
get
{
return _expiresIn;
}
set
{
_expiresIn = value;
Expiration = DateTime.Now.AddMinutes(_expiresIn);
}
}
public string token_type { get; set; }
public string refresh_token { get; set; }
public DateTime Expiration { get; private set; }
}
private LoginResult GetAccessToken(bool sisi, string authCode, out Response response)
{
HttpWebRequest req2 = RequestResponse.CreatePostRequest(new Uri(RequestResponse.token, UriKind.Relative), sisi, true, RequestResponse.refererUri, Cookies);
req2.SetBody(RequestResponse.GetSsoTokenRequestBody(sisi, authCode, challengeCode));
return RequestResponse.GetHttpWebResponse(req2, UpdateCookieStorage, out response);
}
public LoginResult GetRequestVerificationToken(Uri uri, bool sisi, out string verificationToken)
{
Response response;
verificationToken = null;
var req = RequestResponse.CreateGetRequest(uri, sisi, false, RequestResponse.refererUri, Cookies);
req.ContentLength = 0;
var result = RequestResponse.GetHttpWebResponse(req, UpdateCookieStorage, out response);
if (result == LoginResult.Success)
{
verificationToken = RequestResponse.GetRequestVerificationTokenResponse(response);
}
return result;
}
public LoginResult GetAccessToken(bool sisi, out Token accessToken)
{
Token checkToken = sisi ? SisiToken : TranquilityToken;
if (checkToken != null && !checkToken.IsExpired)
{
accessToken = checkToken;
return LoginResult.Success;
}
// need SecurePassword.
if (SecurePassword == null || SecurePassword.Length == 0)
{
DecryptPassword(true);
if (SecurePassword == null || SecurePassword.Length == 0)
{
Windows.EVELogin el = new Windows.EVELogin(this, true);
bool? dialogResult = el.ShowDialog();
if (SecurePassword == null || SecurePassword.Length == 0)
{
// password is required, sorry dude
accessToken = null;
return LoginResult.InvalidUsernameOrPassword;
}
App.Settings.Store();
}
}
var uri = RequestResponse.GetLoginUri(sisi, state.ToString(), challengeHash);
string RequestVerificationToken = string.Empty;
var result = GetRequestVerificationToken(uri, sisi, out RequestVerificationToken);
var req = RequestResponse.CreatePostRequest(uri, sisi, true, RequestResponse.refererUri, Cookies);
using (SecureBytesWrapper body = new SecureBytesWrapper())
{
byte[] body1 = Encoding.ASCII.GetBytes(String.Format("__RequestVerificationToken={1}&UserName={0}&Password=", Uri.EscapeDataString(Username), Uri.EscapeDataString(RequestVerificationToken)));
// byte[] body1 = Encoding.ASCII.GetBytes(String.Format("UserName={0}&Password=", Uri.EscapeDataString(Username)));
using (SecureStringWrapper ssw = new SecureStringWrapper(SecurePassword, Encoding.ASCII))
{
using (SecureBytesWrapper escapedPassword = new SecureBytesWrapper())
{
escapedPassword.Bytes = System.Web.HttpUtility.UrlEncodeToBytes(ssw.ToByteArray());
body.Bytes = new byte[body1.Length + escapedPassword.Bytes.Length];
System.Buffer.BlockCopy(body1, 0, body.Bytes, 0, body1.Length);
System.Buffer.BlockCopy(escapedPassword.Bytes, 0, body.Bytes, body1.Length, escapedPassword.Bytes.Length);
req.SetBody(body);
}
}
}
return GetAccessToken(sisi, req, out accessToken);
}
public LoginResult GetSSOToken(bool sisi, out Token ssoToken)
{
Token accessToken;
LoginResult lr = this.GetAccessToken(sisi, out ssoToken);
return lr;
}
public LoginResult Launch(string sharedCachePath, bool sisi, DirectXVersion dxVersion, long characterID)
{
Token ssoToken;
LoginResult lr = GetSSOToken(sisi, out ssoToken);
if (lr != LoginResult.Success)
return lr;
if (!App.Launch(sharedCachePath, sisi, dxVersion, characterID, ssoToken))
return LoginResult.Error;
return LoginResult.Success;
}
public LoginResult Launch(string gameName, string gameProfileName, bool sisi, DirectXVersion dxVersion, long characterID)
{
Token ssoToken;
LoginResult lr = GetSSOToken(sisi, out ssoToken);
if (lr != LoginResult.Success)
return lr;
if (!App.Launch(gameName, gameProfileName, sisi, dxVersion, characterID, ssoToken))
return LoginResult.Error;
return LoginResult.Success;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void FirePropertyChanged(string value)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(value));
}
}
public void OnPropertyChanged(string value)
{
FirePropertyChanged(value);
}
#endregion
public void Dispose()
{
if (this.SecurePassword != null)
{
this.SecurePassword.Dispose();
this.SecurePassword = null;
}
this.EncryptedPassword = null;
this.EncryptedPasswordIV = null;
if (this.SecureCharacterName != null)
{
this.SecureCharacterName.Dispose();
this.SecureCharacterName = null;
}
this.EncryptedCharacterName = null;
this.EncryptedCharacterNameIV = null;
ISBoxerEVELauncher.Web.CookieStorage.DeleteCookies(this);
this.Username = null;
this.Cookies = null;
//this.NewCookieStorage = null;
}
public override string ToString()
{
return Username;
}
EVEAccount ILaunchTarget.EVEAccount
{
get { return this; }
}
public long CharacterID
{
get { return 0; }
}
}
}
| 38.917945 | 303 | 0.529922 |
[
"MIT"
] |
Dusty-Meg/ISBoxerEVELauncher
|
Games/EVE/EVEAccount.cs
| 50,751 |
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime: 4.0.30319.42000
//
// Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si
// el código se vuelve a generar.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Jcvegan.PdfViewer.Properties {
/// <summary>
/// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc.
/// </summary>
// StronglyTypedResourceBuilder generó automáticamente esta clase
// a través de una herramienta como ResGen o Visual Studio.
// Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen
// con la opción /str o recompile su proyecto de VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if ((resourceMan == null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Jcvegan.PdfViewer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Invalida la propiedad CurrentUICulture del subproceso actual para todas las
/// búsquedas de recursos usando esta clase de recursos fuertemente tipados.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 45.84127 | 183 | 0.624307 |
[
"MIT"
] |
jcvegan/wpf-pdf-viewer
|
src/Jcvegan.PdfViewer/Properties/Resources.Designer.cs
| 2,901 |
C#
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace PWD.Schedule.Migrations
{
public partial class Upgraded_To_Abp_5_1_0 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "UserNameOrEmailAddress",
table: "AbpUserLoginAttempts",
maxLength: 256,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 255,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Value",
table: "AbpSettings",
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 2000,
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "UserNameOrEmailAddress",
table: "AbpUserLoginAttempts",
maxLength: 255,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 256,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Value",
table: "AbpSettings",
maxLength: 2000,
nullable: true,
oldClrType: typeof(string),
oldNullable: true);
}
}
}
| 31.729167 | 71 | 0.522653 |
[
"MIT"
] |
Faridium/pwd.schedule
|
src/PWD.Schedule.EntityFrameworkCore/Migrations/20191216011543_Upgraded_To_Abp_5_1_0.cs
| 1,525 |
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Baseline;
using Marten.Services;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
namespace Marten.Testing.Services
{
public static class StringToTextReaderExtensions
{
public static TextReader ToReader(this string json)
{
return new StringReader(json);
}
}
public class DirtyTrackingIdentityMapTests
{
[Fact]
public void get_value_on_first_request()
{
var target = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
var target2 = map.Get<Target>(target.Id, serializer.ToJson(target).ToReader(), null);
target2.Id.ShouldBe(target.Id);
target2.ShouldNotBeTheSameAs(target);
}
[Fact]
public void get_with_concrete_type()
{
var serializer = new JsonNetSerializer();
var camaro = new NulloIdentityMapTests.Camaro();
var json = serializer.ToJson(camaro);
var map = new DirtyTrackingIdentityMap(serializer, null);
map.Get<NulloIdentityMapTests.Car>(camaro.Id, typeof(NulloIdentityMapTests.Camaro), json.ToReader(), null)
.ShouldBeOfType<NulloIdentityMapTests.Camaro>()
.Id.ShouldBe(camaro.Id);
}
[Fact]
public void get_value_on_subsequent_requests()
{
var target = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
var target2 = map.Get<Target>(target.Id, serializer.ToJson(target).ToReader(), null);
var target3 = map.Get<Target>(target.Id, serializer.ToJson(target).ToReader(), null);
var target4 = map.Get<Target>(target.Id, serializer.ToJson(target).ToReader(), null);
var target5 = map.Get<Target>(target.Id, serializer.ToJson(target).ToReader(), null);
target2.Id.ShouldBe(target.Id);
target3.Id.ShouldBe(target.Id);
target4.Id.ShouldBe(target.Id);
target5.Id.ShouldBe(target.Id);
target2.ShouldBeTheSameAs(target3);
target2.ShouldBeTheSameAs(target4);
target2.ShouldBeTheSameAs(target5);
}
[Fact]
public void detect_changes_with_no_changes()
{
var a = Target.Random();
var b = Target.Random();
var c = Target.Random();
var d = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
var a1 = map.Get<Target>(a.Id, serializer.ToJson(a).ToReader(), null);
var b1 = map.Get<Target>(a.Id, serializer.ToJson(b).ToReader(), null);
var c1 = map.Get<Target>(a.Id, serializer.ToJson(c).ToReader(), null);
var d1 = map.Get<Target>(a.Id, serializer.ToJson(d).ToReader(), null);
// no changes
map.DetectChanges().Any().ShouldBeFalse();
}
[Fact]
public void detect_changes_with_multiple_dirties()
{
var a = Target.Random();
var b = Target.Random();
var c = Target.Random();
var d = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
var a1 = map.Get<Target>(a.Id, serializer.ToJson(a).ToReader(), null);
a1.Long++;
var b1 = map.Get<Target>(b.Id, serializer.ToJson(b).ToReader(), null);
var c1 = map.Get<Target>(c.Id, serializer.ToJson(c).ToReader(), null);
c1.Long++;
var d1 = map.Get<Target>(d.Id, serializer.ToJson(d).ToReader(), null);
var changes = map.DetectChanges();
changes.Count().ShouldBe(2);
changes.Any(x => x.Id.As<Guid>() == a1.Id).ShouldBeTrue();
changes.Any(x => x.Id.As<Guid>() == c1.Id).ShouldBeTrue();
}
[Fact]
public void detect_changes_then_clear_the_changes()
{
var a = Target.Random();
var b = Target.Random();
var c = Target.Random();
var d = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
var a1 = map.Get<Target>(a.Id, serializer.ToJson(a).ToReader(), null);
a1.Long++;
var b1 = map.Get<Target>(b.Id, serializer.ToJson(b).ToReader(), null);
var c1 = map.Get<Target>(c.Id, serializer.ToJson(c).ToReader(), null);
c1.Long++;
var d1 = map.Get<Target>(d.Id, serializer.ToJson(d).ToReader(), null);
var changes = map.DetectChanges();
changes.Each(x => x.ChangeCommitted());
map.DetectChanges().Any().ShouldBeFalse();
}
[Fact]
public void remove_item()
{
var target = Target.Random();
var target2 = Target.Random();
target2.Id = target.Id;
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
var target3 = map.Get<Target>(target.Id, serializer.ToJson(target).ToReader(), null);
// now remove it
map.Remove<Target>(target.Id);
var target4 = map.Get<Target>(target.Id, serializer.ToJson(target2).ToReader(), null);
SpecificationExtensions.ShouldNotBeNull(target4);
target4.ShouldNotBeTheSameAs(target3);
}
[Fact]
public void store()
{
var target = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
map.Store(target.Id, target);
map.Get<Target>(target.Id, "".ToReader(), null).ShouldBeTheSameAs(target);
}
[Fact]
public void has_positive()
{
var target = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
map.Store(target.Id, target);
map.Has<Target>(target.Id).ShouldBeTrue();
}
[Fact]
public void has_negative()
{
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
map.Has<Target>(Guid.NewGuid()).ShouldBeFalse();
}
[Fact]
public void retrieve()
{
var target = Target.Random();
var serializer = new TestsSerializer();
var map = new DirtyTrackingIdentityMap(serializer, null);
map.Store(target.Id, target);
map.Retrieve<Target>(target.Id).ShouldBeTheSameAs(target);
}
}
}
| 29.845188 | 118 | 0.57241 |
[
"MIT"
] |
acid12/marten
|
src/Marten.Testing/Services/DirtyTrackingIdentityMapTests.cs
| 7,133 |
C#
|
/*
* Copyright (c) 2006-2016, openmetaverse.co
* 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.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Net;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
#region Enums
/// <summary>
/// Simulator (region) properties
/// </summary>
[Flags]
public enum RegionFlags : ulong
{
/// <summary>No flags set</summary>
None = 0,
/// <summary>Agents can take damage and be killed</summary>
AllowDamage = 1 << 0,
/// <summary>Landmarks can be created here</summary>
AllowLandmark = 1 << 1,
/// <summary>Home position can be set in this sim</summary>
AllowSetHome = 1 << 2,
/// <summary>Home position is reset when an agent teleports away</summary>
ResetHomeOnTeleport = 1 << 3,
/// <summary>Sun does not move</summary>
SunFixed = 1 << 4,
/// <summary>No object, land, etc. taxes</summary>
TaxFree = 1 << 5,
/// <summary>Disable heightmap alterations (agents can still plant
/// foliage)</summary>
BlockTerraform = 1 << 6,
/// <summary>Land cannot be released, sold, or purchased</summary>
BlockLandResell = 1 << 7,
/// <summary>All content is wiped nightly</summary>
Sandbox = 1 << 8,
/// <summary>Unknown: Related to the availability of an overview world map tile.(Think mainland images when zoomed out.)</summary>
NullLayer = 1 << 9,
/// <summary>Unknown: Related to region debug flags. Possibly to skip processing of agent interaction with world. </summary>
SkipAgentAction = 1 << 10,
/// <summary>Region does not update agent prim interest lists. Internal debugging option.</summary>
SkipUpdateInterestList = 1 << 11,
/// <summary>No collision detection for non-agent objects</summary>
SkipCollisions = 1 << 12,
/// <summary>No scripts are ran</summary>
SkipScripts = 1 << 13,
/// <summary>All physics processing is turned off</summary>
SkipPhysics = 1 << 14,
/// <summary>Region can be seen from other regions on world map. (Legacy world map option?) </summary>
ExternallyVisible = 1 << 15,
/// <summary>Region can be seen from mainland on world map. (Legacy world map option?) </summary>
MainlandVisible = 1 << 16,
/// <summary>Agents not explicitly on the access list can visit the region. </summary>
PublicAllowed = 1 << 17,
/// <summary>Traffic calculations are not run across entire region, overrides parcel settings. </summary>
BlockDwell = 1 << 18,
/// <summary>Flight is disabled (not currently enforced by the sim)</summary>
NoFly = 1 << 19,
/// <summary>Allow direct (p2p) teleporting</summary>
AllowDirectTeleport = 1 << 20,
/// <summary>Estate owner has temporarily disabled scripting</summary>
EstateSkipScripts = 1 << 21,
/// <summary>Restricts the usage of the LSL llPushObject function, applies to whole region.</summary>
RestrictPushObject = 1 << 22,
/// <summary>Deny agents with no payment info on file</summary>
DenyAnonymous = 1 << 23,
/// <summary>Deny agents with payment info on file</summary>
DenyIdentified = 1 << 24,
/// <summary>Deny agents who have made a monetary transaction</summary>
DenyTransacted = 1 << 25,
/// <summary>Parcels within the region may be joined or divided by anyone, not just estate owners/managers. </summary>
AllowParcelChanges = 1 << 26,
/// <summary>Abuse reports sent from within this region are sent to the estate owner defined email. </summary>
AbuseEmailToEstateOwner = 1 << 27,
/// <summary>Region is Voice Enabled</summary>
AllowVoice = 1 << 28,
/// <summary>Removes the ability from parcel owners to set their parcels to show in search.</summary>
BlockParcelSearch = 1 << 29,
/// <summary>Deny agents who have not been age verified from entering the region.</summary>
DenyAgeUnverified = 1 << 30
}
/// <summary>
/// Region protocol flags
/// </summary>
[Flags]
public enum RegionProtocols : ulong
{
/// <summary>Nothing special</summary>
None = 0,
/// <summary>Region supports Server side Appearance</summary>
AgentAppearanceService = 1 << 0,
/// <summary>Viewer supports Server side Appearance</summary>
SelfAppearanceSupport = 1 << 2
}
/// <summary>
/// Access level for a simulator
/// </summary>
[Flags]
public enum SimAccess : byte
{
/// <summary>Unknown or invalid access level</summary>
Unknown = 0,
/// <summary>Trial accounts allowed</summary>
Trial = 7,
/// <summary>PG rating</summary>
PG = 13,
/// <summary>Mature rating</summary>
Mature = 21,
/// <summary>Adult rating</summary>
Adult = 42,
/// <summary>Simulator is offline</summary>
Down = 254,
/// <summary>Simulator does not exist</summary>
NonExistent = 255
}
#endregion Enums
/// <summary>
///
/// </summary>
public class Simulator : UDPBase, IDisposable
{
#region Structs
/// <summary>
/// Simulator Statistics
/// </summary>
public struct SimStats
{
/// <summary>Total number of packets sent by this simulator to this agent</summary>
public long SentPackets;
/// <summary>Total number of packets received by this simulator to this agent</summary>
public long RecvPackets;
/// <summary>Total number of bytes sent by this simulator to this agent</summary>
public long SentBytes;
/// <summary>Total number of bytes received by this simulator to this agent</summary>
public long RecvBytes;
/// <summary>Time in seconds agent has been connected to simulator</summary>
public int ConnectTime;
/// <summary>Total number of packets that have been resent</summary>
public int ResentPackets;
/// <summary>Total number of resent packets recieved</summary>
public int ReceivedResends;
/// <summary>Total number of pings sent to this simulator by this agent</summary>
public int SentPings;
/// <summary>Total number of ping replies sent to this agent by this simulator</summary>
public int ReceivedPongs;
/// <summary>
/// Incoming bytes per second
/// </summary>
/// <remarks>It would be nice to have this claculated on the fly, but
/// this is far, far easier</remarks>
public int IncomingBPS;
/// <summary>
/// Outgoing bytes per second
/// </summary>
/// <remarks>It would be nice to have this claculated on the fly, but
/// this is far, far easier</remarks>
public int OutgoingBPS;
/// <summary>Time last ping was sent</summary>
public int LastPingSent;
/// <summary>ID of last Ping sent</summary>
public byte LastPingID;
/// <summary></summary>
public int LastLag;
/// <summary></summary>
public int MissedPings;
/// <summary>Current time dilation of this simulator</summary>
public float Dilation;
/// <summary>Current Frames per second of simulator</summary>
public int FPS;
/// <summary>Current Physics frames per second of simulator</summary>
public float PhysicsFPS;
/// <summary></summary>
public float AgentUpdates;
/// <summary></summary>
public float FrameTime;
/// <summary></summary>
public float NetTime;
/// <summary></summary>
public float PhysicsTime;
/// <summary></summary>
public float ImageTime;
/// <summary></summary>
public float ScriptTime;
/// <summary></summary>
public float AgentTime;
/// <summary></summary>
public float OtherTime;
/// <summary>Total number of objects Simulator is simulating</summary>
public int Objects;
/// <summary>Total number of Active (Scripted) objects running</summary>
public int ScriptedObjects;
/// <summary>Number of agents currently in this simulator</summary>
public int Agents;
/// <summary>Number of agents in neighbor simulators</summary>
public int ChildAgents;
/// <summary>Number of Active scripts running in this simulator</summary>
public int ActiveScripts;
/// <summary></summary>
public int LSLIPS;
/// <summary></summary>
public int INPPS;
/// <summary></summary>
public int OUTPPS;
/// <summary>Number of downloads pending</summary>
public int PendingDownloads;
/// <summary>Number of uploads pending</summary>
public int PendingUploads;
/// <summary></summary>
public int VirtualSize;
/// <summary></summary>
public int ResidentSize;
/// <summary>Number of local uploads pending</summary>
public int PendingLocalUploads;
/// <summary>Unacknowledged bytes in queue</summary>
public int UnackedBytes;
}
#endregion Structs
#region Public Members
/// <summary>A public reference to the client that this Simulator object
/// is attached to</summary>
public GridClient Client;
/// <summary>A Unique Cache identifier for this simulator</summary>
public UUID ID = UUID.Zero;
/// <summary>The capabilities for this simulator</summary>
public Caps Caps = null;
/// <summary></summary>
public ulong Handle;
/// <summary>The current version of software this simulator is running</summary>
public string SimVersion = string.Empty;
/// <summary></summary>
public string Name = string.Empty;
/// <summary>A 64x64 grid of parcel coloring values. The values stored
/// in this array are of the <seealso cref="ParcelArrayType"/> type</summary>
public byte[] ParcelOverlay = new byte[4096];
/// <summary></summary>
public int ParcelOverlaysReceived;
/// <summary></summary>
public float TerrainHeightRange00;
/// <summary></summary>
public float TerrainHeightRange01;
/// <summary></summary>
public float TerrainHeightRange10;
/// <summary></summary>
public float TerrainHeightRange11;
/// <summary></summary>
public float TerrainStartHeight00;
/// <summary></summary>
public float TerrainStartHeight01;
/// <summary></summary>
public float TerrainStartHeight10;
/// <summary></summary>
public float TerrainStartHeight11;
/// <summary></summary>
public float WaterHeight;
/// <summary></summary>
public UUID SimOwner = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase0 = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase1 = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase2 = UUID.Zero;
/// <summary></summary>
public UUID TerrainBase3 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail0 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail1 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail2 = UUID.Zero;
/// <summary></summary>
public UUID TerrainDetail3 = UUID.Zero;
/// <summary>true if your agent has Estate Manager rights on this region</summary>
public bool IsEstateManager;
/// <summary></summary>
public RegionFlags Flags;
/// <summary></summary>
public SimAccess Access;
/// <summary></summary>
public float BillableFactor;
/// <summary>Statistics information for this simulator and the
/// connection to the simulator, calculated by the simulator itself
/// and the library</summary>
public SimStats Stats;
/// <summary>The regions Unique ID</summary>
public UUID RegionID = UUID.Zero;
/// <summary>The physical data center the simulator is located</summary>
/// <remarks>Known values are:
/// <list type="table">
/// <item>Dallas</item>
/// <item>Chandler</item>
/// <item>SF</item>
/// </list>
/// </remarks>
public string ColoLocation;
/// <summary>The CPU Class of the simulator</summary>
/// <remarks>Most full mainland/estate sims appear to be 5,
/// Homesteads and Openspace appear to be 501</remarks>
public int CPUClass;
/// <summary>The number of regions sharing the same CPU as this one</summary>
/// <remarks>"Full Sims" appear to be 1, Homesteads appear to be 4</remarks>
public int CPURatio;
/// <summary>The billing product name</summary>
/// <remarks>Known values are:
/// <list type="table">
/// <item>Mainland / Full Region (Sku: 023)</item>
/// <item>Estate / Full Region (Sku: 024)</item>
/// <item>Estate / Openspace (Sku: 027)</item>
/// <item>Estate / Homestead (Sku: 029)</item>
/// <item>Mainland / Homestead (Sku: 129) (Linden Owned)</item>
/// <item>Mainland / Linden Homes (Sku: 131)</item>
/// </list>
/// </remarks>
public string ProductName;
/// <summary>The billing product SKU</summary>
/// <remarks>Known values are:
/// <list type="table">
/// <item>023 Mainland / Full Region</item>
/// <item>024 Estate / Full Region</item>
/// <item>027 Estate / Openspace</item>
/// <item>029 Estate / Homestead</item>
/// <item>129 Mainland / Homestead (Linden Owned)</item>
/// <item>131 Linden Homes / Full Region</item>
/// </list>
/// </remarks>
public string ProductSku;
/// <summary>
/// Flags indicating which protocols this region supports
/// </summary>
public RegionProtocols Protocols;
/// <summary>The current sequence number for packets sent to this
/// simulator. Must be Interlocked before modifying. Only
/// useful for applications manipulating sequence numbers</summary>
public int Sequence;
/// <summary>
/// A thread-safe dictionary containing avatars in a simulator
/// </summary>
public InternalDictionary<uint, Avatar> ObjectsAvatars = new InternalDictionary<uint, Avatar>();
/// <summary>
/// A thread-safe dictionary containing primitives in a simulator
/// </summary>
public InternalDictionary<uint, Primitive> ObjectsPrimitives = new InternalDictionary<uint, Primitive>();
public readonly TerrainPatch[] Terrain;
public readonly Vector2[] WindSpeeds;
/// <summary>
/// Provides access to an internal thread-safe dictionary containing parcel
/// information found in this simulator
/// </summary>
public InternalDictionary<int, Parcel> Parcels
{
get
{
if (Client.Settings.POOL_PARCEL_DATA)
{
return DataPool.Parcels;
}
if (_Parcels == null) _Parcels = new InternalDictionary<int, Parcel>();
return _Parcels;
}
}
private InternalDictionary<int, Parcel> _Parcels;
/// <summary>
/// Provides access to an internal thread-safe multidimensional array containing a x,y grid mapped
/// to each 64x64 parcel's LocalID.
/// </summary>
public int[,] ParcelMap
{
get
{
lock (this)
{
if (Client.Settings.POOL_PARCEL_DATA)
{
return DataPool.ParcelMap;
}
if (_ParcelMap == null) _ParcelMap = new int[64, 64];
return _ParcelMap;
}
}
}
/// <summary>
/// Checks simulator parcel map to make sure it has downloaded all data successfully
/// </summary>
/// <returns>true if map is full (contains no 0's)</returns>
public bool IsParcelMapFull()
{
for (int y = 0; y < 64; y++)
{
for (int x = 0; x < 64; x++)
{
if (ParcelMap[y, x] == 0)
return false;
}
}
return true;
}
/// <summary>
/// Is it safe to send agent updates to this sim
/// AgentMovementComplete message received
/// </summary>
public bool AgentMovementComplete;
#endregion Public Members
#region Properties
/// <summary>The IP address and port of the server</summary>
public IPEndPoint IPEndPoint { get { return remoteEndPoint; } }
/// <summary>Whether there is a working connection to the simulator or
/// not</summary>
public bool Connected { get { return connected; } }
/// <summary>Coarse locations of avatars in this simulator</summary>
public InternalDictionary<UUID, Vector3> AvatarPositions { get { return avatarPositions; } }
/// <summary>AvatarPositions key representing TrackAgent target</summary>
public UUID PreyID { get { return preyID; } }
/// <summary>Indicates if UDP connection to the sim is fully established</summary>
public bool HandshakeComplete { get { return handshakeComplete; } }
#endregion Properties
#region Internal/Private Members
/// <summary>Used internally to track sim disconnections</summary>
internal bool DisconnectCandidate = false;
/// <summary>Event that is triggered when the simulator successfully
/// establishes a connection</summary>
internal ManualResetEvent ConnectedEvent = new ManualResetEvent(false);
/// <summary>Whether this sim is currently connected or not. Hooked up
/// to the property Connected</summary>
internal bool connected;
/// <summary>Coarse locations of avatars in this simulator</summary>
internal InternalDictionary<UUID, Vector3> avatarPositions = new InternalDictionary<UUID, Vector3>();
/// <summary>AvatarPositions key representing TrackAgent target</summary>
internal UUID preyID = UUID.Zero;
/// <summary>Sequence numbers of packets we've received
/// (for duplicate checking)</summary>
internal IncomingPacketIDCollection PacketArchive;
/// <summary>Packets we sent out that need ACKs from the simulator</summary>
internal SortedDictionary<uint, OutgoingPacket> NeedAck = new SortedDictionary<uint, OutgoingPacket>();
/// <summary>Sequence number for pause/resume</summary>
internal int pauseSerial;
/// <summary>Indicates if UDP connection to the sim is fully established</summary>
internal bool handshakeComplete;
NetworkManager Network;
Queue<long> InBytes, OutBytes;
// ACKs that are queued up to be sent to the simulator
LocklessQueue<uint> PendingAcks = new LocklessQueue<uint>();
Timer AckTimer;
Timer PingTimer;
Timer StatsTimer;
// simulator <> parcel LocalID Map
int[,] _ParcelMap;
public readonly SimulatorDataPool DataPool;
internal bool DownloadingParcelMap
{
get
{
return Client.Settings.POOL_PARCEL_DATA ? DataPool.DownloadingParcelMap : _DownloadingParcelMap;
}
set
{
if (Client.Settings.POOL_PARCEL_DATA) DataPool.DownloadingParcelMap = value;
_DownloadingParcelMap = value;
}
}
internal bool _DownloadingParcelMap = false;
ManualResetEvent GotUseCircuitCodeAck = new ManualResetEvent(false);
#endregion Internal/Private Members
/// <summary>
///
/// </summary>
/// <param name="client">Reference to the GridClient object</param>
/// <param name="address">IPEndPoint of the simulator</param>
/// <param name="handle">handle of the simulator</param>
public Simulator(GridClient client, IPEndPoint address, ulong handle)
: base(address)
{
Client = client;
if (Client.Settings.POOL_PARCEL_DATA || Client.Settings.CACHE_PRIMITIVES)
{
SimulatorDataPool.SimulatorAdd(this);
DataPool = SimulatorDataPool.GetSimulatorData(Handle);
}
Handle = handle;
Network = Client.Network;
PacketArchive = new IncomingPacketIDCollection(Settings.PACKET_ARCHIVE_SIZE);
InBytes = new Queue<long>(Client.Settings.STATS_QUEUE_SIZE);
OutBytes = new Queue<long>(Client.Settings.STATS_QUEUE_SIZE);
if (client.Settings.STORE_LAND_PATCHES)
{
Terrain = new TerrainPatch[16 * 16];
WindSpeeds = new Vector2[16 * 16];
}
}
/// <summary>
/// Called when this Simulator object is being destroyed
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (disposing)
{
if (AckTimer != null)
AckTimer.Dispose();
if (PingTimer != null)
PingTimer.Dispose();
if (StatsTimer != null)
StatsTimer.Dispose();
if (ConnectedEvent != null)
ConnectedEvent.Close();
// Force all the CAPS connections closed for this simulator
if (Caps != null)
Caps.Disconnect(true);
}
}
/// <summary>
/// Attempt to connect to this simulator
/// </summary>
/// <param name="moveToSim">Whether to move our agent in to this sim or not</param>
/// <returns>True if the connection succeeded or connection status is
/// unknown, false if there was a failure</returns>
public bool Connect(bool moveToSim)
{
handshakeComplete = false;
if (connected)
{
UseCircuitCode(true);
if (moveToSim) Client.Self.CompleteAgentMovement(this);
return true;
}
#region Start Timers
// Timer for sending out queued packet acknowledgements
if (AckTimer == null)
AckTimer = new Timer(AckTimer_Elapsed, null, Settings.NETWORK_TICK_INTERVAL, Timeout.Infinite);
// Timer for recording simulator connection statistics
if (StatsTimer == null)
StatsTimer = new Timer(StatsTimer_Elapsed, null, 1000, 1000);
// Timer for periodically pinging the simulator
if (PingTimer == null && Client.Settings.SEND_PINGS)
PingTimer = new Timer(PingTimer_Elapsed, null, Settings.PING_INTERVAL, Settings.PING_INTERVAL);
#endregion Start Timers
Logger.Log("Connecting to " + this, Helpers.LogLevel.Info, Client);
try
{
// Create the UDP connection
Start();
// Mark ourselves as connected before firing everything else up
connected = true;
// Initiate connection
UseCircuitCode(true);
Stats.ConnectTime = Environment.TickCount;
// Move our agent in to the sim to complete the connection
if (moveToSim) Client.Self.CompleteAgentMovement(this);
if (!ConnectedEvent.WaitOne(Client.Settings.LOGIN_TIMEOUT, false))
{
Logger.Log("Giving up on waiting for RegionHandshake for " + this,
Helpers.LogLevel.Warning, Client);
//Remove the simulator from the list, not useful if we haven't recieved the RegionHandshake
lock (Client.Network.Simulators) {
Client.Network.Simulators.Remove(this);
}
}
if (Client.Settings.SEND_AGENT_THROTTLE)
Client.Throttle.Set(this);
if (Client.Settings.SEND_AGENT_UPDATES)
Client.Self.Movement.SendUpdate(true, this);
return true;
}
catch (Exception e)
{
Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e);
}
return false;
}
/// <summary>
/// Initiates connection to the simulator
/// </summary>
/// <param name="waitForAck">Should we block until ack for this packet is recieved</param>
public void UseCircuitCode(bool waitForAck)
{
// Send the UseCircuitCode packet to initiate the connection
var use = new UseCircuitCodePacket();
use.CircuitCode.Code = Network.CircuitCode;
use.CircuitCode.ID = Client.Self.AgentID;
use.CircuitCode.SessionID = Client.Self.SessionID;
if (waitForAck)
{
GotUseCircuitCodeAck.Reset();
}
// Send the initial packet out
SendPacket(use);
if (waitForAck)
{
if (!GotUseCircuitCodeAck.WaitOne(Client.Settings.LOGIN_TIMEOUT, false))
{
Logger.Log("Failed to get ACK for UseCircuitCode packet", Helpers.LogLevel.Error, Client);
}
}
}
public void SetSeedCaps(string seedcaps)
{
if (Caps != null)
{
if (Caps._SeedCapsURI == seedcaps) return;
Logger.Log("Unexpected change of seed capability", Helpers.LogLevel.Warning, Client);
Caps.Disconnect(true);
Caps = null;
}
if (Client.Settings.ENABLE_CAPS)
{
// Connect to the new CAPS system
if (!string.IsNullOrEmpty(seedcaps))
Caps = new Caps(this, seedcaps);
else
Logger.Log("Setting up a sim without a valid capabilities server!", Helpers.LogLevel.Error, Client);
}
}
/// <summary>
/// Disconnect from this simulator
/// </summary>
public void Disconnect(bool sendCloseCircuit)
{
if (connected)
{
connected = false;
// Destroy the timers
if (AckTimer != null) AckTimer.Dispose();
if (StatsTimer != null) StatsTimer.Dispose();
if (PingTimer != null) PingTimer.Dispose();
AckTimer = null;
StatsTimer = null;
PingTimer = null;
// Kill the current CAPS system
if (Caps != null)
{
Caps.Disconnect(true);
Caps = null;
}
if (sendCloseCircuit)
{
// Try to send the CloseCircuit notice
var close = new CloseCircuitPacket();
var buf = new UDPPacketBuffer(remoteEndPoint);
byte[] data = close.ToBytes();
Buffer.BlockCopy(data, 0, buf.Data, 0, data.Length);
buf.DataLength = data.Length;
AsyncBeginSend(buf);
}
if (Client.Settings.POOL_PARCEL_DATA || Client.Settings.CACHE_PRIMITIVES)
{
SimulatorDataPool.SimulatorRelease(this);
}
// Shut the socket communication down
Stop();
}
}
/// <summary>
/// Instructs the simulator to stop sending update (and possibly other) packets
/// </summary>
public void Pause()
{
var pause = new AgentPausePacket();
pause.AgentData.AgentID = Client.Self.AgentID;
pause.AgentData.SessionID = Client.Self.SessionID;
pause.AgentData.SerialNum = (uint)Interlocked.Exchange(ref pauseSerial, pauseSerial + 1);
Client.Network.SendPacket(pause, this);
}
/// <summary>
/// Instructs the simulator to resume sending update packets (unpause)
/// </summary>
public void Resume()
{
var resume = new AgentResumePacket();
resume.AgentData.AgentID = Client.Self.AgentID;
resume.AgentData.SessionID = Client.Self.SessionID;
resume.AgentData.SerialNum = (uint)Interlocked.Exchange(ref pauseSerial, pauseSerial + 1);
Client.Network.SendPacket(resume, this);
}
/// <summary>
/// Retrieve the terrain height at a given coordinate
/// </summary>
/// <param name="x">Sim X coordinate, valid range is from 0 to 255</param>
/// <param name="y">Sim Y coordinate, valid range is from 0 to 255</param>
/// <param name="height">The terrain height at the given point if the
/// lookup was successful, otherwise 0.0f</param>
/// <returns>True if the lookup was successful, otherwise false</returns>
public bool TerrainHeightAtPoint(int x, int y, out float height)
{
if (Terrain != null && x >= 0 && x < 256 && y >= 0 && y < 256)
{
int patchX = x / 16;
int patchY = y / 16;
x = x % 16;
y = y % 16;
TerrainPatch patch = Terrain[patchY * 16 + patchX];
if (patch != null)
{
height = patch.Data[y * 16 + x];
return true;
}
}
height = 0.0f;
return false;
}
#region Packet Sending
/// <summary>
/// Sends a packet
/// </summary>
/// <param name="packet">Packet to be sent</param>
public void SendPacket(Packet packet)
{
// DEBUG: This can go away after we are sure nothing in the library is trying to do this
if (packet.Header.AppendedAcks || (packet.Header.AckList != null && packet.Header.AckList.Length > 0))
Logger.Log("Attempting to send packet " + packet.Type + " with ACKs appended before serialization", Helpers.LogLevel.Error);
if (packet.HasVariableBlocks)
{
byte[][] datas;
try { datas = packet.ToBytesMultiple(); }
catch (NullReferenceException)
{
Logger.Log("Failed to serialize " + packet.Type + " packet to one or more payloads due to a missing block or field. StackTrace: " +
Environment.StackTrace, Helpers.LogLevel.Error);
return;
}
int packetCount = datas.Length;
if (packetCount > 1)
Logger.DebugLog("Split " + packet.Type + " packet into " + packetCount + " packets");
for (int i = 0; i < packetCount; i++)
{
byte[] data = datas[i];
SendPacketData(data, data.Length, packet.Type, packet.Header.Zerocoded);
}
}
else
{
byte[] data = packet.ToBytes();
SendPacketData(data, data.Length, packet.Type, packet.Header.Zerocoded);
}
}
public void SendPacketData(byte[] data, int dataLength, PacketType type, bool doZerocode)
{
var buffer = new UDPPacketBuffer(remoteEndPoint, Packet.MTU);
// Zerocode if needed
if (doZerocode)
{
try { dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data); }
catch (IndexOutOfRangeException)
{
// The packet grew larger than Packet.MTU bytes while zerocoding.
// Remove the MSG_ZEROCODED flag and send the unencoded data
// instead
data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
//Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
buffer.CopyFrom(data, dataLength);
}
}
else
{
//Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength)
buffer.CopyFrom(data, dataLength);
}
buffer.DataLength = dataLength;
#region Queue or Send
var outgoingPacket = new OutgoingPacket(this, buffer, type);
// Send ACK and logout packets directly, everything else goes through the queue
if (Client.Settings.THROTTLE_OUTGOING_PACKETS == false ||
type == PacketType.PacketAck ||
type == PacketType.LogoutRequest)
{
SendPacketFinal(outgoingPacket);
}
else
{
Network.PacketOutbox.Enqueue(outgoingPacket);
}
#endregion Queue or Send
#region Stats Tracking
if (Client.Settings.TRACK_UTILIZATION)
{
Client.Stats.Update(type.ToString(), OpenMetaverse.Stats.Type.Packet, dataLength, 0);
}
#endregion
}
internal void SendPacketFinal(OutgoingPacket outgoingPacket)
{
UDPPacketBuffer buffer = outgoingPacket.Buffer;
byte flags = buffer.Data[0];
bool isResend = (flags & Helpers.MSG_RESENT) != 0;
bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
// Keep track of when this packet was sent out (right now)
outgoingPacket.TickCount = Environment.TickCount;
#region ACK Appending
int dataLength = buffer.DataLength;
// Keep appending ACKs until there is no room left in the packet or there are
// no more ACKs to append
uint ackCount = 0;
uint ack;
while (dataLength + 5 < Packet.MTU && PendingAcks.TryDequeue(out ack))
{
Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
dataLength += 4;
++ackCount;
}
if (ackCount > 0)
{
// Set the last byte of the packet equal to the number of appended ACKs
buffer.Data[dataLength++] = (byte)ackCount;
// Set the appended ACKs flag on this packet
buffer.Data[0] |= Helpers.MSG_APPENDED_ACKS;
}
buffer.DataLength = dataLength;
#endregion ACK Appending
if (!isResend)
{
// Not a resend, assign a new sequence number
var sequenceNumber = (uint)Interlocked.Increment(ref Sequence);
Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
outgoingPacket.SequenceNumber = sequenceNumber;
if (isReliable)
{
// Add this packet to the list of ACK responses we are waiting on from the server
lock (NeedAck) NeedAck[sequenceNumber] = outgoingPacket;
}
}
// Put the UDP payload on the wire
AsyncBeginSend(buffer);
}
/// <summary>
///
/// </summary>
public void SendPing()
{
uint oldestUnacked = 0;
// Get the oldest NeedAck value, the first entry in the sorted dictionary
lock (NeedAck)
{
if (NeedAck.Count > 0)
{
var en = NeedAck.Keys.GetEnumerator();
en.MoveNext();
oldestUnacked = en.Current;
}
}
//if (oldestUnacked != 0)
// Logger.DebugLog("Sending ping with oldestUnacked=" + oldestUnacked);
var ping = new StartPingCheckPacket();
ping.PingID.PingID = Stats.LastPingID++;
ping.PingID.OldestUnacked = oldestUnacked;
ping.Header.Reliable = false;
SendPacket(ping);
Stats.LastPingSent = Environment.TickCount;
}
#endregion Packet Sending
/// <summary>
/// Returns Simulator Name as a String
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (!string.IsNullOrEmpty (Name))
return string.Format ("{0} ({1})", Name, remoteEndPoint);
return string.Format ("({0})", remoteEndPoint);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return Handle.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
var sim = obj as Simulator;
if (sim == null)
return false;
return (remoteEndPoint.Equals(sim.remoteEndPoint));
}
public static bool operator ==(Simulator lhs, Simulator rhs)
{
// If both are null, or both are same instance, return true
if (ReferenceEquals (lhs, rhs))
{
return true;
}
// If one is null, but not both, return false.
if (((object)lhs == null) || ((object)rhs == null))
{
return false;
}
return lhs.remoteEndPoint.Equals(rhs.remoteEndPoint);
}
public static bool operator !=(Simulator lhs, Simulator rhs)
{
return !(lhs == rhs);
}
protected override void PacketReceived(UDPPacketBuffer buffer)
{
Packet packet = null;
// Check if this packet came from the server we expected it to come from
if (!remoteEndPoint.Address.Equals(((IPEndPoint)buffer.RemoteEndPoint).Address))
{
Logger.Log("Received " + buffer.DataLength + " bytes of data from unrecognized source " +
((IPEndPoint)buffer.RemoteEndPoint), Helpers.LogLevel.Warning, Client);
return;
}
// Update the disconnect flag so this sim doesn't time out
DisconnectCandidate = false;
#region Packet Decoding
int packetEnd = buffer.DataLength - 1;
try
{
packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
// Only allocate a buffer for zerodecoding if the packet is zerocoded
((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[8192] : null);
}
catch (MalformedDataException)
{
Logger.Log(string.Format("Malformed data, cannot parse packet:\n{0}",
Utils.BytesToHexString(buffer.Data, buffer.DataLength, null)), Helpers.LogLevel.Error);
}
// Fail-safe check
if (packet == null)
{
Logger.Log("Couldn't build a message from the incoming data", Helpers.LogLevel.Warning, Client);
return;
}
Interlocked.Add(ref Stats.RecvBytes, buffer.DataLength);
Interlocked.Increment(ref Stats.RecvPackets);
#endregion Packet Decoding
if (packet.Header.Resent)
Interlocked.Increment(ref Stats.ReceivedResends);
#region ACK Receiving
// Handle appended ACKs
if (packet.Header.AppendedAcks && packet.Header.AckList != null)
{
lock (NeedAck)
{
for (int i = 0; i < packet.Header.AckList.Length; i++)
{
if (NeedAck.ContainsKey(packet.Header.AckList[i]) && NeedAck[packet.Header.AckList[i]].Type == PacketType.UseCircuitCode)
{
GotUseCircuitCodeAck.Set();
}
NeedAck.Remove(packet.Header.AckList[i]);
}
}
}
// Handle PacketAck packets
if (packet.Type == PacketType.PacketAck)
{
var ackPacket = (PacketAckPacket)packet;
lock (NeedAck)
{
for (int i = 0; i < ackPacket.Packets.Length; i++)
{
if (NeedAck.ContainsKey(ackPacket.Packets[i].ID) && NeedAck[ackPacket.Packets[i].ID].Type == PacketType.UseCircuitCode)
{
GotUseCircuitCodeAck.Set();
}
NeedAck.Remove(ackPacket.Packets[i].ID);
}
}
}
#endregion ACK Receiving
if (packet.Header.Reliable)
{
#region ACK Sending
// Add this packet to the list of ACKs that need to be sent out
var sequence = packet.Header.Sequence;
PendingAcks.Enqueue(sequence);
// Send out ACKs if we have a lot of them
if (PendingAcks.Count >= Client.Settings.MAX_PENDING_ACKS)
SendAcks();
#endregion ACK Sending
// Check the archive of received packet IDs to see whether we already received this packet
if (!PacketArchive.TryEnqueue(packet.Header.Sequence))
{
if (packet.Header.Resent)
Logger.DebugLog(
string.Format(
"Received a resend of already processed packet #{0}, type: {1} from {2}",
packet.Header.Sequence, packet.Type, Name));
else
Logger.Log(
string.Format(
"Received a duplicate (not marked as resend) of packet #{0}, type: {1} for {2} from {3}",
packet.Header.Sequence, packet.Type, Client.Self.Name, Name),
Helpers.LogLevel.Warning);
// Avoid firing a callback twice for the same packet
return;
}
}
#region Inbox Insertion
NetworkManager.IncomingPacket incomingPacket;
incomingPacket.Simulator = this;
incomingPacket.Packet = packet;
Network.PacketInbox.Enqueue(incomingPacket);
#endregion Inbox Insertion
#region Stats Tracking
if (Client.Settings.TRACK_UTILIZATION)
{
Client.Stats.Update(packet.Type.ToString(), OpenMetaverse.Stats.Type.Packet, 0, packet.Length);
}
#endregion
}
protected override void PacketSent(UDPPacketBuffer buffer, int bytesSent)
{
// Stats tracking
Interlocked.Add(ref Stats.SentBytes, bytesSent);
Interlocked.Increment(ref Stats.SentPackets);
Client.Network.RaisePacketSentEvent(buffer.Data, bytesSent, this);
}
/// <summary>
/// Sends out pending acknowledgements
/// </summary>
/// <returns>Number of ACKs sent</returns>
int SendAcks()
{
uint ack;
int ackCount = 0;
if (PendingAcks.TryDequeue(out ack))
{
var blocks = new List<PacketAckPacket.PacketsBlock>();
var block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
while (PendingAcks.TryDequeue(out ack))
{
block = new PacketAckPacket.PacketsBlock();
block.ID = ack;
blocks.Add(block);
}
var packet = new PacketAckPacket();
packet.Header.Reliable = false;
packet.Packets = blocks.ToArray();
ackCount = blocks.Count;
SendPacket(packet);
}
return ackCount;
}
/// <summary>
/// Resend unacknowledged packets
/// </summary>
void ResendUnacked()
{
int ackCount;
lock (NeedAck)
ackCount = NeedAck.Count;
if(ackCount > 0)
{
OutgoingPacket[] array;
lock (NeedAck)
{
// Create a temporary copy of the outgoing packets array to iterate over
array = new OutgoingPacket[NeedAck.Count];
NeedAck.Values.CopyTo(array, 0);
}
int now = Environment.TickCount;
// Resend packets
for (int i = 0; i < array.Length; i++)
{
OutgoingPacket outgoing = array[i];
if (outgoing.TickCount != 0 && now - outgoing.TickCount > Client.Settings.RESEND_TIMEOUT)
{
if (outgoing.ResendCount < Client.Settings.MAX_RESEND_COUNT)
{
if (Client.Settings.LOG_RESENDS)
{
lock (NeedAck) {
Logger.DebugLog (string.Format ("Resending {2} packet #{0}, {1}ms have passed",
outgoing.SequenceNumber, now - outgoing.TickCount, outgoing.Type), Client);
}
}
// The TickCount will be set to the current time when the packet
// is actually sent out again
outgoing.TickCount = 0;
// Set the resent flag
outgoing.Buffer.Data[0] = (byte)(outgoing.Buffer.Data[0] | Helpers.MSG_RESENT);
// Stats tracking
Interlocked.Increment(ref outgoing.ResendCount);
Interlocked.Increment(ref Stats.ResentPackets);
SendPacketFinal(outgoing);
}
else
{
Logger.DebugLog(string.Format("Dropping packet #{0} after {1} failed attempts",
outgoing.SequenceNumber, outgoing.ResendCount));
lock (NeedAck) NeedAck.Remove(outgoing.SequenceNumber);
}
}
}
}
}
void AckTimer_Elapsed(object obj)
{
SendAcks();
ResendUnacked();
// Start the ACK handling functions again after NETWORK_TICK_INTERVAL milliseconds
if (null == AckTimer) return;
try { AckTimer.Change(Settings.NETWORK_TICK_INTERVAL, Timeout.Infinite); }
catch (Exception) { }
}
void StatsTimer_Elapsed(object obj)
{
long old_in = 0, old_out = 0;
long recv = Stats.RecvBytes;
long sent = Stats.SentBytes;
if (InBytes.Count >= Client.Settings.STATS_QUEUE_SIZE)
old_in = InBytes.Dequeue();
if (OutBytes.Count >= Client.Settings.STATS_QUEUE_SIZE)
old_out = OutBytes.Dequeue();
InBytes.Enqueue(recv);
OutBytes.Enqueue(sent);
if (old_in > 0 && old_out > 0)
{
Stats.IncomingBPS = (int)(recv - old_in) / Client.Settings.STATS_QUEUE_SIZE;
Stats.OutgoingBPS = (int)(sent - old_out) / Client.Settings.STATS_QUEUE_SIZE;
//Client.Log("Incoming: " + IncomingBPS + " Out: " + OutgoingBPS +
// " Lag: " + LastLag + " Pings: " + ReceivedPongs +
// "/" + SentPings, Helpers.LogLevel.Debug);
}
}
void PingTimer_Elapsed(object obj)
{
SendPing();
Interlocked.Increment(ref Stats.SentPings);
}
}
public sealed class IncomingPacketIDCollection
{
readonly uint[] Items;
readonly HashSet<uint> hashSet;
readonly int capacity;
int first;
int next;
public IncomingPacketIDCollection(int capacity)
{
this.capacity = capacity;
Items = new uint[capacity];
hashSet = new HashSet<uint>();
}
public bool TryEnqueue(uint ack)
{
lock (hashSet)
{
if (hashSet.Add(ack))
{
Items[next] = ack;
next = (next + 1) % capacity;
if (next == first)
{
hashSet.Remove(Items[first]);
first = (first + 1) % capacity;
}
return true;
}
}
return false;
}
}
public class SimulatorDataPool
{
static Timer InactiveSimReaper;
static void RemoveOldSims(object state)
{
lock (SimulatorDataPools)
{
int SimTimeout = Settings.SIMULATOR_POOL_TIMEOUT;
var reap = new List<ulong>();
foreach (var pool in SimulatorDataPools.Values)
{
if (pool.InactiveSince != DateTime.MaxValue && pool.InactiveSince.AddMilliseconds(SimTimeout) < DateTime.Now)
{
reap.Add(pool.Handle);
}
}
foreach (var hndl in reap)
{
SimulatorDataPools.Remove(hndl);
}
}
}
public static void SimulatorAdd(Simulator sim)
{
lock (SimulatorDataPools)
{
if (InactiveSimReaper == null)
{
InactiveSimReaper = new Timer(RemoveOldSims, null, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(3));
}
SimulatorDataPool pool = GetSimulatorData(sim.Handle);
if (pool.ActiveClients < 1) pool.ActiveClients = 1; else pool.ActiveClients++;
pool.InactiveSince = DateTime.MaxValue;
}
}
public static void SimulatorRelease(Simulator sim)
{
ulong hndl = sim.Handle;
lock (SimulatorDataPools)
{
SimulatorDataPool dataPool = GetSimulatorData(hndl);
dataPool.ActiveClients--;
if (dataPool.ActiveClients <= 0)
{
dataPool.InactiveSince = DateTime.Now;
}
}
}
static public Dictionary<ulong, SimulatorDataPool> SimulatorDataPools = new Dictionary<ulong, SimulatorDataPool>();
/// <summary>
/// Simulator handle
/// </summary>
readonly public ulong Handle;
/// <summary>
/// Number of GridClients using this datapool
/// </summary>
public int ActiveClients;
/// <summary>
/// Time that the last client disconnected from the simulator
/// </summary>
public DateTime InactiveSince = DateTime.MaxValue;
#region Pooled Items
/// <summary>
/// The cache of prims used and unused in this simulator
/// </summary>
public Dictionary<uint, Primitive> PrimCache = new Dictionary<uint, Primitive>();
/// <summary>
/// Shared parcel info only when POOL_PARCEL_DATA == true
/// </summary>
public InternalDictionary<int, Parcel> Parcels = new InternalDictionary<int, Parcel>();
public int[,] ParcelMap = new int[64, 64];
public bool DownloadingParcelMap = false;
#endregion Pooled Items
SimulatorDataPool(ulong hndl)
{
Handle = hndl;
}
public static SimulatorDataPool GetSimulatorData(ulong hndl)
{
SimulatorDataPool dict;
lock (SimulatorDataPools)
{
if (!SimulatorDataPools.TryGetValue(hndl, out dict))
{
dict = SimulatorDataPools[hndl] = new SimulatorDataPool(hndl);
}
}
return dict;
}
#region Factories
internal Primitive MakePrimitive(uint localID)
{
var dict = PrimCache;
lock (dict)
{
Primitive prim;
if (!dict.TryGetValue(localID, out prim))
{
dict[localID] = prim = new Primitive { RegionHandle = Handle, LocalID = localID };
}
return prim;
}
}
internal bool NeedsRequest(uint localID)
{
var dict = PrimCache;
lock (dict) return !dict.ContainsKey(localID);
}
#endregion Factories
internal void ReleasePrims(List<uint> removePrims)
{
lock (PrimCache)
{
foreach (var u in removePrims)
{
Primitive prim;
if (PrimCache.TryGetValue(u, out prim)) prim.ActiveClients--;
}
}
}
}
}
| 37.874079 | 151 | 0.537828 |
[
"BSD-3-Clause"
] |
VisionSim/Vision-LibOMV
|
OpenMetaverse/Simulator.cs
| 56,546 |
C#
|
using CodeEditor.Features.NavigateTo.SourceSymbols.ServiceModel;
using CodeEditor.Reactive;
using CodeEditor.ReactiveServiceStack;
using ServiceStack.ServiceInterface;
namespace CodeEditor.Features.NavigateTo.SourceSymbols.Services
{
public class SourceSymbolSearchService : AsyncServiceBase<SourceSymbolSearchRequest>
{
public ISourceSymbolIndexProvider IndexProvider { get; set; }
protected override object Run(SourceSymbolSearchRequest request)
{
return
SourceSymbolIndex
.SearchSymbol(request.Filter)
.Select(s => new SourceSymbol {DisplayText = s.DisplayText, SourceFile = s.SourceFile.Path, Line = s.Line-1, Column = s.Column-1})
.ToJsonStreamWriter();
}
ISourceSymbolIndex SourceSymbolIndex
{
get { return IndexProvider.Index; }
}
}
}
| 31.192308 | 136 | 0.758323 |
[
"MIT"
] |
LaudateCorpus1/CodeEditor
|
src/CodeEditor.Features.NavigateTo.SourceSymbols.Services/SourceSymbolSearchService.cs
| 811 |
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 System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal class ManageNamingStylesDialogViewModel : AbstractNotifyPropertyChanged, IManageNamingStylesInfoDialogViewModel
{
private readonly INotificationService _notificationService;
public ObservableCollection<INamingStylesInfoDialogViewModel> Items { get; set; }
public string DialogTitle => ServicesVSResources.Manage_naming_styles;
public ManageNamingStylesDialogViewModel(
ObservableCollection<MutableNamingStyle> namingStyles,
List<NamingStyleOptionPageViewModel.NamingRuleViewModel> namingRules,
INotificationService notificationService)
{
_notificationService = notificationService;
Items = new ObservableCollection<INamingStylesInfoDialogViewModel>(namingStyles.Select(style => new NamingStyleViewModel(
style.Clone(),
!namingRules.Any(rule => rule.SelectedStyle?.ID == style.ID),
notificationService)));
}
internal void RemoveNamingStyle(NamingStyleViewModel namingStyle)
=> Items.Remove(namingStyle);
public void AddItem()
{
var style = new MutableNamingStyle();
var viewModel = new NamingStyleViewModel(style, canBeDeleted: true, notificationService: _notificationService);
var dialog = new NamingStyleDialog(viewModel);
if (dialog.ShowModal().Value == true)
{
Items.Add(viewModel);
}
}
public void RemoveItem(INamingStylesInfoDialogViewModel item)
=> Items.Remove(item);
public void EditItem(INamingStylesInfoDialogViewModel item)
{
var context = (NamingStyleViewModel)item;
var style = context.GetNamingStyle();
var viewModel = new NamingStyleViewModel(style, context.CanBeDeleted, notificationService: _notificationService);
var dialog = new NamingStyleDialog(viewModel);
if (dialog.ShowModal().Value == true)
{
context.ItemName = viewModel.ItemName;
context.RequiredPrefix = viewModel.RequiredPrefix;
context.RequiredSuffix = viewModel.RequiredSuffix;
context.WordSeparator = viewModel.WordSeparator;
context.CapitalizationSchemeIndex = viewModel.CapitalizationSchemeIndex;
}
}
}
}
| 40.702703 | 133 | 0.693559 |
[
"MIT"
] |
333fred/roslyn
|
src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/NamingStyles/ManageNamingStylesDialogViewModel.cs
| 3,014 |
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Upgrade;
using Ship;
using Bombs;
namespace UpgradesList
{
public class ThermalDetonators : GenericTimedBomb
{
public ThermalDetonators() : base()
{
Types.Add(UpgradeType.Bomb);
Name = "Thermal Detonators";
Cost = 3;
bombPrefabPath = "Prefabs/Bombs/ThermalDetonator";
IsDiscardedAfterDropped = true;
}
public override void ExplosionEffect(GenericShip ship, Action callBack)
{
DamageSourceEventArgs thermaldetDamage = new DamageSourceEventArgs()
{
Source = this,
DamageType = DamageTypes.BombDetonation
};
ship.Damage.TryResolveDamage(1, thermaldetDamage, delegate { ship.Tokens.AssignToken(typeof(Tokens.StressToken), callBack); });
}
public override void PlayDetonationAnimSound(GameObject bombObject, Action callBack)
{
BombsManager.CurrentBomb = this;
Sounds.PlayBombSound(bombObject, "Explosion-7");
bombObject.transform.Find("Explosion/Explosion").GetComponent<ParticleSystem>().Play();
bombObject.transform.Find("Explosion/Ring").GetComponent<ParticleSystem>().Play();
GameManagerScript.Wait(1.4f, delegate { callBack(); });
}
}
}
| 28.098039 | 139 | 0.633636 |
[
"MIT"
] |
MatthewBlanchard/FlyCasual
|
Assets/Scripts/Model/Upgrades/Bomb/ThermalDetonators.cs
| 1,435 |
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Msr.Odr.Web
{
public class AppConfiguration
{
public AppConfiguration(IConfiguration config)
{
ApiBaseUrl = config["ApiBaseUrl"];
SiteMap = config["SiteMap"];
AzureAD = new AppConfigurationAzureADConfig(config);
}
public string ApiBaseUrl { get; }
public string SiteMap { get; }
public AppConfigurationAzureADConfig AzureAD { get; }
}
public class AppConfigurationAzureADConfig
{
public AppConfigurationAzureADConfig(IConfiguration config)
{
Tenant = config["AzureAD:Tenant"];
Audience = config["AzureAD:Audience"];
Policy = config["AzureAD:Policy"];
}
public string Tenant { get; }
public string Audience { get; }
public string Policy { get; }
}
}
| 27.410256 | 67 | 0.637979 |
[
"MIT"
] |
Sahaj26/opendatacloud
|
src/Msr.Odr.Web/AppConfiguration.cs
| 1,069 |
C#
|
namespace Bot.Builder.Community.Helpers
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class RandomHelper
{
private static readonly Random _random = new Random((int)DateTime.UtcNow.Ticks);
public static int GetRandom(int left, int right)
{
return _random.Next(left, right);
}
/// <summary>
/// select randomly a subset of size k from online data
/// </summary>
public static IEnumerable<T> GetRandomSubset<T>(IEnumerable<T> data, int k)
{
var result = new List<T>();
int step = 0;
foreach (var el in data)
{
step++;
if (step <= k)
{
// initially store in the result the first k elements in the collection
result.Add(el);
continue;
}
// at step i, probability to be selected is k/i
int pos = _random.Next(step);
if (pos < k)
{
// store element in the result at random position
result[pos] = el;
}
}
return result;
}
public static int Next(this Random r, int minValue, int maxValue, params int[] exclude)
{
int value;
bool excluded;
do
{
value = r.Next(minValue, maxValue);
excluded = exclude.Contains(value);
} while (excluded);
return value;
}
}
}
| 28.982456 | 95 | 0.476998 |
[
"MIT"
] |
weretygr/BotRelated
|
libraries/Bot.Builder.Community.WebChatStyling/Helpers/RandomHelper.cs
| 1,654 |
C#
|
namespace StrongHeart.Features.Core
{
public interface IResponseDto
{
}
}
| 14.333333 | 36 | 0.686047 |
[
"MIT"
] |
kasperbirkelund/StrongHeart
|
Src/StrongHeart.Features/Core/IResponseDto.cs
| 88 |
C#
|
/*
This file is a part of JustLogic product which is distributed under
the BSD 3-clause "New" or "Revised" License
Copyright (c) 2015. All rights reserved.
Authors: Vladyslav Taranov.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JustLogic nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using JustLogic.Core;
using System.Collections.Generic;
using System;
[UnitMenu("String/To Lower")]
[UnitFriendlyName("String.To Lower")]
[UnitUsage(typeof(String), HideExpressionInActionsList = true)]
public class JLStringToLower : JLExpression
{
[Parameter(ExpressionType = typeof(String))]
public JLExpression OperandValue;
public override object GetAnyResult(IExecutionContext context)
{
String opValue = OperandValue.GetResult<String>(context);
return opValue.ToLower();
}
}
| 40.185185 | 79 | 0.776959 |
[
"BSD-3-Clause"
] |
AqlaSolutions/JustLogic
|
Assets/JustLogicUnits/Generated/String/JLStringToLower.cs
| 2,170 |
C#
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Management.MachineLearningCompute;
using Microsoft.Azure.Management.MachineLearningCompute.Models;
using Microsoft.Rest.Azure;
using System;
namespace Microsoft.Azure.Commands.MachineLearningCompute.Cmdlets
{
public abstract class MachineLearningComputeCmdletBase : AzureRMCmdlet
{
public const string CmdletSuffix = "AzureRmMlOpCluster";
public const string ResourceGroupParameterHelpMessage = "The name of the resource group for the operationalization cluster.";
public const string NameParameterHelpMessage = "The name of the operationalization cluster.";
public const string ClusterObjectParameterHelpMessage = "The operationalization cluster object.";
public const string ResourceIdParameterHelpMessage = "The Azure resource id for the operationalization cluster.";
public const string ForceParameterHelpMessage = "Do not ask for confirmation.";
public const string ClusterParameterHelpMessage = "The operationalization cluster properties.";
public const string TagParameterHelpMessage = "The tags for the resource.";
public const string LocationParameterHelpMessage = "The operationalization cluster's location.";
public const string DescriptionParameterHelpMessage = "The operationalization cluster's description.";
public const string ClusterTypeParameterHelpMessage = "The operationalization cluster type.";
public const string OrchestratorTypeParameterHelpMessage = "The ACS cluster's orchestrator type.";
public const string ClientIdParameterHelpMessage = "The Kubernetes orchestrator service principal id.";
public const string SecretParameterHelpMessage = "The Kubernetes orchestrator service principal secret.";
public const string MasterCountParameterHelpMessage = "The number of master nodes in the ACS cluster.";
public const string AgentCountParameterHelpMessage = "The number of agent nodes in the ACS cluster.";
public const string AgentVmSizeParameterHelpMessage = "The VM size of the agent nodes in the ACS cluster.";
public const string StorageAccountParameterHelpMessage = "The URI to the storage account to use instead of creating one.";
public const string AzureContainerRegistryParameterHelpMessage = "The URI to the azure container registry to use instead of creating one.";
public const string ApplicationInsightsParameterHelpMessage = "The URI to the application insights to use instead of creating one.";
public const string ETagParameterHelpMessage = "The configuration ETag for updates.";
public const string GlobalServiceConfigurationAdditionalPropertiesHelpMessage = "Additional properties for the global service configuration.";
public const string SslStatusParameterHelpMessage = "SSL status. Possible values are 'Enabled' and 'Disabled'.";
public const string SslCertificateParameterHelpMessage = "The SSL certificate data in PEM format.";
public const string SslKeyParameterHelpMessage = "The SSL key data in PEM format.";
public const string SslCNameParameterHelpMessage = "The CName for the SSL certificate.";
public const string IncludeAllResourcesParameterHelpMessage = "Remove all resources associated with the cluster.";
public const string ClusterInputObjectAlias = "Cluster";
private IMachineLearningComputeManagementClient machineLearningComputeManagementClient;
public IMachineLearningComputeManagementClient MachineLearningComputeManagementClient
{
get
{
return machineLearningComputeManagementClient ??
(machineLearningComputeManagementClient =
AzureSession.Instance.ClientFactory.CreateArmClient<MachineLearningComputeManagementClient>(
DefaultProfile.DefaultContext, Common.Authentication.Abstractions.AzureEnvironment.Endpoint.ResourceManager));
}
}
protected void HandleNestedExceptionMessages(Exception e)
{
var unwrappedException = e;
// Try to get the details out of the exception
try
{
if (e is ErrorResponseWrapperException)
{
var wrappedException = e as ErrorResponseWrapperException;
if (wrappedException.Body != null && wrappedException.Body.Error != null)
{
var exceptionDetails = e.Message + ": " + wrappedException.Body.Error.Message;
if (wrappedException.Body.Error.Details != null)
{
foreach (var err in wrappedException.Body.Error.Details)
{
exceptionDetails += $" {err.Message};";
}
}
unwrappedException = new ErrorResponseWrapperException(exceptionDetails);
}
}
else if(e is CloudException)
{
var cloudException = e as CloudException;
var exceptionDetails = e.Message;
if (cloudException.Body != null && cloudException.Body.Details != null)
{
exceptionDetails += ":";
foreach (var err in cloudException.Body.Details)
{
exceptionDetails += $" {err.Message};";
}
unwrappedException = new CloudException(exceptionDetails);
}
}
}
catch (Exception) // If there's trouble throw the original exception
{
throw e;
}
throw unwrappedException;
}
}
}
| 57.319672 | 151 | 0.644359 |
[
"MIT"
] |
Acidburn0zzz/azure-powershell
|
src/ResourceManager/MachineLearning/Commands.MachineLearningCompute/Cmdlets/MachineLearningComputeCmdletBase.cs
| 6,874 |
C#
|
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Radio.Intercom
{
/// <summary>
/// Enumeration values for RecordType (radio.ic.param.type, Record type,
/// section 9.3.6.1)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public enum RecordType : ushort
{
/// <summary>
/// Entity Destination record.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Entity Destination record.")]
EntityDestinationRecord = 1,
/// <summary>
/// Group Destination record.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Group Destination record.")]
GroupDestinationRecord = 2,
/// <summary>
/// Group Assignment record.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Group Assignment record.")]
GroupAssignmentRecord = 3
}
}
| 62.45 | 147 | 0.717374 |
[
"BSD-2-Clause"
] |
cdettmering-unity/open-dis-csharp
|
CsharpDis6/OpenDis/Enumerations/Radio.Intercom/RecordType.cs
| 3,747 |
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 comprehend-2017-11-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Comprehend.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Comprehend.Model.Internal.MarshallTransformations
{
/// <summary>
/// StartEventsDetectionJob Request Marshaller
/// </summary>
public class StartEventsDetectionJobRequestMarshaller : IMarshaller<IRequest, StartEventsDetectionJobRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((StartEventsDetectionJobRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(StartEventsDetectionJobRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Comprehend");
string target = "Comprehend_20171127.StartEventsDetectionJob";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-11-27";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetClientRequestToken())
{
context.Writer.WritePropertyName("ClientRequestToken");
context.Writer.Write(publicRequest.ClientRequestToken);
}
else if(!(publicRequest.IsSetClientRequestToken()))
{
context.Writer.WritePropertyName("ClientRequestToken");
context.Writer.Write(Guid.NewGuid().ToString());
}
if(publicRequest.IsSetDataAccessRoleArn())
{
context.Writer.WritePropertyName("DataAccessRoleArn");
context.Writer.Write(publicRequest.DataAccessRoleArn);
}
if(publicRequest.IsSetInputDataConfig())
{
context.Writer.WritePropertyName("InputDataConfig");
context.Writer.WriteObjectStart();
var marshaller = InputDataConfigMarshaller.Instance;
marshaller.Marshall(publicRequest.InputDataConfig, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetJobName())
{
context.Writer.WritePropertyName("JobName");
context.Writer.Write(publicRequest.JobName);
}
if(publicRequest.IsSetLanguageCode())
{
context.Writer.WritePropertyName("LanguageCode");
context.Writer.Write(publicRequest.LanguageCode);
}
if(publicRequest.IsSetOutputDataConfig())
{
context.Writer.WritePropertyName("OutputDataConfig");
context.Writer.WriteObjectStart();
var marshaller = OutputDataConfigMarshaller.Instance;
marshaller.Marshall(publicRequest.OutputDataConfig, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetTargetEventTypes())
{
context.Writer.WritePropertyName("TargetEventTypes");
context.Writer.WriteArrayStart();
foreach(var publicRequestTargetEventTypesListValue in publicRequest.TargetEventTypes)
{
context.Writer.Write(publicRequestTargetEventTypesListValue);
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static StartEventsDetectionJobRequestMarshaller _instance = new StartEventsDetectionJobRequestMarshaller();
internal static StartEventsDetectionJobRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static StartEventsDetectionJobRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 38.329193 | 161 | 0.592773 |
[
"Apache-2.0"
] |
PureKrome/aws-sdk-net
|
sdk/src/Services/Comprehend/Generated/Model/Internal/MarshallTransformations/StartEventsDetectionJobRequestMarshaller.cs
| 6,171 |
C#
|
using System;
using Ding.Caches;
namespace Ding.Locks.Default {
/// <summary>
/// 业务锁
/// </summary>
public class DefaultLock : ILock {
/// <summary>
/// 缓存
/// </summary>
private readonly ICache _cache;
/// <summary>
/// 锁定标识
/// </summary>
private string _key;
/// <summary>
/// 延迟执行时间
/// </summary>
private TimeSpan? _expiration;
/// <summary>
/// 初始化业务锁
/// </summary>
/// <param name="cache">缓存</param>
public DefaultLock( ICache cache ) {
_cache = cache;
}
/// <summary>
/// 锁定,成功锁定返回true,false代表之前已被锁定
/// </summary>
/// <param name="key">锁定标识</param>
/// <param name="expiration">锁定时间间隔</param>
public bool Lock( string key, TimeSpan? expiration = null ) {
_key = key;
_expiration = expiration;
if ( _cache.Exists( key ) )
return false;
return _cache.TryAdd( key, 1, expiration );
}
/// <summary>
/// 解除锁定
/// </summary>
public void UnLock() {
if ( _expiration != null )
return;
if( _cache.Exists( _key ) == false )
return;
_cache.Remove( _key );
}
}
}
| 24.927273 | 69 | 0.455142 |
[
"MIT"
] |
EnhWeb/DC.Framework
|
src/Ding/Locks/Default/DefaultLock.cs
| 1,483 |
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GradesPrototype.Data;
using GradesPrototype.Services;
using GradesPrototype.Views;
namespace GradesPrototype
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GotoLogon();
}
#region Navigation
// TODO: Exercise 1: Task 3a: Display the logon view and and hide the list of students and single student view
public void GotoLogon()
{
logonPage.Visibility = Visibility.Visible;
studentsPage.Visibility = Visibility.Collapsed;
studentProfile.Visibility = Visibility.Collapsed;
}
// TODO: Exercise 1: Task 4c: Display the list of students
private void GotoStudentsPage()
{
studentProfile.Visibility = Visibility.Collapsed;
studentsPage.Visibility = Visibility.Visible;
Refresh();
}
// TODO: Exercise 1: Task 4b: Display the details for a single student
public void GotoStudentProfile()
{
studentsPage.Visibility = Visibility.Collapsed;
studentProfile.Visibility = Visibility.Visible;
Refresh();
}
#endregion
#region Event Handlers
// TODO: Exercise 1: Task 3b: Handle successful logon
private void Logon_Success(object sender, EventArgs e)
{
// Update the display and show the data for the logged on user
logonPage.Visibility = Visibility.Collapsed;
gridLoggedIn.Visibility = Visibility.Visible;
Refresh();
}
// Handle logoff
private void Logoff_Click(object sender, RoutedEventArgs e)
{
// Hide all views apart from the logon page
gridLoggedIn.Visibility = Visibility.Collapsed;
studentsPage.Visibility = Visibility.Collapsed;
studentProfile.Visibility = Visibility.Collapsed;
logonPage.Visibility = Visibility.Visible;
}
// Handle the Back button on the Student page
private void studentPage_Back(object sender, EventArgs e)
{
GotoStudentsPage();
}
// TODO: Exercise 1: Task 5b: Handle the StudentSelected event when the user clicks a student on the Students page
// Set the global context to the name of the student and call the GotoStudentProfile method to display the details of the student
private void studentsPage_StudentSelected(object sender, StudentEventArgs e)
{
SessionContext.CurrentStudent = e.Child;
GotoStudentProfile();
}
#endregion
#region Display Logic
// TODO: Exercise 1: Task 4a: Update the display for the logged on user (student or teacher)
private void Refresh()
{
txtName.Text = string.Format("Welcome {0}", SessionContext.UserName);
switch (SessionContext.UserRole)
{
case Role.Teacher:
GotoStudentsPage();
break;
case Role.Student:
GotoStudentProfile();
break;
}
}
#endregion
}
}
| 32.215517 | 137 | 0.623227 |
[
"MIT"
] |
AurimasNav/20483C
|
Allfiles/Mod03/Labfiles/Starter/Exercise 1/GradesPrototype/MainWindow.xaml.cs
| 3,739 |
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("DjvuReader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DjvuReader")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("b4c5ae22-c292-4f35-8e16-2df4c819d77f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.513514 | 84 | 0.747118 |
[
"MIT"
] |
fel88/CommonLibs
|
DjvuReader/Properties/AssemblyInfo.cs
| 1,391 |
C#
|
using UnityEngine;
namespace game
{
public class AdvertManager : MonoBehaviour
{
public bool tagForChildDirectedTreatment = false;
private IAdvertService m_service = null;
void Start()
{
#if UNITY_EDITOR
DummyAdvertService service = new DummyAdvertService();
service.SetTagForChildDirectedTreatment(this.tagForChildDirectedTreatment);
service.interstitalLoadedEvent += OnInterstitialLoaded;
service.interstitalFailedEvent += OnInterstitialFailed;
m_service = service;
#elif UNITY_ANDROID && ENABLE_ADS
// pass
#elif UNITY_IOS && ENABLE_ADS
// pass
#else
DummyAdvertService service = new DummyAdvertService();
m_service = service;
#endif
}
void OnDestroy()
{
m_service.DestroyBanner();
}
public void ShowBanner()
{
m_service.ShowBanner();
}
public void HideBanner()
{
m_service.HideBanner();
}
public void LoadInterstitial()
{
m_service.LoadInterstitial();
}
public void ShowInterstitial()
{
m_service.ShowInterstitial();
}
private void OnInterstitialLoaded()
{
}
private void OnInterstitialFailed()
{
}
}
}
| 17.075758 | 78 | 0.711624 |
[
"BSD-3-Clause"
] |
IRONKAGE/ShutemUpValhallaHackGames
|
Assets/Scripts/AdvertService/AdvertManager.cs
| 1,127 |
C#
|
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Efs
{
[Serializable]
[EfsFile("/nv/item_files/rfnv/00024640", true, 0xE1FF)]
[Attributes(9)]
public class LteB26TxLinVsTemp
{
[ElementsCount(64)]
[ElementType("int8")]
[Description("")]
public sbyte[] Value { get; set; }
}
}
| 21.47619 | 60 | 0.611973 |
[
"MIT"
] |
HomerSp/EfsTools
|
EfsTools/Items/Efs/LteB26TxLinVsTempI.cs
| 451 |
C#
|
using System;
namespace Org.BouncyCastle.Security.Certificates
{
public class CertificateNotYetValidException : CertificateException
{
public CertificateNotYetValidException() : base() { }
public CertificateNotYetValidException(string message) : base(message) { }
public CertificateNotYetValidException(string message, Exception exception) : base(message, exception) { }
}
}
| 33 | 109 | 0.775253 |
[
"BSD-3-Clause"
] |
GaloisInc/hacrypto
|
src/C#/BouncyCastle/BouncyCastle-1.7/crypto/src/security/cert/CertificateNotYetValidException.cs
| 396 |
C#
|
namespace Witsml.Data
{
public interface IWitsmlQueryType
{
string TypeName { get; }
}
public interface IWitsmlGrowingDataQueryType : IWitsmlQueryType { }
}
| 18.2 | 71 | 0.686813 |
[
"Apache-2.0"
] |
AtleH/witsml-explorer
|
Src/Witsml/Data/IWitsmlQueryType.cs
| 182 |
C#
|
using System;
namespace TDL.Client.Runner.Exceptions
{
public class RecordingSystemNotReachable : Exception
{
public RecordingSystemNotReachable(Exception innerException)
: base($"Could not reach recording system: {innerException.Message}", innerException)
{
}
}
}
| 24.230769 | 97 | 0.68254 |
[
"Apache-2.0"
] |
julianghionoiu/tdl-client-dotnet
|
src/Client/Runner/Exceptions/RecordingSystemNotReachable.cs
| 317 |
C#
|
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Foundation;
using System;
using System.Threading;
using Sensus.Dispose;
using Sensus.Concurrent;
using Xamarin.Forms;
namespace Sensus.iOS.Concurrent
{
public class MainConcurrent : Disposable, IConcurrent
{
private readonly int? _waitTime;
public MainConcurrent(int? waitTime = null)
{
_waitTime = waitTime;
}
public void ExecuteThreadSafe(Action action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (NSThread.IsMain)
{
action();
}
else
{
ManualResetEvent actionWait = new ManualResetEvent(false);
Exception actionException = null;
NSThread.MainThread.BeginInvokeOnMainThread(() =>
{
try
{
action();
}
catch (Exception ex)
{
actionException = ex;
}
finally
{
actionWait.Set();
}
});
if (_waitTime == null)
{
actionWait.WaitOne();
}
else
{
actionWait.WaitOne(_waitTime.Value);
}
if (actionException != null)
{
throw actionException;
}
}
}
public T ExecuteThreadSafe<T>(Func<T> func)
{
if (func == null)
{
throw new ArgumentNullException(nameof(func));
}
if (NSThread.IsMain)
{
return func();
}
else
{
T funcResult = default(T);
ManualResetEvent funcWait = new ManualResetEvent(false);
Exception funcException = null;
NSThread.MainThread.BeginInvokeOnMainThread(() =>
{
try
{
funcResult = func();
}
catch (Exception ex)
{
funcException = ex;
}
finally
{
funcWait.Set();
}
});
if (_waitTime == null)
{
funcWait.WaitOne();
}
else
{
funcWait.WaitOne(_waitTime.Value);
}
if (funcException != null)
{
throw funcException;
}
return funcResult;
}
}
}
}
| 27.371212 | 75 | 0.432328 |
[
"Apache-2.0"
] |
MatthewGerber/sensus
|
Sensus.iOS.Shared/Concurrent/MainConcurrent.cs
| 3,613 |
C#
|
namespace Assimalign.Extensions.Validation;
/// <summary>
/// An abstraction of a validation error.
/// </summary>
public interface IValidationError
{
/// <summary>
/// A unique error code to use when the validation rule fails.
/// </summary>
string Code { get; set; }
/// <summary>
/// A unique error message to use when the validation rule fails.
/// </summary>
string Message { get; set; }
/// <summary>
/// An identifier of the source of the validation error.
/// </summary>
string Source { get; set; }
}
| 25.5 | 69 | 0.623886 |
[
"MIT"
] |
Assimalign-LLC/asal-dotnet-extensions
|
src/validation/src/Assimalign.Extensions.Validation/Abstractions/IValidationError.cs
| 563 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Wodsoft.ComBoost.Wpf.Editor
{
[TemplatePart(Name = "PART_TextBox", Type = typeof(TextBox))]
public class TimeEditor : EditorBase
{
static TimeEditor()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TimeEditor), new FrameworkPropertyMetadata(typeof(TimeEditor)));
}
protected TextBox TextBox { get; private set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
TextBox = (TextBox)GetTemplateChild("PART_TextBox");
TextBox.SetBinding(TextBox.TextProperty, new Binding { Source = this, Path = new PropertyPath(CurrentValueProperty), Mode = BindingMode.OneWay });
TextBox.TextChanged += TextBox_TextChanged;
}
void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TimeSpan value;
TimeSpan.TryParse(TextBox.Text, out value);
CurrentValue = value;
IsChanged = true;
}
}
}
| 31.111111 | 158 | 0.683571 |
[
"MIT"
] |
alexyjian/Core3.0
|
Wodsoft.ComBoost.Wpf/Editor/TimeEditor.cs
| 1,402 |
C#
|
namespace IronFoundry.Bosh.Messages
{
using System;
using IronFoundry.Bosh.Properties;
using IronFoundry.Nats.Client;
using Newtonsoft.Json;
public class Heartbeat : NatsMessage
{
private readonly string publishSubject;
public Heartbeat(string agentID)
{
if (agentID.IsNullOrWhiteSpace()) // TODO code contracts?
{
throw new ArgumentException(Resources.Heartbeat_RequiresAgentID_Message, "agentID");
}
this.publishSubject = String.Format("hm.agent.heartbeat.{0}", agentID);
}
[JsonProperty("job")]
public string Job { get; set; }
[JsonProperty("index")]
public ushort Index { get; set; } // TODO comes from state
[JsonProperty("job_state")]
public string JobState { get; set; } // TODO one job per Agent
[JsonProperty("vitals")]
public Vitals Vitals { get; set; }
[JsonProperty("ntp")]
public NtpStat Ntp { get; set; }
public override string PublishSubject
{
get { return publishSubject; }
}
public override bool CanPublishWithSubject(string subject)
{
return subject.Equals(publishSubject);
}
}
public class Vitals
{
[JsonProperty("load")]
public float[] Load { get; set; }
[JsonProperty("cpu")]
public CpuStat Cpu { get; set; }
[JsonProperty("mem")]
public UsageStat Mem { get; set; }
[JsonProperty("swap")]
public UsageStat Swap { get; set; }
[JsonProperty("disk")]
public DiskStat Disk { get; set; }
}
public class CpuStat
{
[JsonProperty("user")]
public float User { get; set; }
[JsonProperty("sys")]
public float Sys { get; set; }
[JsonProperty("wait")]
public float Wait { get; set; }
}
public class UsageStat
{
[JsonProperty("percent")]
public float Percent { get; set; }
[JsonProperty("kb")]
public uint KiloBytes { get; set; }
}
public class DiskStat
{
[JsonProperty("system")]
public Percentage System { get; set; }
[JsonProperty("ephemeral")]
public Percentage Ephemeral { get; set; }
[JsonProperty("persistent")]
public Percentage Persistent { get; set; }
}
public class Percentage
{
public Percentage() { }
public Percentage(ushort percent)
{
this.Percent = percent;
}
[JsonProperty("percent")]
public ushort Percent { get; set; }
}
public class NtpStat
{
[JsonProperty("offset")]
public float Offset { get; set; }
[JsonProperty("timestamp")] // TODO converter?
public string Timestamp { get; set; }
}
}
/*
# Heartbeat payload example:
# {
# "job": "cloud_controller",
# "index": 3,
# "job_state":"running",
# "vitals": {
# "load": ["0.09","0.04","0.01"],
# "cpu": {"user":"0.0","sys":"0.0","wait":"0.4"},
# "mem": {"percent":"3.5","kb":"145996"},
# "swap": {"percent":"0.0","kb":"0"},
# "disk": {
# "system": {"percent" => "82"},
# "ephemeral": {"percent" => "5"},
# "persistent": {"percent" => "94"}
# },
# "ntp": {
# "offset": "-0.06423",
# "timestamp": "14 Oct 11:13:19"
# }
# }
def heartbeat_payload
job_state = Bosh::Agent::Monit.service_group_state
monit_vitals = Bosh::Agent::Monit.get_vitals
# TODO(?): move DiskUtil out of Message namespace
disk_usage = Bosh::Agent::Message::DiskUtil.get_usage
job_name = @state["job"] ? @state["job"]["name"] : nil
index = @state["index"]
vitals = monit_vitals.merge("disk" => disk_usage)
Yajl::Encoder.encode("job" => job_name,
"index" => index,
"job_state" => job_state,
"vitals" => vitals,
"ntp" => Bosh::Agent::NTP.offset)
*/
| 28.506849 | 100 | 0.529073 |
[
"Apache-2.0"
] |
ironfoundry-attic/ironfoundry
|
src/IronFoundry.Bosh/Messages/Heartbeat.cs
| 4,164 |
C#
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SFA.DAS.AssessorService.Api.Types.Models;
using SFA.DAS.AssessorService.Application.Api.Client.Clients;
using SFA.DAS.AssessorService.Application.Api.Client.Exceptions;
using SFA.DAS.AssessorService.Domain.Consts;
using SFA.DAS.AssessorService.Settings;
using SFA.DAS.AssessorService.Web.Constants;
using SFA.DAS.AssessorService.Web.Infrastructure;
using SFA.DAS.AssessorService.Web.StartupConfiguration;
namespace SFA.DAS.AssessorService.Web.Controllers.ManageUsers
{
[PrivilegeAuthorize(Privileges.ManageUsers)]
[CheckSession]
public class ManageUsersController : Controller
{
private readonly IContactsApiClient _contactsApiClient;
private readonly IHttpContextAccessor _contextAccessor;
private readonly IOrganisationsApiClient _organisationsApiClient;
private readonly IEmailApiClient _emailApiClient;
private readonly IWebConfiguration _config;
public ManageUsersController(IWebConfiguration config, IContactsApiClient contactsApiClient,
IHttpContextAccessor contextAccessor, IOrganisationsApiClient organisationsApiClient, IEmailApiClient emailApiClient)
{
_contactsApiClient = contactsApiClient;
_contextAccessor = contextAccessor;
_organisationsApiClient = organisationsApiClient;
_emailApiClient = emailApiClient;
_config = config;
}
[HttpGet]
[TypeFilter(typeof(MenuFilter), Arguments = new object[] {Pages.Organisations})]
public async Task<IActionResult> Index()
{
var userId = _contextAccessor.HttpContext.User.FindFirst("UserId")?.Value;
var organisation = await _organisationsApiClient.GetOrganisationByUserId(Guid.Parse(userId));
var response = await _contactsApiClient.GetAllContactsForOrganisationIncludePrivileges(organisation.EndPointAssessorOrganisationId);
return View(response);
}
[HttpGet]
[Route("/[controller]/status/{id}/{status}")]
public async Task<IActionResult> SetStatusAndNotify(Guid id, string status)
{
if (status == ContactStatus.Approve)
{
await _contactsApiClient.ApproveContact(id);
}
else
{
await _contactsApiClient.RejectContact(id);
}
return RedirectToAction("Index");
}
}
}
| 39.059701 | 144 | 0.714177 |
[
"MIT"
] |
SkillsFundingAgency/das-assessor-service
|
src/SFA.DAS.AssessorService.Web/Controllers/ManageUsers/ManageUsersController.cs
| 2,619 |
C#
|
using System.Data.Common;
namespace TransactionWeaver
{
public interface IDbConnectionProvider
{
DbConnection Current { get; set; }
DbConnection CreateConnection();
}
}
| 18.090909 | 42 | 0.683417 |
[
"MIT"
] |
nuitsjp/TransactionWeaver
|
Source/TransactionWeaver/IDbConnectionProvider.cs
| 201 |
C#
|
using System;
namespace Core.Framework
{
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class ModuleAttribute : Attribute
{
/// <summary>
/// Name of the module
/// </summary>
public string Name { get; set; }
}
}
| 20.133333 | 64 | 0.556291 |
[
"MIT"
] |
cdotyone/Core.Framework
|
Core.Framework/EntityInfo/ModuleAttribute.cs
| 304 |
C#
|
using System;
using System.ServiceModel.Syndication;
using NetNewsTicker.Model;
namespace NetNewsTicker.Services.RSS
{
public class RSSItem : IContentItem
{
private protected string link, secondaryLink;
private protected bool hasLink;
private protected bool hasSummary;
private protected string itemHeadline, itemSummary;
private protected DateTime itemCreationDate;
public string ItemHeadline => itemHeadline;
public string ItemSummary => itemSummary;
public int ItemId => -1;
public bool HasLink => hasLink;
public bool HasSummary => hasSummary;
public string Link => link;
public string SecondaryLink => link; // no secondary link;
public bool HasSubItems => false;
public Memory<int> SubItems => null;
public DateTime ItemCreationDate => itemCreationDate;
public RSSItem(SyndicationItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
itemHeadline = item.Title.Text;
if (item.Links.Count > 0)
{
link = item.Links[0].Uri.ToString();
hasLink = true;
}
else
{
hasLink = false;
link = string.Empty;
}
}
public bool Equals(IContentItem other)
{
if (other != null)
{
return itemHeadline.Equals(other.ItemHeadline, StringComparison.InvariantCulture);
}
else
{
return false;
}
}
public override bool Equals(object other)
{
return other is IContentItem otherItem ? Equals(otherItem) : false;
}
public override int GetHashCode()
{
return itemHeadline.GetHashCode(StringComparison.InvariantCulture);
}
}
}
| 28.869565 | 98 | 0.559739 |
[
"MIT"
] |
CBGonzalez/NetNewsTicker
|
NetNewsTicker/Services/RSS/RSSItem.cs
| 1,994 |
C#
|
#pragma warning disable CS1591
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.ComponentModel;
namespace Efl {
/// <summary>Efl media playable interface</summary>
[Efl.IPlayableConcrete.NativeMethods]
[Efl.Eo.BindingEntity]
public interface IPlayable :
Efl.Eo.IWrapper, IDisposable
{
/// <summary>Get the length of play for the media file.</summary>
/// <returns>The length of the stream in seconds.</returns>
double GetLength();
bool GetPlayable();
/// <summary>Get whether the media file is seekable.</summary>
/// <returns><c>true</c> if seekable.</returns>
bool GetSeekable();
/// <summary>Get the length of play for the media file.</summary>
/// <value>The length of the stream in seconds.</value>
double Length {
get ;
}
bool Playable {
get ;
}
/// <summary>Get whether the media file is seekable.</summary>
/// <value><c>true</c> if seekable.</value>
bool Seekable {
get ;
}
}
/// <summary>Efl media playable interface</summary>
sealed public class IPlayableConcrete :
Efl.Eo.EoWrapper
, IPlayable
{
///<summary>Pointer to the native class description.</summary>
public override System.IntPtr NativeClass
{
get
{
if (((object)this).GetType() == typeof(IPlayableConcrete))
{
return GetEflClassStatic();
}
else
{
return Efl.Eo.ClassRegister.klassFromType[((object)this).GetType()];
}
}
}
/// <summary>Constructor to be used when objects are expected to be constructed from native code.</summary>
/// <param name="ch">Tag struct storing the native handle of the object being constructed.</param>
private IPlayableConcrete(ConstructingHandle ch) : base(ch)
{
}
[System.Runtime.InteropServices.DllImport("libefl.so.1")] internal static extern System.IntPtr
efl_playable_interface_get();
/// <summary>Initializes a new instance of the <see cref="IPlayable"/> class.
/// Internal usage: This is used when interacting with C code and should not be used directly.</summary>
/// <param name="wh">The native pointer to be wrapped.</param>
private IPlayableConcrete(Efl.Eo.Globals.WrappingHandle wh) : base(wh)
{
}
/// <summary>Get the length of play for the media file.</summary>
/// <returns>The length of the stream in seconds.</returns>
public double GetLength() {
var _ret_var = Efl.IPlayableConcrete.NativeMethods.efl_playable_length_get_ptr.Value.Delegate(this.NativeHandle);
Eina.Error.RaiseIfUnhandledException();
return _ret_var;
}
public bool GetPlayable() {
var _ret_var = Efl.IPlayableConcrete.NativeMethods.efl_playable_get_ptr.Value.Delegate(this.NativeHandle);
Eina.Error.RaiseIfUnhandledException();
return _ret_var;
}
/// <summary>Get whether the media file is seekable.</summary>
/// <returns><c>true</c> if seekable.</returns>
public bool GetSeekable() {
var _ret_var = Efl.IPlayableConcrete.NativeMethods.efl_playable_seekable_get_ptr.Value.Delegate(this.NativeHandle);
Eina.Error.RaiseIfUnhandledException();
return _ret_var;
}
/// <summary>Get the length of play for the media file.</summary>
/// <value>The length of the stream in seconds.</value>
public double Length {
get { return GetLength(); }
}
public bool Playable {
get { return GetPlayable(); }
}
/// <summary>Get whether the media file is seekable.</summary>
/// <value><c>true</c> if seekable.</value>
public bool Seekable {
get { return GetSeekable(); }
}
private static IntPtr GetEflClassStatic()
{
return Efl.IPlayableConcrete.efl_playable_interface_get();
}
/// <summary>Wrapper for native methods and virtual method delegates.
/// For internal use by generated code only.</summary>
public new class NativeMethods : Efl.Eo.EoWrapper.NativeMethods
{
private static Efl.Eo.NativeModule Module = new Efl.Eo.NativeModule( efl.Libs.Efl);
/// <summary>Gets the list of Eo operations to override.</summary>
/// <returns>The list of Eo operations to be overload.</returns>
public override System.Collections.Generic.List<Efl_Op_Description> GetEoOps(System.Type type)
{
var descs = new System.Collections.Generic.List<Efl_Op_Description>();
var methods = Efl.Eo.Globals.GetUserMethods(type);
if (efl_playable_length_get_static_delegate == null)
{
efl_playable_length_get_static_delegate = new efl_playable_length_get_delegate(length_get);
}
if (methods.FirstOrDefault(m => m.Name == "GetLength") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_playable_length_get"), func = Marshal.GetFunctionPointerForDelegate(efl_playable_length_get_static_delegate) });
}
if (efl_playable_get_static_delegate == null)
{
efl_playable_get_static_delegate = new efl_playable_get_delegate(playable_get);
}
if (methods.FirstOrDefault(m => m.Name == "GetPlayable") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_playable_get"), func = Marshal.GetFunctionPointerForDelegate(efl_playable_get_static_delegate) });
}
if (efl_playable_seekable_get_static_delegate == null)
{
efl_playable_seekable_get_static_delegate = new efl_playable_seekable_get_delegate(seekable_get);
}
if (methods.FirstOrDefault(m => m.Name == "GetSeekable") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_playable_seekable_get"), func = Marshal.GetFunctionPointerForDelegate(efl_playable_seekable_get_static_delegate) });
}
return descs;
}
/// <summary>Returns the Eo class for the native methods of this class.</summary>
/// <returns>The native class pointer.</returns>
public override IntPtr GetEflClass()
{
return Efl.IPlayableConcrete.efl_playable_interface_get();
}
#pragma warning disable CA1707, CS1591, SA1300, SA1600
private delegate double efl_playable_length_get_delegate(System.IntPtr obj, System.IntPtr pd);
public delegate double efl_playable_length_get_api_delegate(System.IntPtr obj);
public static Efl.Eo.FunctionWrapper<efl_playable_length_get_api_delegate> efl_playable_length_get_ptr = new Efl.Eo.FunctionWrapper<efl_playable_length_get_api_delegate>(Module, "efl_playable_length_get");
private static double length_get(System.IntPtr obj, System.IntPtr pd)
{
Eina.Log.Debug("function efl_playable_length_get was called");
var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj);
if (ws != null)
{
double _ret_var = default(double);
try
{
_ret_var = ((IPlayable)ws.Target).GetLength();
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
return _ret_var;
}
else
{
return efl_playable_length_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)));
}
}
private static efl_playable_length_get_delegate efl_playable_length_get_static_delegate;
[return: MarshalAs(UnmanagedType.U1)]
private delegate bool efl_playable_get_delegate(System.IntPtr obj, System.IntPtr pd);
[return: MarshalAs(UnmanagedType.U1)]
public delegate bool efl_playable_get_api_delegate(System.IntPtr obj);
public static Efl.Eo.FunctionWrapper<efl_playable_get_api_delegate> efl_playable_get_ptr = new Efl.Eo.FunctionWrapper<efl_playable_get_api_delegate>(Module, "efl_playable_get");
private static bool playable_get(System.IntPtr obj, System.IntPtr pd)
{
Eina.Log.Debug("function efl_playable_get was called");
var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj);
if (ws != null)
{
bool _ret_var = default(bool);
try
{
_ret_var = ((IPlayable)ws.Target).GetPlayable();
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
return _ret_var;
}
else
{
return efl_playable_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)));
}
}
private static efl_playable_get_delegate efl_playable_get_static_delegate;
[return: MarshalAs(UnmanagedType.U1)]
private delegate bool efl_playable_seekable_get_delegate(System.IntPtr obj, System.IntPtr pd);
[return: MarshalAs(UnmanagedType.U1)]
public delegate bool efl_playable_seekable_get_api_delegate(System.IntPtr obj);
public static Efl.Eo.FunctionWrapper<efl_playable_seekable_get_api_delegate> efl_playable_seekable_get_ptr = new Efl.Eo.FunctionWrapper<efl_playable_seekable_get_api_delegate>(Module, "efl_playable_seekable_get");
private static bool seekable_get(System.IntPtr obj, System.IntPtr pd)
{
Eina.Log.Debug("function efl_playable_seekable_get was called");
var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj);
if (ws != null)
{
bool _ret_var = default(bool);
try
{
_ret_var = ((IPlayable)ws.Target).GetSeekable();
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
return _ret_var;
}
else
{
return efl_playable_seekable_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)));
}
}
private static efl_playable_seekable_get_delegate efl_playable_seekable_get_static_delegate;
#pragma warning restore CA1707, CS1591, SA1300, SA1600
}
}
}
| 39.794224 | 242 | 0.639027 |
[
"Apache-2.0"
] |
sparrow74/TizenFX
|
internals/src/EflSharp/EflSharp/efl/efl_playable.eo.cs
| 11,023 |
C#
|
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace Tests.Sources
{
partial class TestMain
{
bool behave;
public TestMain(bool behave)
{
this.behave = behave;
}
public static int Main()
{
try
{
PositiveTest();
NegativeTest();
return 0;
}
catch (Exception e)
{
Console.WriteLine("{0} {1}", e.Message, e.StackTrace);
return -1;
}
}
partial void Run();
static void PositiveTest()
{
try
{
var t = new TestMain(true);
t.Run();
}
catch(Exception e)
{
Console.WriteLine();
Console.WriteLine("Positive test failed.");
Console.WriteLine("Error: " + e);
Console.WriteLine();
throw;
}
}
static void NegativeTest()
{
var t = new TestMain(false);
try
{
#if NETFRAMEWORK_4_5 || NETFRAMEWORK_4_0
try {
t.Run();
}
catch (AggregateException ae) {
throw ae.Flatten().InnerException;
}
#else
t.Run();
#endif
throw new Exception("Expected failure did not happen");
}
catch (TestInfrastructure.RewriterMethods.ContractException e)
{
TestInfrastructure.Assert.AreEqual(t.NegativeExpectedKind, e.Kind);
TestInfrastructure.Assert.AreEqual(t.NegativeExpectedCondition, e.Condition);
}
catch (ArgumentException e)
{
TestInfrastructure.Assert.AreEqual(t.NegativeExpectedKind, ContractFailureKind.Precondition);
TestInfrastructure.Assert.AreEqual(t.NegativeExpectedCondition, e.Message);
}
}
}
}
namespace TestInfrastructure
{
class Assert
{
public static void AreEqual(object expected, object actual)
{
if (object.Equals(expected, actual)) return;
var result = String.Format("Expected: '{0}', Actual: '{1}'", expected, actual);
Console.WriteLine(result);
throw new Exception(result);
}
}
public class RewriterMethods
{
public static void Requires(bool condition, string userMsg, string conditionText)
{
if (!condition)
{
RaiseContractFailedEvent(System.Diagnostics.Contracts.ContractFailureKind.Precondition, userMsg, conditionText, null);
throw new PreconditionException(userMsg, conditionText);
}
}
#if false
public static void Requires<E>(bool condition, string userMessage, string conditionText)
where E:Exception
{
if (condition) return;
string msg = RaiseContractFailedEvent(System.Diagnostics.Contracts.ContractFailureKind.Precondition, userMessage, conditionText, null);
if (conditionText != null)
{
if (userMessage != null)
{
msg = conditionText + " required: " + userMessage;
}
else
{
msg = conditionText + " required";
}
}
else
{
msg = userMessage;
}
var ci = typeof(E).GetConstructor(new []{typeof(String)});
Exception obj = null;
if (ci != null)
{
obj = ci.Invoke(new []{msg}) as Exception;
}
if (obj != null) { throw obj; }
throw new ArgumentException(msg);
}
#endif
public static void Ensures(bool condition, string userMsg, string conditionText) {
if (!condition) throw new PostconditionException(userMsg, conditionText);
}
public static void EnsuresOnThrow(bool condition, string userMsg, string conditionText, Exception e)
{
if (!condition)
{
RaiseContractFailedEvent(System.Diagnostics.Contracts.ContractFailureKind.PostconditionOnException, userMsg, conditionText, e);
throw new PostconditionOnThrowException(userMsg, conditionText);
}
}
public static void Invariant(bool condition, string userMsg, string conditionText)
{
if (!condition)
{
RaiseContractFailedEvent(System.Diagnostics.Contracts.ContractFailureKind.Invariant, userMsg, conditionText, null);
throw new InvariantException(userMsg, conditionText);
}
}
public static void Assert(bool condition, string userMsg, string conditionText)
{
if (!condition)
{
RaiseContractFailedEvent(System.Diagnostics.Contracts.ContractFailureKind.Assert, userMsg, conditionText, null);
throw new AssertException(userMsg, conditionText);
}
}
public static void Assume(bool condition, string userMsg, string conditionText)
{
if (!condition)
{
RaiseContractFailedEvent(System.Diagnostics.Contracts.ContractFailureKind.Assume, userMsg, conditionText, null);
throw new AssumeException(userMsg, conditionText);
}
}
public static int FailureCount = 0;
public static string RaiseContractFailedEvent(System.Diagnostics.Contracts.ContractFailureKind kind, string user, string condition, Exception inner)
{
FailureCount++;
if (condition != null)
{
if (user != null)
{
return String.Format("{0} failed: {1}: {2}", kind, condition, user);
}
else
{
return String.Format("{0} failed: {1}", kind, condition);
}
}
else
{
if (user != null)
{
return String.Format("{0} failed: {1}", kind, user);
}
else
{
return String.Format("{0} failed.", kind);
}
}
}
public static void TriggerFailure(System.Diagnostics.Contracts.ContractFailureKind kind, string message, string user, string condition, Exception inner)
{
switch (kind)
{
case System.Diagnostics.Contracts.ContractFailureKind.Assert:
throw new AssertException(user, condition);
case System.Diagnostics.Contracts.ContractFailureKind.Assume:
throw new AssumeException(user, condition);
case System.Diagnostics.Contracts.ContractFailureKind.Invariant:
throw new InvariantException(user, condition);
case System.Diagnostics.Contracts.ContractFailureKind.Postcondition:
throw new PostconditionException(user, condition);
case System.Diagnostics.Contracts.ContractFailureKind.PostconditionOnException:
throw new PostconditionOnThrowException(user, condition);
case System.Diagnostics.Contracts.ContractFailureKind.Precondition:
throw new PreconditionException(user, condition);
}
}
#region Exceptions
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public abstract class ContractException : Exception
{
public readonly System.Diagnostics.Contracts.ContractFailureKind Kind;
public readonly string User;
public readonly string Condition;
//protected ContractException() : this("Contract failed.") { }
//protected ContractException(string message) : base(message) { }
//protected ContractException(string message, Exception inner) : base(message, inner) { }
public ContractException(ContractFailureKind kind, string user, string cond)
: base(user + ": " + cond)
{
this.Kind = kind;
this.User = user;
this.Condition = cond;
}
#if FEATURE_SERIALIZATION
#if !MIDORI
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
#endif
protected ContractException (SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class AssertException : ContractException
{
#if false
public AssertException() : this("Assertion failed.") { }
public AssertException(string message) : base(message) { }
public AssertException(string message, Exception inner) : base(message, inner) { }
#endif
public AssertException(string user, string cond) : base(ContractFailureKind.Assert, user, cond) { }
#if FEATURE_SERIALIZATION
private AssertException (SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class AssumeException : ContractException
{
#if falsen
public AssumeException() : this("Assumption failed.") { }
public AssumeException(string message) : base(message) { }
public AssumeException(string message, Exception inner) : base(message, inner) { }
#endif
public AssumeException(string user, string cond) : base(ContractFailureKind.Assume, user, cond) { }
#if FEATURE_SERIALIZATION
private AssertException (SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class PreconditionException : ContractException
{
#if false
public PreconditionException() : this("Precondition failed.") { }
public PreconditionException(string message) : base(message) { }
public PreconditionException(string message, Exception inner) : base(message, inner) { }
#endif
public PreconditionException(string user, string cond) : base(ContractFailureKind.Precondition, user, cond) { }
#if FEATURE_SERIALIZATION
private PreconditionException (SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class PostconditionException : ContractException
{
#if false
public PostconditionException() : this("Postcondition failed.") { }
public PostconditionException(string message) : base(message) { }
public PostconditionException(string message, Exception inner) : base(message, inner) { }
#endif
public PostconditionException(string user, string cond) : base(ContractFailureKind.Postcondition, user, cond) { }
#if FEATURE_SERIALIZATION
private PostconditionException (SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class PostconditionOnThrowException : ContractException
{
#if false
public PostconditionOnThrowException() : this("Postcondition on Exception failed.") { }
public PostconditionOnThrowException(string message) : base(message) { }
public PostconditionOnThrowException(string message, Exception inner) : base(message, inner) { }
#endif
public PostconditionOnThrowException(string user, string cond) : base(ContractFailureKind.PostconditionOnException, user, cond) { }
#if FEATURE_SERIALIZATION
private PostconditionOnThrowException (SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public sealed class InvariantException : ContractException
{
#if false
public InvariantException() { }
public InvariantException(string message) : base(message) { }
public InvariantException(string message, Exception inner) : base(message, inner) { }
#endif
public InvariantException(string user, string cond) : base(ContractFailureKind.Invariant, user, cond) { }
#if FEATURE_SERIALIZATION
private InvariantException (SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
}
#endregion Exceptions
}
}
| 34.191257 | 463 | 0.689148 |
[
"MIT"
] |
Acidburn0zzz/CodeContracts
|
Foxtrot/Tests/Sources/TestHarness.cs
| 12,514 |
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Northwind.Perf;
using ServiceStack.Logging;
using ServiceStack.OrmLite.TestsPerf.Scenarios.Northwind;
using ServiceStack.OrmLite.TestsPerf.Scenarios.OrmLite;
namespace ServiceStack.OrmLite.TestsPerf
{
class Program
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
const long DefaultIterations = 1;
static readonly List<long> BatchIterations = new List<long> { 100, 1000, 5000, 20000, /*100000, 250000, 1000000, 5000000*/ };
//static readonly List<long> BatchIterations = new List<long> { 1, 10, 100 };
static List<DatabaseScenarioBase> GetUseCases()
{
return new List<DatabaseScenarioBase>
{
//new InsertModelWithFieldsOfDifferentTypesPerfScenario(),
//new InsertSampleOrderLineScenario(),
//new SelectOneModelWithFieldsOfDifferentTypesPerfScenario(),
//new SelectOneSampleOrderLineScenario(),
//new SelectManyModelWithFieldsOfDifferentTypesPerfScenario(),
//new SelectManySampleOrderLineScenario(),
new InsertNorthwindDataScenario(),
};
}
static void Main(string[] args)
{
try
{
foreach (var configRun in OrmLiteScenrioConfig.DataProviderConfigRuns())
{
Console.WriteLine("\n\nStarting config run {0}...", configRun);
if (args.Length == 1 && args[0] == "csv")
RunBatch(configRun);
else
RunInteractive(configRun, args);
}
Console.ReadKey();
}
catch (Exception ex)
{
Log.Error("Error running perfs", ex);
throw;
}
}
private static void RunBatch(OrmLiteConfigRun configRun)
{
Console.Write(";");
var useCases = GetUseCases();
useCases.ForEach(uc => Console.Write("{0};", uc.GetType().Name));
Console.WriteLine();
BatchIterations.ForEach(iterations => {
Console.Write("{0};", iterations);
useCases.ForEach(uc => {
configRun.Init(uc);
// warmup
uc.Run();
GC.Collect();
Console.Write("{0};", Measure(uc.Run, iterations));
});
Console.WriteLine();
});
}
private static void RunInteractive(OrmLiteConfigRun configRun, string[] args)
{
long iterations = DefaultIterations;
if (args.Length != 0)
iterations = long.Parse(args[0]);
Console.WriteLine("Running {0} iterations for each use case.", iterations);
var useCases = GetUseCases();
useCases.ForEach(uc => {
configRun.Init(uc);
// warmup
uc.Run();
GC.Collect();
var avgMs = Measure(uc.Run, iterations);
Console.WriteLine("{0}: Avg: {1}ms", uc.GetType().Name, avgMs);
});
}
private static decimal Measure(Action action, decimal iterations)
{
GC.Collect();
var stopWatch = new Stopwatch();
stopWatch.Start();
var begin = stopWatch.ElapsedMilliseconds;
for (var i = 0; i < iterations; i++)
{
action();
}
var end = stopWatch.ElapsedMilliseconds;
return (end - begin) / iterations;
}
}
}
| 24.633333 | 127 | 0.670162 |
[
"BSD-3-Clause"
] |
augustoproiete-forks/ServiceStack--ServiceStack.OrmLite
|
tests/ServiceStack.OrmLite.TestsPerf/Program.cs
| 2,958 |
C#
|
using System.Collections.Generic;
using System.Text.Json;
using FluentAssertions;
using Xunit;
namespace Sandra.Templating.Tests.Templates
{
public class SystemTextJsonBugTests
{
[Fact]
public void Deserialized_Json_Should_Allow_Boolean_Checks_For_Iif()
{
var jsonDictionary = @"{
""BooleanTrue"": true
}";
var data = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonDictionary, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
var template = "[iif BooleanTrue?'Hello World':'fail']";
var result = new TemplateEngine().Render(template, data!);
result.Should().Be("Hello World");
}
[Fact]
public void Deserialized_Json_Should_Allow_Boolean_Checks_For_If()
{
var jsonDictionary = @"{
""BooleanTrue"": true
}";
var data = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonDictionary, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
var template = "[if BooleanTrue]This should render[end if]";
var result = new TemplateEngine().Render(template, data!);
result.Should().Be("This should render");
}
}
}
| 28.041667 | 119 | 0.609212 |
[
"MIT"
] |
Sandra/Sandra.Templating
|
tests/Sandra.Templating.Tests/SystemTextJsonBooleanBugTests.cs
| 1,346 |
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBody.cs.tt
namespace Microsoft.Graph
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
/// <summary>
/// The type WorkbookFunctionsTimevalueRequestBody.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class WorkbookFunctionsTimevalueRequestBody
{
/// <summary>
/// Gets or sets TimeText.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "timeText", Required = Newtonsoft.Json.Required.Default)]
public Newtonsoft.Json.Linq.JToken TimeText { get; set; }
}
}
| 35.606061 | 153 | 0.600851 |
[
"MIT"
] |
DamienTehDemon/msgraph-sdk-dotnet
|
src/Microsoft.Graph/Generated/model/WorkbookFunctionsTimevalueRequestBody.cs
| 1,175 |
C#
|
using System;
using System.IO;
using System.Threading.Tasks;
using DataContract;
using Microsoft.Extensions.DependencyInjection;
using NetRpc;
using Helper = TestHelper.Helper;
namespace Client
{
internal class Program
{
private static IClientProxy<IServiceAsync> _c1;
private static IClientProxy<IService2Async> _c2;
private static async Task Main(string[] args)
{
await RabbitMQ();
await Grpc();
await Http();
Console.WriteLine("\r\n--------------- End ---------------");
Console.Read();
}
private static async Task RabbitMQ()
{
//RabbitMQ
Console.WriteLine("\r\n--------------- Client RabbitMQ ---------------");
var services = new ServiceCollection();
services.AddNClientContract<IServiceAsync>();
services.AddNClientContract<IService2Async>();
services.AddNRabbitMQClient(o => o.CopyFrom(Helper.GetMQOptions()));
var sp = services.BuildServiceProvider();
_c1 = sp.GetService<IClientProxy<IServiceAsync>>();
_c2 = sp.GetService<IClientProxy<IService2Async>>();
await TestAsync();
}
private static async Task Grpc()
{
Console.WriteLine("\r\n--------------- Client Grpc ---------------");
var services = new ServiceCollection();
services.AddNClientContract<IServiceAsync>();
services.AddNClientContract<IService2Async>();
services.AddNGrpcClient(o => o.Url = "http://localhost:50000");
var sp = services.BuildServiceProvider();
_c1 = sp.GetService<IClientProxy<IServiceAsync>>();
_c2 = sp.GetService<IClientProxy<IService2Async>>();
await TestAsync();
}
private static async Task Http()
{
Console.WriteLine("\r\n--------------- Client Http ---------------");
var services = new ServiceCollection();
services.AddNClientContract<IServiceAsync>();
services.AddNClientContract<IService2Async>();
services.AddNHttpClient(o =>
{
o.SignalRHubUrl = "http://localhost:5000/callback";
o.ApiUrl = "http://localhost:5000/api";
});
var sp = services.BuildServiceProvider();
_c1 = sp.GetService<IClientProxy<IServiceAsync>>();
_c2 = sp.GetService<IClientProxy<IService2Async>>();
await TestAsync();
}
private static async Task TestAsync()
{
await Test_Call();
await Test_Call2();
await Test_ComplexCallAsync();
}
private static async Task Test_Call()
{
Console.Write("[Call]...Send 123...");
_c1.AdditionHeader.Add("k1", "k1 value");
await _c1.Proxy.Call("123");
Console.WriteLine("end.");
}
private static async Task Test_Call2()
{
Console.Write("[Call2]...Send 123...");
await _c2.Proxy.Call2("123");
Console.WriteLine("end.");
}
private static async Task Test_ComplexCallAsync()
{
using (var stream = File.Open(Helper.GetTestFilePath(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
Console.Write("[ComplexCallAsync]...Send TestFile.txt...");
var complexStream = await _c1.Proxy.ComplexCallAsync(
new CustomObj {Date = DateTime.Now, Name = "ComplexCall"},
stream,
async i => Console.Write(", " + i.Progress),
default);
using (var stream2 = complexStream.Stream)
Console.Write($", receive length:{stream.Length}, {Helper.ReadStr(stream2)}");
Console.WriteLine($", otherInfo:{complexStream.OtherInfo}");
}
}
}
}
| 36.825688 | 121 | 0.544594 |
[
"MIT"
] |
NameIsBad/NetRpc
|
samples/Gateway/Client/Program.cs
| 4,016 |
C#
|
/*******************************************************************************
* Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Gives you information about your VPN gateways.
/// </summary>
/// <remarks>
/// You can filter the results to return information
/// only about VPN gateways that match criteria you specify. For example,
/// you could ask to get information about a particular VPN gateway (or all) only
/// if the gateway's state is pending or available. You can specify
/// multiple filters (e.g., the VPN gateway is in a particular
/// Availability Zone and the gateway's state is pending or available).
/// The result includes information for a particular VPN gateway only if
/// the gateway matches all your filters. If there's no match, no
/// special message is returned; the response is simply empty.
///
/// The returned information consists of:
///
/// 1. The VPN gateway ID - The current state of the VPN gateway
/// (pending, available, deleting, deleted)
/// 2. The type of VPN connection the VPN gateway supports.
/// 3. The Availability Zone where the VPN gateway was created.
/// 4. The VPCs the VPN gateway is attached to and the state of each
/// attachment (attaching, attached, detaching, detached)
/// </remarks>
[XmlRootAttribute(IsNullable = false)]
public class DescribeVpnGatewaysRequest : EC2Request
{
private List<string> vpnGatewayIdField;
private List<Filter> filterField;
/// <summary>
/// One or more VPN gateway IDs.
/// </summary>
[XmlElementAttribute(ElementName = "VpnGatewayId")]
public List<string> VpnGatewayId
{
get
{
if (this.vpnGatewayIdField == null)
{
this.vpnGatewayIdField = new List<string>();
}
return this.vpnGatewayIdField;
}
set { this.vpnGatewayIdField = value; }
}
/// <summary>
/// Sets VPN gateway IDs.
/// </summary>
/// <param name="list">A VPN gateway ID.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeVpnGatewaysRequest WithVpnGatewayId(params string[] list)
{
foreach (string item in list)
{
VpnGatewayId.Add(item);
}
return this;
}
/// <summary>
/// Checks if VpnGatewayId property is set
/// </summary>
/// <returns>true if VpnGatewayId property is set</returns>
public bool IsSetVpnGatewayId()
{
return (VpnGatewayId.Count > 0);
}
/// <summary>
/// The filter to apply on the results of DescribeVpnGateways.
/// Filters can be:
/// a. state - The state of the VPN gateway. (pending, available, deleting, deleted).
/// b. type - The type of VPN gateway. Currently the only supported type is ipsec.1.
/// c. availabilityZone - The Availability Zone the VPN gateway is in.
/// </summary>
[XmlElementAttribute(ElementName = "Filter")]
public List<Filter> Filter
{
get
{
if (this.filterField == null)
{
this.filterField = new List<Filter>();
}
return this.filterField;
}
set { this.filterField = value; }
}
/// <summary>
/// Sets the filter to apply on the results of DescribeVpnGateways.
/// </summary>
/// <param name="list">The filter to apply on the results of DescribeVpnGateways. Filters
/// can be:
/// a. state - The state of the VPN gateway. (pending, available, deleting, deleted).
/// b. type - The type of VPN gateway. Currently the only supported type is ipsec.1.
/// c. availabilityZone - The Availability Zone the VPN gateway is in.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeVpnGatewaysRequest WithFilter(params Filter[] list)
{
foreach (Filter item in list)
{
Filter.Add(item);
}
return this;
}
/// <summary>
/// Checks if Filter property is set
/// </summary>
/// <returns>true if Filter property is set</returns>
public bool IsSetFilter()
{
return (Filter.Count > 0);
}
}
}
| 38.825503 | 177 | 0.576664 |
[
"Apache-2.0"
] |
jdluzen/aws-sdk-net-android
|
AWSSDK/Amazon.EC2/Model/DescribeVpnGatewaysRequest.cs
| 5,785 |
C#
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Rsk.Samples.IdentityServer4.SharePointIntegration
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddIdentityServer()
.AddSigningCredential("CN=ScottBrady91")
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers())
.AddWsFederation()
.AddInMemoryRelyingParties(Config.GetRelyingParties());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDeveloperExceptionPage();
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
| 31.088235 | 109 | 0.654683 |
[
"MIT"
] |
RockSolidKnowledge/Samples.IdentityServer4.SharePointIntegration
|
Rsk.Samples.IdentityServer4.SharePointIntegration/Startup.cs
| 1,059 |
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.